Shay Young
Shay Young

Reputation: 207

Ajax not returning data

Hey i am trying to return books beginning with a certain letter in this case H. But i cant get this code to work at all any help would be great full. HTML

<a href="" id="searchH" name="h" value="h"> <<<< CLICKED

<div id="ack2"></div> <<<<<< DISPLAYED HERE

PHP

<?php
include('db.php');
$letter = "";
$i = 0;
$jsonData = '{"books":[';
if(isset($_POST['letter'])){
    $letter = $_POST['letter'];

    $sqlString = "SELECT * FROM book WHERE title LIKE '$letter%'";

    $query = mysql_query($sqlString) or die (mysql_error()); 
    while ($row = mysql_fetch_array($query)) {
        $i++;   
        $year = $row["year"];   
        $title = $row["title"];
        $author = $row["author"]; 
        $jsonData .= '{ "title":"'.$title.'", "author":"'.$author.'", "year":"'.$year.'" },';
    }

    $jsonData =  chop($jsonData, ",");
    $jsonData .= ']}';
    echo $jsonData;
}
?>

Ajax/javaScript

$("#searchH").click(function(){
    letter = $("#searchH").val();
    $.ajax({
        type: "POST",
        url: "azlistscript.php",
        data: "letter ="+letter,
        success: function(html){
            $("#ack2").html(html);
            }
            });
    });

the PHP file does return the book data if i change the letter value manually it displays the books beginning with H, Just need it to display in a div tag on my html page.

The value of the click event logs no value in the console

Upvotes: 0

Views: 131

Answers (6)

2upmedia
2upmedia

Reputation: 2910

You have a good start but you're missing a couple of things:

  1. Don't trust input data coming from an untrusted source. Treat data coming from $_REQUEST, $_GET, $_POST as if it's coming from a malicious hacker. That's why you should filter data. Your code is currently open to SQL injection attacks like others have mentioned. If you were doing SQL inserts using input data you'd also be open to XSS.

  2. Always double check your HTML to check if you're writing it correctly, that you understand the use of the tag and its attributes. This means that it abides to W3C standards. You can run your HTML through http://validator.w3.org. You're going to want to read documentation from http://www.w3.org/TR/html5/. It's easier to just to Google w3c html5 a tag, just replace the tag you're interested in. The value attribute doesn't exist on the anchor tag. If you want to attach a value to it use HTML5 data- attributes instead. Look at my altered code.

  3. Make sure you understand the jQuery API and parameters: http://api.jquery.com and http://learn.jquery.com. For instance, the first parameter to the success function changes depending on the type of data coming back from the server (xml, json, html). It could be a string OR it could be a real javascript object which is one reason why you're JSON isn't showing up in the div.

  4. In your AJAX data option you put an extra space after the key name (i.e. letter). That means that's how it's going to end up in your PHP so your if statement will fail. Be careful about little typos like that. They really do make a difference.

  5. The mysql_* functions are now deprecated in PHP 5.5 which means you're code will eventually not work in future versions of PHP. Keep this in mind and use mysqli_* functions instead or better yet use the mysqli class and write your code object oriented style.

  6. Like others have mentioned use json_encode instead. Why? You don't have to worry about getting your JSON syntax right especially when you want to change how your JSON responses look like. With json_encode all you need to do is give it an array. If you change the shape of the array, the JSON will always come out the way you want it. Sooooo much easier.

Here's the live code:

Javascript and HTML: http://jsbin.com/nutaquzu/2/edit

PHP: http://codepad.viper-7.com/zak79I

Welcome to the world of web development!

Upvotes: 0

akr
akr

Reputation: 739

generate your php output like this json_encode(array("title"=>$title,"author"=>$author,"year"=>$year));

and in your js use output = $.parseJSON(html) to parse the output and then you display it using

$("#ack2").html('<span>'+output.title+'</span>'+'<span>'+output.author+'</span>'+'<span>'+output.year+'</span>');

Upvotes: 0

Jonast92
Jonast92

Reputation: 4967

success: function(html)
{
});

html is just a name you provide for the returned object. The object contains some variables, including the message d.

You have to fetch it:

success: function(html)
{
    var message = html.d;
    // use message
});

I don't know why it's d but that's the way the cookie crumbles.

If it doesn't do the job then there's something wrong with the data you provide or the way things are handled in the back-end, just use the developer tools and check what's happening in the network. If you're blank you can always log what's going on.

EDIT: There's possible that the d part is only a part of the [WebMethod] return method provided by ASP. See discussion. More on-topic then:

  • Make sure that you've checked the value you're sending.
  • Make sure that you've checked the value you're receiving.
  • Make sure that you've checked the http network status provided by the response of the request (Is it actually 200?).

If something is odd there then you are more on track on what's going on.

Upvotes: 0

Wilmer
Wilmer

Reputation: 2511

You need to fix a few things:

$("#searchH").click(function (e) {
    e.preventDefault(); //prevent browser link behaviour
    var letter = $(this).attr("value"); //get the attribute (ex: value, name, etc.)
               //^^^^^^^this refers to the current element being clicked
    $.ajax({
        type: "POST",
        url: "azlistscript.php",
        data: "letter =" + letter,
        success: function (html) {
            $("#ack2").html(html);
        }
    });
});

Upvotes: 0

fitorec
fitorec

Reputation: 1042

Check your data in your javascript, try with:

 //JavasCript code
 $("#searchH").click(function(){
   $.ajax({
      type: "POST",
      url: "azlistscript.php",
      data: { letter:  $("#searchH").val()},
      success: function(html){
          $("#ack2").html(html);
          }
        });
  });

In PHP check your POST array:

 <?php
 // PHP code
  if(isset($_POST['letter'])){
    // your more code...
  }else { //debug POST array
      echo '<pre>'. print_r($_POST['letter'], true) . '</pre>'
  }

Upvotes: 0

Shovan
Shovan

Reputation: 215

One problem I can see is

letter = $("#searchH").val();

the element is 'a' tag which is not a form element so .val() does not work here. In stead try

letter = $("#searchH").attr('value');

Upvotes: 3

Related Questions