1

I want to get more then 1 value from my php file.

Here is my ajax code

$.ajax({
    type: "POST",
    url: "insert.php",
    data: $(this).serialize(),
    success: function(response){
        alert(response);
        alert(response.dummy_code);
        alert(response.user_id);
    },
});

and on my insert.php i make this output

echo json_encode(array("dummy_code" => "$dummy_code", "user_id" => "$insertet_user_id"));

As example $dummy_code have to value 5s8374m9f9f3m34mc334 and $user_id the value 14.

With the command

alert(response);

I get this ouput

{"dummy_code":"5s8374m9f9f3m34mc334","user_id":"14"}

And the ouput of the two other commands

undefined

Why response.dummy_code & respone.id dont work?

3
  • Just for testing purpose: alert(eval(response.dummy_code)); Commented Jun 1, 2015 at 19:21
  • Read the documentation, in particular, the dataType option. Commented Jun 1, 2015 at 19:21
  • @Hackerman output = undefined Commented Jun 1, 2015 at 19:22

3 Answers 3

2

Are you setting the correct content type in the response header? if not tru adding this line before the echo:

header('Content-Type: application/json');
echo json_encode(array("dummy_code" => "$dummy_code", "user_id" => "$insertet_user_id"));
Sign up to request clarification or add additional context in comments.

1 Comment

@Name if this helped you, you could mark it as answer. It would help me ;)
2

Because you're getting a string back you have to parse the string as JSON

function(response){
    var myJSON = JSON.parse(response);
    console.log(response);
    console.log(myJSON.dummy_code);
    console.log(myJSON.user_id);
},

If you don't want to do that you can just add a dataType to the jQuery AJAX request -

$.ajax({
    type: "POST",
    url: "insert.php",
    data: $(this).serialize(),
    dataType: 'JSON',

Quit using alert() for troubleshooting., use console.log() instead.

2 Comments

I tried it now multiple times. But the ouput in the console is every time the same, only {"dummy_code":"5s8374m9f9f3m34mc334","user_id":"14"}. I think there must be 2 lines more (the value of dummy_code & the value of user_id)?
This syntax seems to be working for me just fine. If the last 2 lines were problematic you would get undefined.
1

your response is not parsed into an object its just a string, if you're returning JSON, tell jQuery and It'll parse it for you.
The are two ways to do it, 1: set the response type to application/json

header('Content-Type: application/json');

or set the dataType in $.ajax to json.

dataType: 'json',

1 Comment

Yep that was the problem. THanks!

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.