0

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..

6
  • Why is the call to update message_ajax commented out? Commented Aug 8, 2011 at 17:34
  • Although you would lose flexibility/reusability, have you consider allowing your server to return HTML instead of JSON? That would allow you to just drop it into your HTML page w/o any processing. Just an idea... Commented Aug 8, 2011 at 17:36
  • You still have an error compared to my code. It should be getmessage = encodeURIComponent(getmessage); Commented Aug 8, 2011 at 18:09
  • Sorry, I updated now - it works but I can't get the JSON value. Commented Aug 8, 2011 at 18:26
  • I updated my script now so you should be able to get the JSON part. Commented Aug 8, 2011 at 18:40

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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>

5 Comments

great! BUT it prints [object Object]...How do I get it to print the php response (i.e. the value in the JSON encoded key value pair)...
Because you are telling it in the jQuery AJAX call that it is JSON, in your PHP script, you need to change the echo statements to echo json_encode('Your message here');
Sorry, I had actually update my php- check the code above...I'm using JSON
Okay, I have updated the script according to your new PHP script. Just as a side note, you should also change your die statement or die(json_encode(array('message' => "didn't query"));
Sorry, that is my fault. The data returned to you is automatically parsed into a JSON object. There is no need to reparse it which was causing the problem. I have fixed the error, and tested it using the exact same scripts you are using (except on my server) and it is working.
0

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];

Comments

0

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,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.