223

I have a registration form and am using $.ajax to submit it.

This is my AJAX request:

$(document).ready(function() {
    $("form#regist").submit(function() {
        var str = $("#regist").serialize();
        $.ajax({
            type: 'POST',
            url: 'submit1.php',
            data: $("#regist").serialize(),
            dataType: 'json',
            success: function() {
                $("#loading").append("<h2>you are here</h2>");
            }        
        });
        return false;        
    });
});

In my submit1.php file I check for the existence of fields email address and username in the database. I wish to display an error message if those value exist without a page refresh.

How can I add this to the success callback of my AJAX request?

Liam
  • 27,717
  • 28
  • 128
  • 190
codingbbq
  • 4,049
  • 5
  • 35
  • 47

16 Answers16

431

The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.

You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row.

Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
  • 24
    i changed the dataType to text and got it working. like this `dataType:'text'` – Magesh Jan 03 '12 at 12:00
  • +1 even my, but on code that wasn't mine, I solved by returning json data from server – albanx Aug 17 '12 at 10:15
  • 4
    This can also occur if a `dataType:` isn't specified, but the `url:` ends in `.json`. – davetapley Mar 21 '13 at 14:54
  • 1
    Also in `$.post` alias supplying `json` as data type without actual json coming from server does not trigger `success` callback – baldrs Sep 24 '13 at 11:26
  • If you want to make a json ajax request be sure it's mime-type is set to application/json. That gave me some troubles. – Gellweiler Apr 07 '14 at 19:11
  • I must add that I was having this same issue and simply removing the datatype attribute entirely made it work. I was just using plain text; not JSON. – Richard Barker Aug 21 '15 at 19:40
  • You don't seem to need JSON in that function anyways, so you can also take out the dataType: 'json' row. - Does the trick for me! – Subrata Sarkar Sep 03 '15 at 06:34
  • Now it's best to use `promises` when doing this as mentioned here http://api.jquery.com/jquery.ajax/ – BRogers Mar 10 '16 at 23:30
  • You can also repair this on the server side. For instance, when using Spring you can declare the produced type: produces=MediaType.APPLICATION_JSON_VALUE If you remove this or change it to text, it would work. So, in short, both ends must align. – womplefrog Apr 05 '16 at 16:58
  • How did you solve the ajax events not firing at all (success,error,complete)? – MC9000 Nov 14 '19 at 01:15
23

Although the problem is already solved i add this in the hope it will help others.

I made the mistake an tried to use a function directly like this (success: OnSuccess(productID)). But you have to pass an anonymous function first:

  function callWebService(cartObject) {

    $.ajax({
      type: "POST",
      url: "http://localhost/AspNetWebService.asmx/YourMethodName",
      data: cartObject,
      contentType: "application/x-www-form-urlencoded",
      dataType: "html",
      success: function () {
        OnSuccess(cartObject.productID)
      },
      error: function () {
        OnError(cartObject.productID)
      },
      complete: function () {
        // Handle the complete event
        alert("ajax completed " + cartObject.productID);
      }
    });  // end Ajax        
    return false;
  }

If you do not use an anonymous function as a wrapper OnSuccess is called even if the webservice returns an exception.

js newbee
  • 249
  • 2
  • 3
  • 6
    this has nothing to do with ajax, nor jquery, nor handlers. We could just as well have a comment reminding that "the whole code shoud be wrapped in a script tag". The explanation is false: you do not have to wrap anything in anonymous functions, a named function will do, as long as you pass it instead of calling it. Furthermore it is misleading: OnSuccess gets called before the request is even sent, so it makes no sense to relate it to webservice returning anything. – fdreger Mar 04 '11 at 14:57
  • This answer helped me, but I did not upvote, you should update your answer according to @fdreger comment. – Ozair Kafray Mar 10 '15 at 10:03
  • 1
    For me **complete** and **error** works, but not **success**. – AnonymousUser Apr 27 '22 at 05:18
17

I tried removing the dataType row and it didn't work for me. I got around the issue by using "complete" instead of "success" as the callback. The success callback still fails in IE, but since my script runs and completes anyway that's all I care about.

$.ajax({
    type: 'POST',
    url: 'somescript.php',
    data: someData,
    complete: function(jqXHR) {
       if(jqXHR.readyState === 4) {
          ... run some code ... 
       }   
    }        
 });

in jQuery 1.5 you can also do it like this.

var ajax = $.ajax({
    type: 'POST',
    url: 'somescript.php',
    data: 'someData'
});
ajax.complete(function(jqXHR){
    if(jqXHR.readyState === 4) {
        ... run some code ... 
    }
});
Allen
  • 2,717
  • 2
  • 30
  • 34
  • 11
    Just a note to this. `complete` will always get called regardless if the ajax call was successful or not while `success` only gets called if the web server responds with a `200 OK` HTTP header (everything's OK). – katalin_2003 Sep 30 '14 at 07:03
10

Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.

Delfin
  • 101
  • 1
  • 2
  • This really helped me out. I know it's an old answer but it was exacltly the problem I'd been having. Using echo's or print_r's during debugging and finding out that those actually cause the bug... :) Thanks! – lennyklb Feb 17 '15 at 00:49
  • 6 years later and still helping people out with this answer! I wouldn't have known where to look otherwise. – Tania Rascia Mar 09 '18 at 16:26
7

Put an alert() in your success callback to make sure it's being called at all.

If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.

Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • Thanks for your reply. Tried alert in success event but it did not work. I have firebug addon for firefox and it does receive a successful ( 200 OK ) response so no issues there.. I have a die function called in my php file for any errors and when i check it in firebug , it shows proper response. what do you mean by "You can also put another alert() in the complete callback, which should definitely be invoked."?? Thanks a lot for a quick reply – codingbbq Dec 28 '09 at 13:47
  • 2
    if you don't see the alert in your `success`, then it is not a success. since the response is 200 OK, Tatu's reply seems reasonable, but for further troubleshooting, you can use another event, called `complete` which is always invoked, regardless of whether or not a request is successful (`success` only happens if the request is successful). `complete: function (xhr, status) { alert('complete: '+status); }` – David Hedlund Dec 28 '09 at 13:55
4

I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified

dataType: "json"

once I did, unlike the "accepted answer", that actually fixed the problem.

Kabir Sarin
  • 18,092
  • 10
  • 50
  • 41
3

I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.

Thusitha Wickramasinghe
  • 1,063
  • 2
  • 15
  • 30
2

You must declare both Success AND Error callback. Adding

error: function(err) {...} 

should fix the problem

JeffNhan
  • 363
  • 3
  • 3
1

I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.

In my case the reason was , that the closing tag did not match the opening tag.

<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <result>
        <status>$status</status>
        <OPENING_TAG>$message</CLOSING_TAG>
    </result>";
?>
thowa
  • 590
  • 1
  • 8
  • 29
1

I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:

  1. The result was not being returned in JSON format
  2. I was trying to convert an array to JSON format, but this array had non-utf characters

So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.

Andresa Martins
  • 280
  • 2
  • 9
1

I tried to return string from controller but why control returning to error block not in success of ajax

var sownum="aa";
$.ajax({
    type : "POST",
    contentType : 'application/json; charset=utf-8',
    dataType : "JSON",
    url : 'updateSowDetails.html?sownum=' + sownum,
    success : function() {
        alert("Wrong username");
    },
    error : function(request, status, error) {

        var val = request.responseText;
        alert("error"+val);
    }
});
rlandster
  • 7,294
  • 14
  • 58
  • 96
1

I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved. note using Lavalite framework. before:

public function Activity($id)
    {
        $data=getData();
        return
            $this->response->title('title')
                ->layout('layout')
                ->data(compact('data'))
                ->view('view')
                ->output();
    }
after code looks like:
    try {
            $attributes = $request->all();
            //do something
            return $this->response->message('')
                ->code(204)
                ->status('success')
                ->url('url'. $data->id)
                ->redirect();
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url('nothing Wrong')
                ->redirect()
        }

this worked for me

Malakai
  • 3,011
  • 9
  • 35
  • 49
masokaya
  • 589
  • 4
  • 10
1

I had the same problem i solved it in that way: My ajax:

event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}), 
success: function(php_response){
            if (php_response == 'item') 
                {
                    console.log('it works');
                }
            }
        })

Ok. The problem is not with json but only php response. Before: my php response was:

echo 'item';

Now:

$variable = 'item';
 echo json.encode($variable);

Now my success working. PS. Sorry if something is wrong but it is my first comment on this forum :)

silkykg
  • 11
  • 1
0

in my case the error was this was in the server side and for that reason it was returning a html

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");
Emiliano Barboza
  • 475
  • 4
  • 11
0

Add 'error' callback (just like 'success') this way:

$.ajax({
   type: 'POST',
   url: 'submit1.php',
   data: $("#regist").serialize(),
   dataType: 'json',
   success: function() {
      $("#loading").append("<h2>you are here</h2>");
   },
   error: function(jqXhr, textStatus, errorMessage){
      console.log("Error: ", errorMessage);
   }
});

So, in my case I saw in console:

Error:  SyntaxError: Unexpected end of JSON input
  at parse (<anonymous>), ..., etc.
Vlado
  • 3,517
  • 2
  • 26
  • 24
-4

The success callback takes two arguments:

success: function (data, textStatus) { }

Also make sure that the submit1.php sets the proper content-type header: application/json

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for your reply. I read about this on jquery ajax documentaion but i cannot figure out what my next step to should be to get it working... would appreciate if you could point me to the right direction. Also does it mean that i should have some specific code in my php file?? thanks a lot – codingbbq Dec 28 '09 at 13:40
  • 8
    the fact that `success` takes two arguments seems completely irrelevant to the question. You can pass any amount of parameters to a javascript function, regardless of how many it accepts in its declaration, so that's definitely not the cause of these issues, and since none of the values `data` or `textStatus` are being used in the success callback, there seems to be no good reason to declare them in the function at all. – David Hedlund Dec 28 '09 at 13:42
  • And JSON data doesn't have to have correct content-type header, it just has to be in JSON format. – Tatu Ulmanen Dec 28 '09 at 13:44