Reputation: 3
I am trying to make an AJAX call, it's the very first time I use AJAX, my code is the following:
$.get( "validate.php", { 'userinput':'x'}, function(response) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
});
vaidate.php:
<?php
$user_input=$_GET['userinput'];
//print_r($user_input);
if(!is_null($user_input)) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
?>
If I access my validate.php, I get "undefined index" error. What is the proper way to do this?
Upvotes: 0
Views: 96
Reputation: 95031
The php looks fine once you comment out the test code:
<?php
$user_input=$_GET['userinput'];
//print_r($user_input);
if(!is_null($user_input)) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
?>
you need to specify that you expect JSON, the simplest way would be to use getJSON
$.getJSON( "validate.php", { 'userinput':'x'}, function(response) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
});
Other alternative with jQuery is
$.get( "validate.php", { 'userinput':'x'}, function(response) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
},"json");
or to set the contentType header in php:
<?php
$user_input=$_GET['userinput'];
//print_r($user_input);
header('Content-type: application/json');
if(!is_null($user_input)) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
?>
Upvotes: 1