0

I want to receive array from php file by ajax , I tried Encode but didn't work , Any help?

php file :

$Data = array()
foreach($Query as $User){
    //get Year variable
    if($Year['Year'] == $YearPosted){
        //get Name variable
        $Data['Id'] = $Name['FirstName']." ".$Name['LastName'];

    }
}
echo json_encode($Data);

js file :

$.ajax({
        type: "post",
        url: "Ajax/Users/GetUsers.php",
        data: {
            year: Year
        },
        success: function (data) {
            alert(data.Id)
        }
    });

I want to receive from php File Something Like that

var User = [{
  "1": "Name of UserId One"
}, {
  "2": "Name of UserId One"
}]
1
  • 2
    try to add dataType: 'json', to your ajax call. If you make some search on SO you can find a lot of questions like this. Commented Sep 6, 2019 at 10:16

2 Answers 2

0

You have to do something like below, variable may be undefined because you did not mention field of your table.

php side

$Data = array()
foreach($Query as $key => $User){

    //get Year variable
    if($Year['Year'] == $YearPosted){
        //get Name variable
        $Data[$key]['Id'] = $Name['FirstName']." ".$Name['LastName'];

    }
}
echo json_encode($Data);

From js side

$.ajax({
        type: "post",
        url: "Ajax/Users/GetUsers.php",
        data: {
            year: Year
        },
        success: function (data) {
            data = JSON.parse(data);
            console.log(data.id);

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

Comments

0

Try adding a new array level:

$Data = array()
foreach($Query as $User){
    //get Year variable
    if($Year['Year'] == $YearPosted){
        //get Name variable
        $Data[] = [$Data['Id'] => $Name['FirstName']." ".$Name['LastName']];
    }
}
echo json_encode($Data);

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.