0

Hi I have the following AJAX which references a method in my .aspx page. I've done some console debugging and my data.d is always undefined. So I've put a breakpoint in the .aspx page on the first line of the method referenced and it never hits it.

I'm really stuck - so if someone could point me in the right direction that would be great.

AJAX:

var param = { "mySearchString": str };
$.ajax({
   type: 'POST',
   url: 'myForm.aspx/myMethod',
   data: JSON.stringify(param),
   contentType: 'application/json; charset=utf-8',
   dataType: 'json',
   async: false,
   success: function (data) {
        $("#MyResults").empty();
        console.log(data);
        console.log(data.d);
        console.log(data.d.length);
        for (i = 0; i < data.d.length; i++) {
            $("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
        }
        if (data.d.length == 0)
        {
          $("#MyResults").empty();
        }
    }
});

The initial set up for my .NET method:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public static IEnumerable<MyItem> myMethod(string searchString)
    {

I'm passing the right type across, and there are no errors on build or when I run it. So I'm a bit stumped!

Jeric Cruz
  • 1,899
  • 1
  • 14
  • 29
hlh3406
  • 1,382
  • 5
  • 29
  • 46
  • Doesn't look like your server returns anything ? – adeneo Oct 12 '16 at 13:26
  • Within my .NET method I have a call to a stored procedure and then I return the results of that - I can debug if the stored procedure is wrong, but I don't know why if I have a breakpoint in the method it never hits it? Is there something wrong with the way I'm referencing the method in ajax? 'url: 'myForm.aspx/myMethod'' – hlh3406 Oct 12 '16 at 13:28
  • 5
    var param = { "mySearchString": str }; try changing "mySearchString" to "searchString" so it matches the name in the c# method. – Paritosh Oct 12 '16 at 13:30
  • Start by removing `async:false`, you should never set that. Then make sure you return actual valid JSON from the server, as that's what you're expecting. If all else fails, add an `error` handler to that ajax request, and open your console. – adeneo Oct 12 '16 at 13:30
  • 1
    First confirm that your .NET code returning any response back to AJAX call, and also use data.responseText , to get response data – Affan Pathan Oct 12 '16 at 13:33
  • @Paritosh tried that now - still no luck :( – hlh3406 Oct 12 '16 at 13:33
  • @AffanPathan that seems to be the problem - getting an Authentication Failed error – hlh3406 Oct 12 '16 at 13:36
  • 1
    Try using PostMan or Fiddler and use that first to debug your .net code. Once you get that working move on to trying to get your jquery code's ajax call to work. This will help you isolate testing to only your .net code. Also you should share the rest of your .net class, any configuration you have with your web services. Finally try using a simple `HttpGet` method and call to see if you can get that to work and then work up to using HttpPost and then HttpPost with parameters. Im advocating for baby steps, start small and build up so you can rule out where the problem lies. – Igor Oct 12 '16 at 13:38
  • @Igor - thanks that's exactly what I'm going to do! :) – hlh3406 Oct 12 '16 at 13:40

7 Answers7

1

Try adding this as part of the signature

[HttpPost]
Neo
  • 3,309
  • 7
  • 35
  • 44
1

Add this to your ajax call to see more about the error:

 error: function (request, status, error) {
                    alert('Error: ' + error);
                }

Is this an MVC application? Should the url actually be myForm.aspx/myMethod or just myForm/myMethod? What I am getting at is have you ever hit a breakpoint on the server side and is the path correct?

Neo
  • 3,309
  • 7
  • 35
  • 44
  • No I'm using the web api. I've added that error in and I get "unexpected < in JSON in position 4" – hlh3406 Oct 13 '16 at 13:43
  • Does the sql ( i assume ) hydrate the object IEnumerable as you expect? Are you returning json or the object from your method? – Neo Oct 13 '16 at 13:45
  • 1
    I only get this error if I take the data type out so I think that error then refers to this? http://stackoverflow.com/questions/36814694/unexpected-token-in-json-at-position-4 – hlh3406 Oct 13 '16 at 13:46
  • Above my method I set this: [ScriptMethod(ResponseFormat = ResponseFormat.Json)] which I assumed was formatting my response from a list into Json? – hlh3406 Oct 13 '16 at 13:47
  • 1
    are you using return Json statement? – Neo Oct 13 '16 at 13:48
  • 1
    like this return Json(result); – Neo Oct 13 '16 at 13:49
0

You can add the below attribute to the class, which enables the web method to be called from an ajax script.

[System.Web.Script.Services.ScriptService]
0

you have

var param = { "mySearchString": str }; 

but the parameter in you Method is

public static IEnumerable<MyItem> myMethod(string searchString)

Both parameters should have the same name.

Jelte
  • 1
  • 2
0

You're passing a string as parameter, you should pass an object with a string attribute named searchString:

var param = { "mySearchString": str }; 

$.ajax({

           type: 'POST',
           url: 'myForm.aspx/myMethod',
           data: param,
           contentType: 'application/json; charset=utf-8',
           dataType: 'json',
           async: false,
           success: function (data) {
                 $("#MyResults").empty();
                 console.log(data);
                 console.log(data.d);
                 console.log(data.d.length);
                 for (i = 0; i < data.d.length; i++) {
                     $("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
                 }

                  if (data.d.length == 0)
                       $("#MyResults").empty();
                  }

                });
Fourat
  • 2,366
  • 4
  • 38
  • 53
0

kindly remove the following properties, and remove the JSON.stringfy

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

and kindly don't remove the async because it will freeze your UI if you set it to false.

you can do it like this:

$.ajax({
   type: 'POST',
   url: 'myForm.aspx/myMethod',
   data: param, 
   success: function (data) {
         $("#MyResults").empty();
         console.log(data);
         console.log(data.d);
         console.log(data.d.length);
         for (i = 0; i < data.d.length; i++) {
             $("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
         }
         if (data.d.length == 0)
         {
            $("#MyResults").empty();
         }             
  }
});
Jeric Cruz
  • 1,899
  • 1
  • 14
  • 29
  • When I do this it gets rid of my authentication fail message, but instead it seems to return the contents of the current html page? It also still doesn't hit the break point in my .net method? – hlh3406 Oct 12 '16 at 15:17
0

I found my answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"

I was hitting this error:

Object {Message: Ajax error: "Authentication failed.", StackTrace: null, ExceptionType: "System.InvalidOperationException"}

Turns out that I needed to do:

Inside ~/App_Start/RouteConfig.cs change:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

Hopefully this will help someone else!

Community
  • 1
  • 1
hlh3406
  • 1,382
  • 5
  • 29
  • 46