Skip to content
Advertisement

Ajax calling PHP and getting Return value

Not used Javascript -> Ajax -> PHP -> Javascript before and I am struggling to pick-up the return value. Ajax is calling the PHP, but all I am getting back is the HTML for the web page. Can anyone see what I am doing wrong?

Javascript: –

onChange: function(value, text, $selectedItem) {
    jQuery.ajax({ url : 'index.php', type : 'post', data : { action: 'getTest', param : text },
                    success: function(result){
                      console.log('Sucess',result);
                    },
                      failure: function(result){ console.log('Failed'); }
                    });
}

PHP: –

$_action = isset($_Post['action']) ? $_Post['action'] : '0';
if ($_action == 'getTest') {
  $test = $_Post['param'];
  echo $test;
  exit;
}

As I said, RESULT just seems to contain the page’s HTML and not the expected string value.

Thanks

Advertisement

Answer

Your post variable is with small caps letters. However the Variable should be full caps ($_POST). So your php is not going into the if statement.

https://www.php.net/manual/en/reserved.variables.post.php

To debug these kind of issues start logging variables like $_action and check if their value is what you expect it to be. Then check if the if statement actually fires, etc. until you find the error.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement