简体   繁体   中英

How to generate a PHP response for $.ajax

A form is being submitted using the ajax code below. I am unsure what response to generate using PHP, so that $.ajax can call the appropriate callbacks done() and fail()

request = $.ajax({
        url: "php_process.php",
        type: "post",
        data: serializedData
    });

    // callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // log a message to the console
        console.log("Hooray, it worked!");

    });

    // callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.error(
            "The following error occured: "+
            textStatus, errorThrown
        );
    });`

See .done() and .fail() responses at result area , network tab at console

$(function() {
    var urls = ["/echo/jsons/", "/echo/json/"];
    var request = function(url) {

        return $.ajax({
        url: url,
        type: "POST",
        data: {json : JSON.stringify({"abc":[123]}) }            
        });
    };           
    // callback handler that will be called on success
 $.each(urls, function(k, v) {
     $.when(request(v))
    .done(function (response, textStatus, jqXHR){
        // log a message to the console
        console.log("Hooray, it worked!", response);
        $("body").prepend("DONE: <br>" 
                          + Object.keys(response) + ":" 
                          +  response[Object.keys(response)] 
                          + "<br><br>")
    })    
    // callback handler that will be called on failure
   .fail(function (jqXHR, textStatus, errorThrown){
        // log the error to the console
        console.log("The following error occured: "
                    + textStatus, errorThrown);
       $("textarea")
       .before("FAIL: <br>")
       .val(jqXHR.getAllResponseHeaders() +"\n" 
           + jqXHR.status +"\n"+ textStatus 
           +"\n"+ errorThrown +"\n" +  jqXHR.responseText)
    });  
});
});

jsfiddle http://jsfiddle.net/guest271314/L3jbvnex/1/

See

PHP: How to send HTTP response code?

http://php.net/manual/en/function.http-response-code.php

http://php.net/manual/en/function.header.php

fail() is only called if there is an error in getting the response from server. Else the done() is called. So fail() doesn't depend on the response from the PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM