Ajax success event not working

2020-01-24 02:39发布

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?

16条回答
够拽才男人
2楼-- · 2020-01-24 02:51

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.

查看更多
【Aperson】
3楼-- · 2020-01-24 02:51

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.
查看更多
太酷不给撩
4楼-- · 2020-01-24 02:53

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.

查看更多
我想做一个坏孩纸
5楼-- · 2020-01-24 02:57

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

查看更多
趁早两清
6楼-- · 2020-01-24 02:59

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.

查看更多
相关推荐>>
7楼-- · 2020-01-24 02:59

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");
查看更多
登录 后发表回答