1

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
Beginner
  • 28,539
  • 63
  • 155
  • 235
  • try console.log(msg) to see the error object – Mirko Akov Jan 16 '12 at 14:08
  • alert('Failure: ' + msg); is concatenating the msg object. Maybe try to do console.log(msg); and see what the error message contains? – Aram Kocharyan Jan 16 '12 at 14:08
  • 2
    you'll get sql injections by making queries this way. – WoLfulus Jan 16 '12 at 14:11
  • *"Now all of a sudden the post functions seem to have stopped working?"* What did you change just before it stopped working? *Something* had to change. – T.J. Crowder Jan 16 '12 at 14:12
  • i have put the log into my question?? – Beginner Jan 16 '12 at 14:12
  • It's difficult to say from the info provided. Narrow it down by using FireBug and seeing what (if anything) is getting sent to the server. If that looks correct, breakpoint the method on the server and step through what's happening there. It's all about narrowing it down and slowly and methodically eliminating possibles. – DavidGouge Jan 16 '12 at 14:13
  • 2
    Side point: Your `DeleteRow` server-side function is wide open to [SQL Injection attacks](http://en.wikipedia.org/wiki/SQL_injection). See the link for how to fix it. – T.J. Crowder Jan 16 '12 at 14:13

4 Answers4

3

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.

Joe
  • 80,724
  • 18
  • 127
  • 145
  • 1
    still not quite right it should remove the double quote after the OrderNo and LineNo variables. ATM you have it wrapping the two parameter names in double quotes and the actually values just have a double quote after them. Either they should be before and after it to make it a string or neither so its a number – Steve Jan 16 '12 at 14:18
  • 1
    @Steve, I've updated. Thanks for finding that. I still think the downvote was a little harsh though ;) – Joe Jan 16 '12 at 14:22
  • I did too.. but then I wanted to remove the down vote and it wouldn't let me... it was either a + or a - ... now you have fixed it, ive up voted it! – Steve Jan 16 '12 at 17:13
1

PHP devs (like me) who deal with jQuery, Ajax and other frontend technologies: "Suddenly not working" could mean that you added some debugging, some "echos" (PHP wrong way of debugging) and you forgot to check the entire stack in order of removing it. That debugging code you let there will cost long painful days of reviews and tests. Have you ever considered that? Follow these steps:

0 - (Please: Developers start counting from zero) - Directly call backend using URL only, whenever possible, instead of using ajax. You can grab a testing tool like these ones QA guys use - and we should get used on them too - there are many. Grow up. Go find one. Talk to QA guys. Do something. Now! :-)! Look at what you received: is it a valid JSON? Is it a valid XML? Is it a valid JSON/XML plus something that should not be there? Is it a valid JSON/XML but not the one you expected to receive? Probably this step is enough.

1 - Get used to the following useful ajax snippet (http://craigsworks.com/projects/forums/showthread.php?tid=3829) :

$.ajax({
  url: 'http://localhost/formengine/index.php?r=site/ajax',
  success: function(response) {
    console.log(response);
  }
});

2 - Test any other jQuery behavior instead of the one you are building. This step is just to make you feel better and recover that everyday rationality that pays your salary. jQuery, Ajax, PHP, .net stack, Java stack: they are friendly, nice and do want to be working for you. Sometimes it's just matter of handling head stuff: either an offline CDN, a URL that is wrong, source location may be wrong, these ordinary, everyday stuff. Place the CDN URL to the navigation bar: you shall be able to read the entire lib in your browser screen. Click on this: https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js

3 - In the deepest moment of your desperation, have you placed any alert somewhere where it's not legal? Do not say "no"! Go testing it: google chrome, F12, a developers perspective frame opens and at the top right you can see the smallest red flag ever - yes: the smallest. Hear the voices in your head: click on it. A meaningful message will appear. If it's the case, fix the issue.

4 - Drive all the necessary efforts towards having a well defined deploying process. Copying and pasting are not professional approaches - and, believe me, you are the most interested ones on doing things right. There are many "best practices" references regarding deploying, considering, of course, the technology stack you guys use: follow them.

Good Luck to you all! Hope it helps!

Farlon Souto
  • 116
  • 1
  • 6
1

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I will attempt to do all this but firs it need to just get it working how it was before i attempt to clean it – Beginner Jan 16 '12 at 14:54
  • @Beginner, this is what you need to implement. But if you really just want to get it to work once and then refactor. Fix your data string. Or simply change your data line to `JSON.stringify({ OrderNo: OrderNo, LineNo: LineNo }),` – Joe Jan 16 '12 at 15:45
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.

Nick Bork
  • 4,831
  • 1
  • 24
  • 25
  • yes i think that is the issue, but why is it returning the html now? it had been working fine before. Do u know how i could fix the issue – Beginner Jan 16 '12 at 14:23
  • I can only assume that the URL is incorrect or something else is intercepting your request before it gets to your WebMethod. – Nick Bork Jan 16 '12 at 14:25
  • Did you recently change the AJAX page from an ASMX (Webservice) to an ASPX (Webform)? I'm not an expert on Webforms but read this post: http://forums.asp.net/t/1423555.aspx/1 The claim is that you can't call the "DeleteRow" webmethod from your ASPX page. You can only do that if the WebMethod is in a Webservice (ASMX) – Nick Bork Jan 16 '12 at 14:33
  • i did hav a webservice but this has been working fine without being in a webservice – Beginner Jan 16 '12 at 14:55
  • The ScriptManager is what enables your WebMethods to be called. The poster was getting the same parser error you are getting in your output. See the following post for more information: http://stackoverflow.com/questions/2651091/jquery-ajax-call-to-httpget-webmethod-c-not-working – Nick Bork Jan 16 '12 at 15:14