ludvik120 ludvik120 - 27 days ago 9
Ajax Question

How to access string from PHP to jQuery using AJAX

I have a simple registration form. What I want to achieve is when the output from PHP is

success
then do something. Else do something else. Both in AJAX. I hope you can help me because I am totally new in jQuery and AJAX

This is part of my PHP for this form:

if ($kontrolaMenoPocet != 0) {
$error[] = "<p class='text_chyba'>Takéto meno už existuje!</p>";
}
if ($pocetZnakovNick > 15) {
$error[] = "Nick môže mať maximálne 15 znakov!";
}
if ($kontrolaEmailPocet != 0) {
$error[] = "<p class='text_chyba'>Takýto E-mail sa už používa</p>";
}
if ($pocetZnakovHeslo != 0 AND $pocetZnakovHeslo < 6) {
$error[] = "Heslo musí mať minimálne 6 znakov";
}elseif ($pocetZnakovHeslo == 0) {
echo "";
}
if ($heslo != $hesloZnova) {
$error[] = "Hesla sa nezhodujú";
}
if (empty($error)) {
//writte into database
}
if (isset($error)) {
if (empty($error)) {
echo "Success";
}else{
foreach ($error as $chyba) {
echo $chyba;
}
}
}


And this is my jQuery with AJAX:

if (nick == '' || email == '' || heslo == '' || hesloZnova == '') {
$('.registracia_form .nick, .email, .password, .password_again').addClass('inputError');
} else {
$.ajax({
method: 'post',
url: 'PHP/register.php',
data: data,
}).done(function(data) {
console.log("success");
}).fail(function() {
console.log("error");
}).always(function() {
console.log("complete");
});
}

Answer

Change your .done() callback to:

.done(function(data) {
    console.log(data);
    if (data === 'Success') {
      // do something
    } else {
      // do something else
    }
})
Comments