Petrus Petrus - 4 months ago 26
Javascript Question

jQuery Ajax - Wrong response

I have a problem with jQuery ajax function:

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

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

$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">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Medivia</title>
<form action="index.php" method="POST">
<label>E-mail:<br><input type="text" name="mail" required></label>
<label>Hasło:<br><input type="password" name="pass" required></label>
<button name="login">Zaloguj się</button>

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


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:

  $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.