Petrus Petrus - 19 days ago 5
Javascript Question

jQuery Ajax - Wrong response

I have a problem with jQuery ajax function:

var arrayIdEq = JSON.stringify(iditem);
$.ajax({
type: "POST",
url: "index.php",
dataType : 'text',
contentType: 'application/json; charset=utf-8',
data: {
arrayIdEq : arrayIdEq
},
success: function(answer) {
alert(answer);
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});


"arrayIdEq" contains number from 0 to 7, or string "EMPTY".
PHP code:

elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;


After request, when success response come, alert show up... but here's the problem. Instead of "$answer" value, alert contains... HTML code from my main page!

<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Medivia</title>
</head>
<body>
<h1>Medivia</h1>
<form action="index.php" method="POST">
<label>E-mail:<br><input type="text" name="mail" required></label>
<br>
<label>Hasło:<br><input type="password" name="pass" required></label>
<br>
<button name="login">Zaloguj się</button>
</form>
</body>
</html>


I have no idea what happend here. Could anybody explain to me what happend there? What did i do wrong?

Answer

Your answer variable in the success function will contain the complete output of your php script.

So when you call index.php and you do:

elseif(isset($_POST['arrayIdEq'])){ 
  $answer = "my_answer";
  return $answer;
}

The script will only exit if the return statement is called from the main script (not from within a function) but the output will be the output generated by the script until that point.

Your script should output - and not return - only what you want returned to the javascript.

Probably a separate script for ajax requests will be a more convenient solution than using the index.php file you use to build the complete page.

Comments