ridwan
ridwan

Reputation: 23

json, how to return specific value and not the object

im new to this json and ajax thing, can some1 help me with this?

MY JS:

        $(document).ready(function(){
        $(".testajax").submit(function(){


            $.ajax({
              type: "POST",
              url: "controller.php",
              data: $(".testajax").serialize()
            })
              .done(function( msg ){
                $(".result").html("name:" + msg.name);

             });    

             return false;


        });

this is my Json

$return= array("name"=>$_POST);
header('Content-Type: application/json');
echo json_encode($return);

my HTML

<form method="post" action="controller.php" class="testajax">
    <input type="text" name="name" value="">
    <button type="submit">SAVE</button>
</form>

<p class="result"></p>

what i want to do is when i input "Maria" in form and click save... the return result... should be "Maria". but, instead what i got is "name : Object"

Upvotes: 1

Views: 56

Answers (1)

MrCode
MrCode

Reputation: 64526

Here, you are inserting the whole POST array into the name element:

$return= array("name"=>$_POST);

So the JSON will look like this:

{
    "name": {
        "name": "john"
    }
}

Using that, you would have to change the JavaScript to use msg.name.name:

$(".result").html("name:" + msg.name.name);

You are seeing Object because json_encode() by default, converts associative arrays to objects ($_POST is an associative array). It would make more sense to put the name in the name element, not the whole POST array, like so:

$return= array("name"=>$_POST['name']);

Using that, your current JavaScript will work.

Upvotes: 1

Related Questions