Skip to main content

Jquery ajax functions stopped working



Ive been working on some jquery within a a page. Now all of a sudden the post functions seem to have stopped working?







function deleteRow(OrderNo, LineNo) {

alert(OrderNo + ";" + LineNo);

$.ajax({

type: "POST",

url: "Ajax.aspx/DeleteRow",

data: '{' + 'OrderNo:"' + OrderNo + '",' + 'LineNo:"' + LineNo + '"' +

'}',

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function (msg) {

//$("#item").val(msg);

var data = jQuery.parseJSON(msg);

if (!data.error) {

$('#' + LineNo).remove();

}

else {

alert("Error" + " " + data.error);

}

},

error: function (msg) {

alert('Failure: ' + msg);

}

});

}







This is a jquery function which gives an error back 'Failure [object Object]'





the function DeleteRow does exist in Ajax.aspx and does work. Cant understand why all of a sudden the post functions would stop working??







[WebMethod]

public static string DeleteRow(string OrderNo, string LineNo)

{

SqlConnection myConnection = new SqlConnection(connStr);

myConnection.Open();

//Check if param exisits

string SQLst = "Delete from Saved_Order_Import where [Order No] = '"+OrderNo+"' And [Line No] = '"+LineNo+"'";

try

{

SqlCommand myComman = new SqlCommand(SQLst, myConnection);

myComman.ExecuteNonQuery();

}

catch (Exception ex)

{

myConnection.Close();

return "{\"error\":\"Error Line Not Deleted" + ex.ToString() + "\"}";

}

myConnection.Close();

return "{\"Success\":\"Line Deleted\"}";

}







console log







abort: function ( statusText ) {

always: function () {

complete: function () {

done: function () {

error: function () {

fail: function () {

getAllResponseHeaders: function () {

getResponseHeader: function ( key ) {

isRejected: function () {

isResolved: function () {

overrideMimeType: function ( type ) {

pipe: function ( fnDone, fnFail ) {

promise: function ( obj ) {

readyState: 4

responseText:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">



<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1"><title>



</title></head>

<body>

<form name="form1" method="post" action="Ajax.aspx" id="form1">

<div>

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZAZAz479BJ9BS5KpwM0PauBgztmI" />

</div>



<div>

</div>

</form>

</body>

</html>

"

setRequestHeader: function ( name, value ) {

status: 200

statusCode: function ( map ) {

statusText: "parsererror"

success: function () {

then: function ( doneCallbacks, failCallbacks ) {

__proto__: Object




Comments

  1. Based on the response you posted, the server output was a HTTP Status 200 with a HTML Form as the response. Was this the desired format of the response?

    You're telling the AJAX function to parse the response as JSON but no JSON came back from the request. Look at your console log. The exception is a parser error.

    ReplyDelete
  2. You problem is on this line:

    '{' + 'OrderNo:"' + OrderNo + '",' + 'LineNo:"' + LineNo + '"' +
    '}',


    It should be like this:

    '{' + '"OrderNo":"' + OrderNo + '",' + '"LineNo":"' + LineNo + '"' +
    '}',


    Notice the missing opening " before OrderNo:" and before LineNo:". The fix will produce a valid JSON string:

    '{"OrderNo": "OrderNo Value", "LineNo": "LineNo Value"}'


    It's suprisingly uncommon the knowledge that those double quotes are required for valid JSON.

    ReplyDelete
  3. There are lots of improvements that could be brought to your code. I will try to cover at least some of them that are bugging me when hovering over your code at first sight.

    The first thing that worries me is that your page method returns a string, in which you are manually writing some JSON. That's something you should never do. You should never manually serialize/deserialize anything. In any language. Never. You can read the following article to understand why. Page methods can return strongly typed objects and the ASP.NET infrastructure will take care of properly serializing them into JSON so that you don't have to worry about it. So let's start by introducing a model that your page method could return:

    public class Result
    {
    public bool Success { get; set; }
    public string ErrorMessage { get; set; }
    }


    As you can see in this model we have a boolean variable indicating the success or failure of the page method and a string variable containing the error message in the event of failure.

    The next thing, and probably, the worst with your code, is the SQL injection vulnerability present in your ADO.NET snippet. Let's fix that by introducing parametrized queries and returning the model we have just defined:

    [WebMethod]
    public static Result DeleteRow(string OrderNo, string LineNo)
    {
    try
    {
    using (var myConnection = new SqlConnection(connStr))
    using (var myCommand = myConnection.CreateCommand())
    {
    myConnection.Open();
    myCommand.CommandText = "DELETE FROM Saved_Order_Import WHERE [Order No] = @OrderNo AND [Line No] = @LineNo";
    myCommand.Parameters.AddWithValue("@OrderNo", OrderNo);
    myCommand.Parameters.AddWithValue("@LineNo", LineNo);
    myCommand.ExecuteNonQuery();
    }
    }
    catch (Exception ex)
    {
    return new Result
    {
    Success = false,
    ErrorMessage = "Error Line Not Deleted" + ex.ToString()
    };
    }
    return new Result
    {
    Success = true
    };
    }


    The last step is to clean the client side code. Here you I would recommend you to use the JSON.stringify method to properly JSON serialize the javascript literal instead of using some string concatenations to manually build your JSON (read the article I have linked previously in my answer to understand why you should never manually serialize/deserialize anything => you should always use a proper qserializer for the given format).

    $.ajax({
    type: 'POST',
    url: 'Ajax.aspx/DeleteRow',
    data: JSON.stringify({ OrderNo: OrderNo, LineNo: LineNo }),
    contentType: 'application/json; charset=utf-8',
    success: function (msg) {
    // Notice how we use msg.d here. The ASP.NET Page Methods
    // infrastructure will JSON serialize the response using this property:
    // {"d":{"Success":"true"}}
    var data = msg.d;
    if (data.Success) {
    $('#' + LineNo).remove();
    }
    else {
    alert('Error ' + data.ErrorMessage);
    }
    },
    error: function (msg) {
    alert('Failure: ' + msg);
    }
    });


    Also make sure that you have enabled page methods in the script manager of your page:

    <asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true" />


    Remark: the JSON.stringify method is natively built-in modern browsers but if you need to support legacy browsers you could include the json2.js script to your page.

    ReplyDelete

Post a Comment

Popular posts from this blog

[韓日関係] 首相含む大幅な内閣改造の可能性…早ければ来月10日ごろ=韓国

div not scrolling properly with slimScroll plugin

I am using the slimScroll plugin for jQuery by Piotr Rochala Which is a great plugin for nice scrollbars on most browsers but I am stuck because I am using it for a chat box and whenever the user appends new text to the boxit does scroll using the .scrollTop() method however the plugin's scrollbar doesnt scroll with it and when the user wants to look though the chat history it will start scrolling from near the top. I have made a quick demo of my situation http://jsfiddle.net/DY9CT/2/ Does anyone know how to solve this problem?

Why does this javascript based printing cause Safari to refresh the page?

The page I am working on has a javascript function executed to print parts of the page. For some reason, printing in Safari, causes the window to somehow update. I say somehow, because it does not really refresh as in reload the page, but rather it starts the "rendering" of the page from start, i.e. scroll to top, flash animations start from 0, and so forth. The effect is reproduced by this fiddle: http://jsfiddle.net/fYmnB/ Clicking the print button and finishing or cancelling a print in Safari causes the screen to "go white" for a sec, which in my real website manifests itself as something "like" a reload. While running print button with, let's say, Firefox, just opens and closes the print dialogue without affecting the fiddle page in any way. Is there something with my way of calling the browsers print method that causes this, or how can it be explained - and preferably, avoided? P.S.: On my real site the same occurs with Chrome. In the ex