draft
draft

Reputation: 303

Why isn't AJAX working?

I'm trying to perform a simple ajax call to a simple php script to test that ajax is working.

HTML:

<button id="hi">hi</button>

JS:

<script type="text/javascript">
$( "#hi" ).click(function(){
   var dataString = "hi";
   $.ajax({
     url: "custom_scripts/hi.php",
     type: "POST",
     dataType:'json',
     data: dataString,
     cache: false,
     success: function(data){
       if(data.auth==true){
         alert("success: " + data.auth);
       }         
     }
   }) 

});

PHP:

<?php

    $hi=$_POST['hi'];

    $rVal=array("auth" => false);

    if(isset($hi)){
        $rVal['auth']=true;
    } else {
        $rVal['auth']=false;
    }

    echo json_encode($rVal);

?>

Are there any other scripts or libraries (from any language) that can interfere with ajax calls? When I step through, it's reaching the call, it's not returning any data (and no error in console) ...

Upvotes: -1

Views: 504

Answers (1)

devpro
devpro

Reputation: 16117

You just need to pass Ajax data as:

 data: "hi="+dataString,

Complete Ajax Example:

$( "#hi" ).click(function(){
   var dataString = "hi";
   $.ajax({
     url: "custom_scripts/hi.php",
     type: "POST",
     dataType:'json',
     data: "hi="+dataString,
     cache: false,
     success: function(data){
       if(data.auth==true){
         alert("success: " + data.auth);
       }         
     }
   }) 
}); 

In your example, if you check browser console, you are getting Undefined Index Notice.

Upvotes: 2

Related Questions