最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Send a request to a php page and then get back results using ajax - Stack Overflow

programmeradmin3浏览0评论

I have a script where i am trying to send some location information to a php page, carry out a mysql search query and get the results back without going to another page.

my php works fine, and i have had the page working that it redirects to the php page, however when i try and use the code below, i do not get any results passed back.

Javascript code

   function phpRedirect(loc) { 

  // var radius = get('r');     // Retrieve GET values for search radius      and                           
  // var numResults = get('n'); // number of results

  var radius = 10;     // Retrieve GET values for search radius and                           
   var numResults = 5; // number of results

  var latitude = loc.coords.latitude;   // Get long, lat and accuracy from
  var longitude = loc.coords.longitude; // location object
  var accuracy = loc.coords.accuracy;

var xmlHttp = new XMLHttpRequest();  //not the cross browser way of doing it
   xmlHttp.open("GET", "find.php?lat=" + latitude + "&long=" + 
                   longitude + "&acc=" + accuracy + "&r=" + radius 
                   + "&n=" + numResults, true); 
    xmlHttp.send(null);                    

    } 

      $(function () 
     {
   $.ajax({                                      
    url: 'find.php',                  //the script to call to get data          
    type: "post",
    data: { getData: true },
    dataType: 'json',                //data format      
    success: function(data)          //on recieve of reply
    {
        var name = data[0];              

        $('#output').html("<b>username: </b>"+username);

       } 
    });
  }); 


 function error(loc) { 
 // This is called if the location can't be found.
  document.write("Error finding GPS location");
  } 

 // Use navigator to get current user location. If found, calls 'phpRedirect()',
// If not available calls 'error()'. Includes timeout and ensures highest acc.
navigator.geolocation.getCurrentPosition(phpRedirect, error, {maximumAge:60000,    timeout:5000, enableHighAccuracy:true}); 

<div id="output">this element will be accessed by jquery and this text replaced </div>

Below is the output from my php query,

   $result=mysql_query($query) or die (mysql_error());

  while($row=mysql_fetch_assoc($result)) $data[]=$row; // Turn result to array

  $acc_package = array('location_accuracy'=>"$accuracy"); // Include result array
  $output[] = $acc_package;                          // and accuracy value inside
  $output[] = $data;                                 // an output array.
  print(json_encode($output)); // Convert output array to json format and print

Which gives the following results

 [{"location_accuracy":"122000"},[{"username":"bobbyj","distance":"0.484367160806139"}]]

I have a script where i am trying to send some location information to a php page, carry out a mysql search query and get the results back without going to another page.

my php works fine, and i have had the page working that it redirects to the php page, however when i try and use the code below, i do not get any results passed back.

Javascript code

   function phpRedirect(loc) { 

  // var radius = get('r');     // Retrieve GET values for search radius      and                           
  // var numResults = get('n'); // number of results

  var radius = 10;     // Retrieve GET values for search radius and                           
   var numResults = 5; // number of results

  var latitude = loc.coords.latitude;   // Get long, lat and accuracy from
  var longitude = loc.coords.longitude; // location object
  var accuracy = loc.coords.accuracy;

var xmlHttp = new XMLHttpRequest();  //not the cross browser way of doing it
   xmlHttp.open("GET", "find.php?lat=" + latitude + "&long=" + 
                   longitude + "&acc=" + accuracy + "&r=" + radius 
                   + "&n=" + numResults, true); 
    xmlHttp.send(null);                    

    } 

      $(function () 
     {
   $.ajax({                                      
    url: 'find.php',                  //the script to call to get data          
    type: "post",
    data: { getData: true },
    dataType: 'json',                //data format      
    success: function(data)          //on recieve of reply
    {
        var name = data[0];              

        $('#output').html("<b>username: </b>"+username);

       } 
    });
  }); 


 function error(loc) { 
 // This is called if the location can't be found.
  document.write("Error finding GPS location");
  } 

 // Use navigator to get current user location. If found, calls 'phpRedirect()',
// If not available calls 'error()'. Includes timeout and ensures highest acc.
navigator.geolocation.getCurrentPosition(phpRedirect, error, {maximumAge:60000,    timeout:5000, enableHighAccuracy:true}); 

<div id="output">this element will be accessed by jquery and this text replaced </div>

Below is the output from my php query,

   $result=mysql_query($query) or die (mysql_error());

  while($row=mysql_fetch_assoc($result)) $data[]=$row; // Turn result to array

  $acc_package = array('location_accuracy'=>"$accuracy"); // Include result array
  $output[] = $acc_package;                          // and accuracy value inside
  $output[] = $data;                                 // an output array.
  print(json_encode($output)); // Convert output array to json format and print

Which gives the following results

 [{"location_accuracy":"122000"},[{"username":"bobbyj","distance":"0.484367160806139"}]]
Share Improve this question asked Dec 12, 2012 at 0:00 Sam WilliamsSam Williams 1752 gold badges3 silver badges12 bronze badges 6
  • 1 Heads up! Future versions of PHP are deprecating and removing the mysql_ family of functions. Now would be a great time to switch to PDO or mysqli. – Charles Commented Dec 12, 2012 at 0:01
  • 2 Also, why in the name of all things good and holy are you bining modern jQuery with prehistoric manual ajax? – Charles Commented Dec 12, 2012 at 0:01
  • @Charles Haha there's even an $.ajax call in there! – Ian Commented Dec 12, 2012 at 0:04
  • your .ajax call doesn't send any data to the server. Actually why is it there? – shapeshifter Commented Dec 12, 2012 at 0:12
  • Agree with @Charles on this, decide for one method of executing your ajax call. But for the question, i don't see where you are defining the variable username in the success function. And have you tried something like console.dir(data); in the success function? To verify that you get data from request and correct format – martin-lundberg Commented Dec 12, 2012 at 0:34
 |  Show 1 more ment

1 Answer 1

Reset to default 2

Sam, I have a few suggestions for you.

First, the jQuery library is great and the AJAX module works amazing :) It's great that you are using it! No need to mix that old XMLHTTP junk with it (they do basically the same thing). So get rid of that and replace it with jQuery ajax.

Let's start with something really basic:

$.ajax({                                      
    url: 'find.php',       
    type: "POST",
    data: { lat: lattitude } 
}).done(function( msg ) {
    alert(msg);
});

Put your other variables in the data: as well.

On your PHP page, try a simple var_dump($_POST); so you can see what is ing through. The AJAX should make an alert with contents of the PHP page.

Work your way up from this with your Mysql :)

发布评论

评论列表(0)

  1. 暂无评论