user559142
user559142

Reputation: 12527

get JSON - JQuery & PHP

I have a HTML/JQuery frontend. I would like my HTML page to have a link, which when clicked posts data to a php file and decodes a JSON response which should be printed to the document window.

EDIT:

Here is my UPDATED HTML/JQuery Code based on @Kyle's answer:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
    <style>
       a.test { font-weight: bold; }
    </style>
  </head>
  <body>
    <a href="">display message</a>
    <script src="jQuery/jQuery.js"></script>
    <script>
    $(document).ready(function(){                     
      $(function(){
         $("a").click(function(e){
            e.preventDefault();
            getmessage = "Yes";
            getmessage = encodeURIComponent(getmessage);//url encodes data
            $.ajax({
               type: "POST",
               url: "http://dev.speechlink.co.uk/David/test.php",
               data: {'getmessage': getmessage},
               dataType: "json",
               success: function(data) {
                  json = $.parseJSON(data);
                  $("#message_ajax").html("<div class='successMessage'>" + json.message + "</div>");
               }
            });
         });
      });
  });
  </script>
  <div id = "message_ajax"></div>
  </body>
</html>

Here is test.php

<?php
 if(isset($_POST['getmessage'])){
  $dbh = connect();
  $message = mysql_real_escape_string($_POST['message']); 
  $query =  mysql_query("SELECT message FROM messages WHERE id = '46'") or die(json_encode(array('message' => "didn't query"));
  if($query){
    echo json_encode(array('message' => 'Successfully Submitted Data'));
  }else{
    echo json_encode(array('message' => 'Error Submitting Data'));
  }
  mysql_close();
}
?>

The back-end is setup fine...So I know the issue doesn't lie there. I think it's a syntax issue on my behalf but I cannot for the life of me get the div to display the response.I have tried for hours. I think one of the potential many problems is the fact that i'm not posting 'getmessage' correctly in my jQuery function...I'm a jQuery noob, which probably answers most of your questions...

EDIT:

With the above code, I manage to get the following written to the document window after the link is pressed:

[Object object]

My question is how do I get it to print the actual value within the JSON endoded PHP response..

Upvotes: 0

Views: 2310

Answers (4)

Kyle
Kyle

Reputation: 4449

Your dataString variable inside of your ajax request is empty. You never set it to anything inside of your code. Also, non-jQuery object don't support the .serialize method. You should use the encodeURIComponent method for that.

Try this:

<script>
   $(document).ready(function(){                     
      $(function(){
         $("a").click(function(e){
            e.preventDefault();
            getmessage = "Yes";
            getmessage = encodeURIComponent(getmessage);//url encodes data
            $.ajax({
               type: "POST",
               url: "test.php",
               data: {'getmessage': getmessage},
               dataType: "json",
               success: function(data) {
                  $("#message_ajax").html("<div class='successMessage'>" + data.message + "</div>");
               }
            });
         });
      });
   });
</script>

Upvotes: 3

ipr101
ipr101

Reputation: 24236

Try changing -

data: dataString,

to

data: "getmessage=yes",

In your code the lines -

getmessage = "Yes";
getmessage = getmessage.serialize();

won't work as 'serialize()' would normally be called on an array of form elements rather than a string. If your HTML contained a form that contained an input named 'getmessage' you could do something like -

getmessage = $('form').serialize();

Then pass your getmessage variable as your data string -

data: getmessage,

Upvotes: 0

Daff
Daff

Reputation: 44215

Besides the things already mentioned, the fact, that your PHP script doesn't return valid JSON might also be a problem. It just prints

Successfully Submitted Data

to the page which is not JSON. Try:

echo json_encode(array('message' => 'Successfully Submitted Data'));

Or use plain HTML.

Upvotes: 4

Tom
Tom

Reputation: 9167

A couple of things here. You have what seems like an extraneous anonymizing wrapper around your code. And it looks like the code that does the page update was incomplete and commented out.

Try this:

$(document).ready(function(){
    $("a").click(function(e){
        e.preventDefault();
        getmessage = "Yes";
        getmessage = getmessage.serialize(); // url encodes data; DOES IT??
        $.ajax({
            type: "POST",
            url: "test.php",
            data: dataString,
            dataType: "json",
            success: function(data) {
                $("#message_ajax").html(
                    '<div class="successMessage">'
                    + data +
                    '</div>'
                );
            }
        });
        return false;
    });
});

While testing, try to use something like Fiddler or LiveHTTPHeaders to verify that the browser is actually sending the data you expect -- another poster may be on to something in that dataString doesn't appear to contain any information specific to the clicked link. You may need to do something like to get it:

var dataString = $(this).attr('href').split('?')[1];

Upvotes: 0

Related Questions