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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.