How can I call a function C# (server side) function in a Javascript function (client side) which triggers the browser is closed? as:
window.onbeforeclose = MyFunction() // C#
You can not call your server side function from client side , You will need to decorate your C# method with Web Method attribute and make it static to expose it as a callable AJAX member:
something like
[WebMethod]
public static void someCSharpFunction() {
// body of function
}
and in your client side
$.ajax({
type: "POST",
url: "SomePage.aspx/someCSharpFunction",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Hope that helps.
If you are looking to call a server side (c#) method from JavaScript, there are few ways to interact with server side through client side(Javascript):
XMLHttpRequest
Callback
WebService call
PageMethod
Related
I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}
Basically I have a C# web service method that helps to generate HTML code and return it as a string. Now I would like to grab the HTML string from this method and replace a particular div.
function replaceHTML(ID) {
var gID = ID;
$.ajax({
type: "get",
contentType: //what should it be,
url: "the method location",
data: {"ID" : gID },
dataType: //what should it be,
success: function (data) {
$('#Div ID').empty();
$('#Div ID').html(data);
}
});
}
What should be the content Type and data Type? Am I doing it correctly?
Well it all depends on what your web service is providing you and since we cannot see the web service call, we cannot tell you.
In every average web service it should be specified what type of data it communicates with, whether json, xml, or plain text.
Usually though, it will be xml unless something else is specified because web services are SOAP based and are xml formatted, but you should check your web service or share it's code with us.
contentType is the type of data you send to the server, so it'll be application/json in your case. Not nessecary to provide that info though, jQuery will detect it based on the contents of data.
dataType is the type you expect the server to return, so you set it to text/html.
Also, see:
http://api.jquery.com/jquery.ajax/
Hope this will work for you :).
function replaceHTML(ID) {
var gID = ID;
$.ajax({
type: "get",
contentType: 'text',//what should it be,
url: "the method location",
data: JSON.stringify({"ID" : gID }),
dataType: "application/json; charset=utf-8",,
success: function (data) {
$('#Div ID').empty();
$('#Div ID').html(data);
}
}
I'm trying to do something that's very new to me. I've done some digging but what I've come up with only had solutions by using some kind of .aspx page to process forms.
What I'd like to do is send some form input via ajax (I'm using jquery) to the server to be processed by c#.
This is, I believe, a fairly general question. It doesn't have to do with submitting form input specifically, but more about how to send some data to be processed by c# in the backend.
I want to make an ajax POST to a certain page for processing such as this:
$.ajax({
type: "POST",
url: "****???****",
data: { name: "Bob", gender: "Male" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var names = response.d;
alert(names);
}
});
Now, my question is, what kind of file/page can I use for the url value in the above ajax call, that will be able to handle the POSTed data using c#?
All the examples I've seen use a .aspx page that processes the form and sends it to a .cs code-behind page. If possible, I'd like to be able to use something other than an .aspx page.
The site I'm working on is using just HTML as I'm working with angular. Is there any other way I can handle ajax on the server in a way that I can use c#?
To be very specific, I'm trying to setup a registration page where a user puts in their username and password. I need the password to be sent to the server to have a hash and salt created in C#.
Thanks, and please let me know if you need any additional information to continue.
Try this
In code behind file:Default.aspx.cs
[WebMethod]
public static void GenerateHash(string name,string password)
{
//Write logic to generate hash
}
.aspx page
$.ajax({
type: "POST",
url: "Default.aspx/GenerateHash",
data: { name: "xxx", password: "xxxx" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var names = response.d;
alert(names);
}
});
I am accessing a cross domain api using jquery ajax but I can't achieve it . Iam getting error as "uncaught syntaxerror : unexpected token <" in the console, How to fix this.
Code:
$.ajax({
url: "http://..............",
type:"GET",
dataType: 'jsonp',
crossDomain: true,
contentType:"application/javascript",
success: function (data) {
alert(data);
},
error: function (errorMEssage, Errtext) {
alert(Errtext);
}
});
Error:
uncaught syntaxerror : unexpected token <
You cannot make cross domain AJAX calls using JSONP to a server that returns XML. If you want to be able to make a cross domain AJAX call you have 2 possibilities:
use JSONP -> your server needs to support it.
use CORS -> your server AND client browser need t support it.
If your server supports CORS your request may look like this:
$.ajax({
url: "http://..............",
type:"GET",
crossDomain: true,
success: function (data) {
alert(data);
},
error: function (errorMEssage, Errtext) {
alert(Errtext);
}
});
change the dataType to xml
dataType: 'xml',
Currently, I am working on Asp.net 3.5 project and I am calling a Webservice by ajax call
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "WebService/DefaultPage.asmx/GetTours",
dataType: "json",
success: function (data) {
Home.ReadTours(data);
},
error: function (result) {
$('.load-3').hide();
}
});
working fine.
but when I change the URL to lowercase.
url: "webservice/defaultpage.asmx/gettours",
its not working.
Is this Jquery Ajax URL is case sensitive and is there any by I can ignore case sensitiveness of ajax URL.
Your server fielding the ajax request will need to be configured to NOT be case sensitive. There is nothing you can do in the client to change case sensitivity of a server (other than providing the case that the server expects).