We help IT Professionals succeed at work.

php to javascript

MK15
MK15 asked
on
Hi,

I am an academic student wondering if i could get some help regarding passing arrays from php to a javascript script in html.

what i want is to pass a array  from php to javascript. this will allow me to iterate over the array and display it in a search box.  i have the following code;

html:--

<script type="text/javascript">
function showHint(str)
{
$x = $.getJSON('search.php');
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
xmlhttp.onreadystatechange=function(){
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML= xmlhttp.responseText
    }
  }
xmlhttp.open("POST","search.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
</form>
<div id="txtHint"></div>

php //not exact php code - similar to below

$info = Array( "Author" => $book->author, "Price"=>$book->price, "Title"=>$book->title)
echo json_encode($info);

I can get the first index of the variable to be displayed but nothing else.

Any help would be greatly appreciated.

thanks
 
Comment
Watch Question

Post the entire PHP code. It's not clear if you're actually returning more than one object in the results, unless when you say you are only getting the first index, you mean that only the "Author" is being displayed. From what you've shown, though, you are not producing an Array, you are producing an Object. Associative arrays in PHP will always be encoded as objects in JSON.

Also, if you're using jQuery, why are you also using XMLHttpRequest? jQuery provides you a more convenient interface for making AJAX requests that works cross-browser.


Author

Commented:
try
{
$response = $amazonEcs->category('Books')->responseGroup('Medium')->search("php");
      foreach($response->Items->Item as $item) {
            if ($item->ItemAttributes->ProductGroup == "Book") {

            $book = array(      "ASIN" => $item->ASIN,
                                    "Title" =>       $item->ItemAttributes->Title,
                                    "Publisher" =>$item->ItemAttributes->Publisher;

            }

      }


}

catch(Exception $e)
{
  echo $e->getMessage();
}
echo json_encode($book);

If i search for php it would return with
{"ASIN":"0596101015","Title":"PHP Cookbook (Cookbooks (O'Reilly))","Publisher":"O'Reilly Media"} directly from amazons DB.. I need it to return all the books available.

I have not use jQuery before, what would you suggest using instead of XMLHttpRequest?

thank you
Hello

you can use Jquery's autocomplete plugin for that..

Look at following link

http://jqueryui.com/demos/autocomplete/

Hope this will help you.

Thank You.

Amar.
Commented:
hi,

using autocomplete was the second stage - i first need to be able to get the values of the json array in javascript i have tried using json parse and eval but have failed.  could you please show me how i would get the data into the js.

thank you
Hello MK15,

You should use Jquery's AJAX that handles JSON well.

can you please try following code instead of what you have used

 
<script>
function showHint(str){
  if(str != "")
  {
    $.getJSON("search.php?q="+str,
            function(data){
              $.each(data.items, function(i,item){
               alert(item.ASIN);
              });
            });
  }
}
</script>

Open in new window


It should give you some idea.

Hope this will help

Thank You.

Amar Bardoliwala.

Author

Commented:
hey Amar,

Thanks for the prompt reply.

i have tried the above but am getting nor response when typing in a value.. any suggestions?

thank you
Hello MK15,

It seems that you are not getting response from server or code that I have give is not accessing returned JSON properly.

Look at following link. It has given an example to handle form with JSON.

http://www.damnsemicolon.com/php/submitting-a-form-via-ajax-using-jquery-php-and-json

Hope it will help you.

Thank You.

Amar Bardoliwala
Hello MK15,

Following is one more example for you.

http://jhoyimperial.wordpress.com/2008/07/28/parsing-json-data-from-php-using-jquery/

I think this should definitely clear your concept and should solve your problem as well.

Hope this will help you.

Thank You.

Amar Bardoliwala.
First, you need to re-examine your PHP code. You are looping through the $response->Items->Item array, but with each iteration, you were resetting the value of "$book", not adding those elements to an array. If you want to add items to an array, first you would need to define "$book" as an empty array ($book = array();), and then in your loop you need to use the square brackets to indicate that you're adding elements to the array, and not just setting the value of the array variable (see modified code below).

try
{
    $book = array();
    $response = $amazonEcs->category('Books')->responseGroup('Medium')->search("php");
    foreach($response->Items->Item as $item) {
        if ($item->ItemAttributes->ProductGroup == "Book") {
            $book[] = array(
                "ASIN"      => $item->ASIN,
                "Title"     => $item->ItemAttributes->Title,
                "Publisher" => $item->ItemAttributes->Publisher);
            }

      }


}
catch(Exception $e)
{
  echo $e->getMessage();
}
echo json_encode($book);

Open in new window


While there are redundancy issues with the JavaScript, the main issue is that your script is only ever returning a single item. However, here is another JavaScript block that uses jQuery's "ajax" method to retrieve the data from your PHP script and adds to your page. Assumptions here are that you've included the jQuery JavaScript libraries in script tags on your HTML page, and that you've wired the showHint method to an HTML control event, like a button click or textbox change.

function showHint(str)
{
    $.ajax({
        url: "search.php?q="+str,
        datatype: "json",
        success: function (data, textStatus, jqXHR) {
            $('#txtHint').html("");
            for (var i = 0; i < data.length; i ++)
            {
                $('#txtHint').append("<li>" + data[i].Author + " <i>" + data[i].Title + "</i> (" + data[i].Price + ")</li>");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + ": " + errorThrown);
        }
    });
}

Open in new window


Typo in the JavaScript above...

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
function showHint(str)
{
    $.ajax({
        url: "search.php?q="+str,
        datatype: "json",
        success: function (data, textStatus, jqXHR) {
            $('#txtHint').html("");
            for (var i = 0; i < data.length; i ++)
            {
                $('#txtHint').append("<li>" + data[i].ASIN + " <i>" + data[i].Title + "</i> (" + data[i].Price + ")</li>");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(textStatus + ": " + errorThrown);
        }
    });
}

Open in new window

Author

Commented:
Thanks