Asked  7 Months ago    Answers:  5   Viewed   124 times

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?

 Answers

75

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"}
Tuesday, June 1, 2021
 
QuantumMechanic
answered 7 Months ago
29

Here's an example from Encosia.com (I added a form parameter). You don't need to access Page.Form - you can use method parameters instead.

Codebehind

public partial class _Default : Page 
{
  [WebMethod]
  public static string GetDate(string someParameter)
  {
    return DateTime.Now.ToString();
  }
}

Javascript

$(document).ready(function() {
  // Add the page method call as an onclick handler for the div.
  $("#Result").click(function() {
    $.ajax({
      type: "POST",
      url: "Default.aspx/GetDate",
      data: {someParameter: "some value"},
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        // Replace the div's content with the page method's return.
        $("#Result").text(msg.d);
      }
    });
  });
});
Wednesday, August 11, 2021
 
employeegts
answered 4 Months ago
100

Thanks for all of your responses.

Today i got the answer after googling for more than 1 hr.

Things i learned is while sending json data using stringfy() method, in server side we need to define the parameter as object. not any other format like string/int/bla bla.....

Actually there was a mistake on my Server side parameter.I modified it from string to object and it worked for me. Here i have defined my modified answer.

        $('#btnResult').on('click', function () {

        var mydata = [];
        $("#<%=GridProjectDetails.ClientID %>  tr").each(function () {
            var myObject = new Object();
            var id = $(this).find("input[name*='ID']").val();
            var locationcode = $(this).find("input[name*='TextLocationCode']").val();
            var Location = $(this).find("input[name*='TextLocation']").val();
            myObject.id = id;
            myObject.locationcode = locationcode;
            myObject.Location = Location;
            mydata.push(myObject);
        });

        var myString = JSON.stringify({ details: JSON.stringify(mydata) });
        alert(myString);
        var exportdata = myString;

        $.ajax({
            type: "POST",
            url: "Default.aspx/ExportToExcel",
            data: exportdata,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $("#Result").text(data.d);
            },
            error: function () { alert(arguments[2]); }
        });
    });
});

and my server side method should be

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string ExportToExcel(object details)
{

    return "Message : Success";
}
Sunday, August 29, 2021
 
Usman Khan
answered 3 Months ago
65

The response is:

Content-Type:application/json
["Asset","AssetElementDefMap",…,"WorkingSet"]

That's no JSONP script, but plain JSON (the "padding", ie. the callback function, is missing). Since the request is cross-domain, you're not allowed to access it - and executing it as a script fails even when the resource loads with a 200 OK status.

Tuesday, August 31, 2021
 
Lasse Edsvik
answered 3 Months ago
31

Cross-domain requests are not directly allowed. However, there is a commonly-used technique called JSONP that will allow you to avoid this restriction through the use of script tags. Basically, you create a callback function with a known name:

function receiveData(data) {
    // ...
}

And then your server wraps JSON data in a function call, like this:

receiveData({"the": "data"});

And you "call" the cross-domain server by adding a script tag to your page. jQuery elegantly wraps all of this up in its ajax function.

Another technique that I've had to use at times is cross-document communication through iframes. You can have one window talk to another, even cross-domain, in a restricted manner through postMessage. Note that only recent browsers have this functionality, so that option is not viable in all cases without resorting to hackery.

Monday, November 15, 2021
 
mkl
answered 3 Weeks ago
mkl
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share