Scott
Scott

Reputation: 465

Accessing JSON returned by php script using jquery ajax

Basically my program is a web page with 5 radio buttons to select from. I want my web app to be able to change the picture below the buttons every time a different button is selected.

My problem is coming in the JSON decoding stage after receiving the JSON back from my php scrip that accesses the data in mysql.

Here is my code for my ajax.js file:

$('#selection').change(function() {
   var selected_value = $("input[name='kobegreat']:checked").val();

   $.ajax( {
       url: "kobegreat.php",
       data: {"name": selected_value},
       type: "GET",
       dataType: "json",

       success: function(json) {
           var $imgEl = $("img");
           if( $imgEl.length === 0) {
               $imgEl = $(document.createElement("img"));
               $imgEl.insertAfter('h3');
               $imgEl.attr("width", "300px");
               $imgEl.attr("alt", "kobepic");
           }
           var link = json.link + ".jpg";
           $imgEl.attr('src', link);
           alert("AJAX was a success");
      },
      cache: false
  });
});

And my php file:

<?php


   $db_user = 'test';
   $db_pass = 'test1';       

   if($_SERVER['REQUEST_METHOD'] == "GET") {
       $value = filter_input(INPUT_GET, "name");
   }

   try {
       $conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
       $conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
       $stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
       do_search($stmt, $value);
  } catch (PDOException $e) {
      echo 'ERROR', $e->getMessage();
  }

  function do_search ($stmt, $name) {
      $stmt->execute(['name'=>$name]);

      if($row = $stmt->fetch()) {
          $return = $row;
          echo json_encode($return);
      } else {
          echo '<p>No match found</p>;
      }
  }

?>

Here's my HTML code where I am trying to post the image to.

<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
   <input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
   <input type="radio" name="kobegreat" value="kobe2"/>Kobe2
   <input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>

<div id="target">
    <h3>Great Kobe Moment!</h3>
</div>

And here's is what my database looks like:

greatshots(name, link)

name         link
------       --------
kobe1        images/kobe1
kobe2        images/kobe2
kobe3        images/kobe3

Whenever I run the web app right now, the rest of the images on the page disappear and the image I am trying to display won't show up. I get the alert that "AJAX was a success" though, but nothing comes of it other than the alert. Not sure where I am going wrong with this and any help would be awesome.

Upvotes: 1

Views: 37

Answers (1)

yk11
yk11

Reputation: 768

As mentioned you should parse the JSON response using JSON.parse(json);.

Also, you should specifically target the div element with a simpler setup: $("#target").append('<img width="300px" src="' + link + '.png"/>');

Upvotes: 1

Related Questions