Angel F.
Angel F.

Reputation: 176

Handle different type of PHP responses with AJAX

I am designing some PHP pages to process forms. In these pages I want to redirect if result is successful or print a message if there was an error. Structure of pages is like this:

$arg = $_POST["arg"];
if (isset($arg)) {
    if (function($arg)) {
        header ("Location: page2.php");
    }
    else {
        echo "Response was not successfully";
    }
}
else {
    echo "$arg parameter was not defined";
}

When I need to print messages I use cftoast for JQuery (http://www.jqueryscript.net/other/Android-Style-jQuery-Toaster-Messages-Plugin-cftoaster.html) To handle all forms I am using this Javascript function:

$(document).ready(function() {
$("#asynchronousForm").submit(function() {
    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),

        success: function(data) {
            $("body").cftoaster({content: data});
            window.location.href = ""; //Refresh page to clear possible errors
        }
    })   
    return false;
});

My problem is, when form redirects, sometimes appears problems like no redirection and shows empty toast, refreshing page with duplicated input fields... How can I solve this problem? I am using JQueryMobile as skeleton of my webpage.

Upvotes: 0

Views: 60

Answers (1)

fdehanne
fdehanne

Reputation: 1718

A good way to handle AJAX responses is to use JSON. It will allow you to send multiples data and do a redirect or show message depending of AJAX result.

In PHP you can use json_encode() to convert and array to JSON.

$arg = $_POST["arg"];
if (isset($arg)) {
    if (function($arg)) {
        exit(json_encode(array('redirect' => 'page2.php')));
    }
    else {
        exit(json_encode(array('message' => 'Response was not successfully')));
    }
}
else {
    exit(json_encode(array('message' => $arg.' parameter was not defined')));
}

AJAX: You just have to add dataType: 'json'. You can also use $.getJSON()

$.ajax({
    type: $(this).attr('method'),
    url: $(this).attr('action'),
    data: $(this).serialize(),
    dataType: 'json',
    success: function(json) {
        if ( json.redirect )
            window.location.href = json.redirect;
        else
            $("body").cftoaster({content: json.message});
    }
})   

Upvotes: 1

Related Questions