Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON return value

Tags:

json

jquery

php

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.

like image 922
user1897151 Avatar asked Apr 21 '26 16:04

user1897151


2 Answers

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.

like image 149
Niet the Dark Absol Avatar answered Apr 23 '26 07:04

Niet the Dark Absol


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.

like image 29
Hernan Velasquez Avatar answered Apr 23 '26 06:04

Hernan Velasquez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!