简体   繁体   中英

Unable to retrieve data using jQuery.post

I'm trying to use jQuery.post() function to retrieve some data. But i get no output.

I have a HTML that displays a table. Clicking this table should trigger a jQuery.post event.

My scriptfile looks like this:

jQuery(document).ready(function() { 

  jQuery('#storeListTable tr').click(function() { 
    var storeID = this.cells[0].innerHTML; //This gets me the rowID for the DB call.

    jQuery.post("../functions.php", { storeID: "storeID" }, 
      function(data){ 
         alert(data.name); // To test if I get any output 
      }, "json"); 
    }); 
});  

My PHP file looks like this:

<?php 
  inlcude_once('dal.php'); 

  //Get store data, and ouput it as JSON. 
  function getStoreInformation($storeID) 
  {
    $storeID = "9";//$_GET["storeID"]; 
    $sl = new storeLocator(); 
    $result = $sl->getStoreData($storeID); 

    while ($row = mysql_fetch_assoc($result)) { 
    { 
        $arr[] = $row; 
    } 
    $storeData = json_encode($arr); 
    echo $storeData;  //Output JSON data 
  } 
?> 

I have tested the PHP file, and it outputs the data in JSON format. My only problem now is to return this data to my javascript.

  1. since the javascript is located in the /js/ folder, is it correct to call the php file by using '../'?
  2. I don't think I'm passing the storeID parameter correctly. What is the right way?
  3. How can I call the getStoreInformation($storeID) function and pass on the parameter? The jQuery example on jQuery.com has the following line: $.post("test.php", { func: "getNameAndTime" } Is the getNameAndTime the name of the function in test.php ?

I have gotten one step further. I have moved the code from inside the function(), to outside. So now the php code is run when the file is executed.

My js script now looks like this:

  jQuery('#storeListTable tr').click(function() {
    var storeID = this.cells[0].innerHTML;

    jQuery.post("get_storeData.php", { sID: storeID },
      function(data){
         alert(data);
      }, "text");
    });

This results in an alert window which ouputs the store data as string in JSON format. (because I have changed "json" to "text").

The JSON string looks like this:

[{"id":"9","name":"Brandstad Byporten","street1":"Jernbanetorget","street2":null,"zipcode":"0154","city":"Oslo","phone":"23362011","fax":"22178889","www":"http:\/\/www.brandstad.no","email":"bs.byporten@brandstad.no","opening_hours":"Man-Fre 10-21, L","active":"pending"}]

Now, what I really want, is to ouput the data from JSON. So I would change "text" to "json" and "alert(data)" to "alert(data.name)". So now my js script will look like this:

  jQuery('#storeListTable tr').click(function() {
    var storeID = this.cells[0].innerHTML;

    jQuery.post("get_storeData.php", { sID: storeID },
      function(data){
         alert(data.name);
      }, "json");
    });

Unfortunately, the only output I get, is "Undefined". And if I change "alert(data.name);" to "alert(data);", the output is "[object Object]".

  1. So how do I output the name of teh store?

  2. In the PHP file, I've tried setting $storeID = $_GET["sID"]; But I don't et the value. How can I get the value that is passed as paramter in jQuery.post ? (currently I have hardcoded the storeID, for testing)

Lose the quotes around "storeID":

Wrong:

jQuery.post("../functions.php", { storeID: "storeID" }

Right:

jQuery.post("../functions.php", { storeID: storeID }

bartclaeys is correct. As it is right now, you are literally passing the string "storeID" as the store ID.

However, a couple more notes:

  • It might seem weird that you will be setting storeID: storeID - why is only the second one being evaluated? When I first started I had to triple check everytime that I wasn't sending "1:1" or something. However, keys aren't evaluated when you are using object notation like that, so only the second one will be the actual variable value.
  • No, it is not correct that you are calling the PHP file as ../ thinking of the JS file's location. You have to call it in respect of whatever page has this javascript loaded. So if the page is actually in the same directory as the PHP file you are calling, you might want to fix that to point to the right place.
  • Kind of tied to the previous points, you really want to get your hands on Firebug . This will allow you to see AJAX requests when they are sent, if they successfully make it, what data is being sent to them, and what data is being sent back. It is, put simply, the consensus tool of choice to debug your Javascript/AJAX application, and you should have it, use it, and cherish it if you don't want to waste another 6 days debugging a silly mistake. :)

EDIT As far as your reply, if you break down what you are returning:

[
  {
    "id":"9",
    "name":"Brandstad Byporten",
    "street1":"Jernbanetorget",
    "street2":null,
    "zipcode":"0154",
    "city":"Oslo",
    "phone":"23362011",
    "fax":"22178889",
    "www":"http:\\/www.brandstad.no",
    "email":"bs.byporten@brandstad.no",
    "opening_hours":"Man-Fre 10-21, L",
    "active":"pending"
  }
]

This is actually an array (the square brackets) containing a single object (the curly braces).

So when you try doing:

alert(data.name);

This is not correct because the object resides as the first element of the array.

alert(data[0].name);

Should work as you expect.

Your JSON is returned as a javascript array... with [] wrapping the curly bits [{}]

so this would work.

wrong:  alert(data.name);
right:  alert(data[0].name);

Hope that helps. D

Ok, thanks to Darryl, I found the answer.

So here is the functional code for anyone who is wondering about this:

javascript file

jQuery(document).ready(function() {

  jQuery('#storeListTable tr').click(function() {

    jQuery.post("get_storeData.php", { storeID: this.cells[0].innerHTML },     // this.cells[0].innerHTML is the content ofthe first cell in selected table row
      function(data){
         alert(data[0].name);
      }, "json");
    });

});

get_storeData.php

<?php
  include_once('dal.php');

  $storeID = $_POST['storeID'];   //Get storeID from jQuery.post parameter

  $sl = new storeLocator();
  $result = $sl->getStoreData($storeID);  //returns dataset from MySQL (SELECT * from MyTale)

  while ($row = mysql_fetch_array($result))
  {
    $data[] = array( 
    "id"=>($row['id']) ,
    "name"=>($row['name']));
  }  

  $storeData = json_encode($data);

  echo $storeData;
?>

Thanks for all your help guys!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM