Theekopje Theekopje - 7 months ago 16
Javascript Question

Ajax succes request

Im not really familiar with Ajax, or Jquery so sorry if i'm not explaining it well enough but I cant seem to figure this one out.

if(usernameAvailable) {
$.ajax({
type: 'POST',
url: 'register.php',
data: register_data,
success: function(data, status) {
if(data.success) {
alert("Account created succesfully!");
window.location.href = "loginForm.php";
} else {
//no succes
}
},
error: function(err) {
console.log(err);
}
});
}



register.php


if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}

echo json_encode(array("success" => true));


What I get returned in the console is the
error: function(err){console.log(err);}



Object {readyState: 4, responseText: "Message has been sent{"success":true}", status: 200, statusText: "OK"}


So if im guessing correctly the status gets a
succes:true
back. But still fires the error instead of running the
succes:function
. Any idea how I get the
succes:function(data,status)
to run?

Answer

First of all, if you're expecting a json object as response from server, then include dataType: 'json' setting in your AJAX request. dataType is the type of data that you're expecting back from the server.

So your AJAX request should be like this:

if(usernameAvailable) {
    $.ajax({
        type: 'POST',
        url: 'register.php',
        data: register_data,
        dataType: 'json',
        success: function(data) {
            if(data.success) {
                alert(data.message);
                window.location.href = "loginForm.php";
            } else {
                //no succes
            }
        },
        error: function(err) {
            console.log(err);
        }
    });
}

And on register.php page, create a message variable to store the relevant message and push it in your array before encoding, like this:

$message = null;
if(!$mail->send()) {
$message = 'Message could not be sent. ';
$message .= 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$message = 'Message has been sent';
}

echo json_encode(array("success" => true, "message" => $message));