3

Currently I am having issue with returning some values from PHP to jQuery - not sure how to do it

$(document).ready(function(){
  $('#testForm').submit(function(e){
    $.post('submit.php',$(this).serialize(),function(msg){

        $('#submit').val('Submit');

        if(msg.status){
            $('#testForm').html(msg);
        }
        else {
            $('#testForm').html("fail");
        }
    },'json');

});

});

<?php
$name = $_POST['name'];
$email = $_POST['email'];

//echo json_encode(array('status'=>1,'html'=>$name." : ".$email));
echo '{"status":1,'.$name.'}';
?>

I would like to return the name variable value from PHP to jQuery once status = 1 means success, but I'm still having no luck in doing it.

3
  • Why are you not using the commented-out line? Commented Dec 19, 2012 at 3:50
  • it has special char on a name try htmlentities($name) Commented Dec 19, 2012 at 3:50
  • echo '{"status":1,name:"'.$name.'"}'; Try this Commented Dec 19, 2012 at 3:54

2 Answers 2

5

JSON has a very strict syntax.

In your case, however, you're failing because you're not even specifying a property name, you just have a bare value with no quotes.

Just use json_encode, it will handle all edge cases for you.

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

1 Comment

how does the syntax looks like for the json_encode if i would like to set status 1/0 together with the data return from php to jquery?
1

Are you sure that you are returning a valid json string?

From this instruction:

echo '{"status":1,'.$name.'}';

Assuming that $name is a plain string, for example "hello", you will return this json string:

{"status":1, hello}

And this is invalid.

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.