Geeth
Geeth

Reputation: 5343

$.ajax is not working

In my web page there is a textbox to get the scanned barcode value. Once we scan the barcode it has to get details from the database. I am creating the change event for the textbox.

Problem: $.ajax is not working.

Code:

    var target = $('#txtBarcode'), val = target.val();
        target.change(monitor());
        function monitor() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: "{}",
                url: "HomePage.aspx/SearchProduct",
                dataType: "json",
                success: function(data) {
                alert("Success!!!");
                }
            });
        }

Upvotes: 0

Views: 170

Answers (3)

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

You can copy some answers posted here, and at least one of will likely to work, but you won't get the intimate knowledge of why. Here's an additional way:

  1. Since you use asp.net, put the break point in the first line of HomePage.aspx/SearchProduct. This ensure that the request goes to the right URL on the server.

  2. Step all the way through this method to make sure there's no exception that gets thrown.

  3. Use FireFox and install Firebug (even if you target IE and have no intention to make it run on FF). You can inspect the http response.
  4. Add an error handler in addition to the success handler.

Upvotes: 0

Dan Heberden
Dan Heberden

Reputation: 11068

You are trying to pass 'monitor' to the change method but you're actually calling it. It should look like this (no parens)

var target = $('#txtBarcode'), val = target.val();
        target.change(monitor);
        function monitor() {

You can always declare it inline too:

 var target = $('#txtBarcode'), val = target.val();
        target.change(
             function() {
                 $.ajax({
                  type: "POST",
                  contentType: "application/json; charset=utf-8",
                  data: "{}",
                  url: "HomePage.aspx/SearchProduct",
                  dataType: "json",
                  success: function(data) {
                             alert("Success!!!");
                           }
                 });
             });

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284796

  1. Add an error handler.
  2. Make sure your relative URL is right.
 $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            url: "HomePage.aspx/SearchProduct",
            dataType: "json",
            success: function(data) {
            alert("Success!!!");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown)
            {
              // ...
            }
        });

EDIT: Dan is right about your change handler.

Upvotes: 1

Related Questions