Yahoo
Yahoo

Reputation: 4187

Extracting data from a ajax response

I need to extract the URL's from the php datas, how can i achieve this?

PHP

$query = 'SELECT * FROM picture LIMIT 3';
$result = mysql_query($query);


while ($rec = mysql_fetch_array($result,  MYSQL_ASSOC)) {
    $url.=$rec['pic_location'].";";
}

echo json_encode($url);

Ajax

 <script type="text/javascript">
    $(document).ready(function() {
    $(".goButton").click(function() {
       var dir =  $(this).attr("id");

   var imId = $(".theImage").attr("id");
   $.ajax({
      url: "viewnew.php",
      data: {
         current_image: imId,
         direction    : dir
      },
     success: function(ret){
          console.log(ret);
          var arr = ret;
          alert("first: " + arr[0] + ", second: " + arr[1]);
          alert(arr[0]);
          $(".theImage").attr("src", +arr[0]);
          if ('prev' == dir) {
        imId ++;
     } else {
        imId --;
     }
     $("#theImage").attr("id", imId);
          }
       });

    });
    });
    </script>

the alert message isn't working its just printing H T ( i think these are http://... )

Upvotes: 0

Views: 185

Answers (2)

Thomas
Thomas

Reputation: 8859

You're returning a string which is not parsed as JSON. Just add dataType: "json" to the ajax settings.

And since you're reading it as an array in your javascript you should return it like so:

while ($rec = mysql_fetch_array($result,  MYSQL_ASSOC)) {
    $url[] = $rec['pic_location'];
}

Upvotes: 1

slash197
slash197

Reputation: 9034

You are sending a string in your PHP and expecting an array as response in javascript. Change you PHP to

while ($rec = mysql_fetch_array($result,  MYSQL_ASSOC)) {
    $url[] = $rec['pic_location'];
}

And javascript to

$.ajax({
      url: "viewnew.php",
      dataType: "JSON",
      data: {
         current_image: imId,
         direction    : dir
      },
      success: function(ret){
          console.log(ret[0]);
          var arr = ret;
          alert(arr);  
          alert("first: " + arr[0] + ", second: " + arr[1]);    // THIS IS NOT WORKING!!!!
          if ('prev' == dir) {
            imId ++;
         } else {
            imId --;
         }
         $("#theImage").attr("id", imId);
      }
   });

Upvotes: 1

Related Questions