0

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

Shay Young
  • 207
  • 3
  • 11
  • 1
    Use firebug and track the send/response from the browser and server – jcho360 Mar 10 '14 at 20:08
  • You have a SQL injection vulnerability. – SLaks Mar 10 '14 at 20:09
  • 2
    Why don't you use `json_encode()` in PHP? – barell Mar 10 '14 at 20:09
  • Use a JSON serializer. – SLaks Mar 10 '14 at 20:10
  • @barell where do i use that at, i dont think the value of the click is getting to the php file the console logs no value – Shay Young Mar 10 '14 at 20:18
  • in Chrome CTR+SHIFT+I and click network. then click your "link" you should see the ajax call to azlistscript.php appear there. click on it and see that the response is. Obvi if it doesnt show up then you implemented JQuery wrong. Is you $("#searchH").click( function under on document load? – Robert Mar 10 '14 at 20:20
  • @user3061378 [read about json encode in PHP](http://uk3.php.net/json_encode) – barell Mar 10 '14 at 20:21

6 Answers6

3

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');
Shovan
  • 185
  • 7
0

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>');

akr
  • 739
  • 4
  • 15
0
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.

Community
  • 1
  • 1
Jonast92
  • 4,964
  • 1
  • 18
  • 32
0

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>'
  }
fitorec
  • 1,022
  • 12
  • 10
0

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);
        }
    });
});
Wilmer
  • 2,511
  • 1
  • 14
  • 8
0

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!

2upmedia
  • 2,832
  • 1
  • 20
  • 16
  • Thank you will try all of your tips tomorrow. Does the code you commented on work for multiple items coming from database – Shay Young Mar 10 '14 at 22:59
  • Whatever your previous code did, this is the same, but with a couple of corrections. So technically yes it would work with multiple items since that's what it did previously. – 2upmedia Mar 10 '14 at 23:59