Negrea Stefan
Negrea Stefan

Reputation: 3

AJAX GET request not working

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

Answers (1)

Kevin B
Kevin B

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

Related Questions