0

I'm trying get a value inside a JavaScript array from the output of an AJAX request.

Ajax request:

$.ajax({
    url: "ajax-test.php",
    type: "POST",
    data: "sku=800270",
    dataType: "html"

    }).done(function(resposta) {

        console.log(resposta);
}

Ajax-Test.php:

$produto[] = array('sku'    => $product->getSku(),
                   'name'   => $product->getName());

var_dump($produto[0]);

Returns:

array(6) {
  ["sku"]=>
  string(6) "000188"
  ["name"]=>
  string(80) "Cuba Gastronômica Aço Inoxidável para Buffet GN 1/2×65mm (325x265mm) - 812-2"
}

I need to access the values inside the array, something like:

var sku = resposta["sku"]

In my tests if I try to print resposta["sku"] its giving me "undefined variable".

1
  • 2
    Change dataType: "html" to dataType: "json" Commented Aug 29, 2016 at 13:26

2 Answers 2

2

On php side you need to change var_dump($produto[0]); to echo json_encode($produto[0]). On JS side you need to change your request to dataType: "json", because it is not a html response. Then you can access the fields by the property names.

var sku  = resposta.sku;
var name = resposta.name;

Your aproach is not wrong to, to access by a string:

var sku  = resposta["sku"];
var name = resposta["name"];

So for conclusion, your php:

$produto[] = array(
    'sku'    => $product->getSku(),
    'name'   => $product->getName()
);

echo json_encode($produto[0]);

Your AJAX request:

$.ajax({
    url: "ajax-test.php",
    type: "POST",
    data: "sku=800270",
    dataType: "json"
}).done(function(resposta) {
    var sku  = resposta.sku;
    var name = resposta.name;

    console.log(sku, name);
}
Sign up to request clarification or add additional context in comments.

2 Comments

It wouldn't be $produto[0], though, would it? Edit: Oh, yes, I see, it would be. Probably make more sense just to drop the []: $produto = array('sku' => $product->getSku(), 'name' => $product->getName()); echo(json_encode($produto));
This belongs to what he want to to. Because he uses $produto[] to assign another array, $produto[0] isn't wrong here. It would work. But if he want to have more products there, he have to use echo json_encode($produto); and do more actions on JS side ... but that belongs to the usecase. @T.J.Crowder
1
  • Set a proper dataType for ajax object as dataType: "json"
  • Change your Ajax-Test.php file content as shown below(to send a proper json responce):

    $produto[] = ['sku' => $product->getSku(), 'name' => $product->getName()];       
    echo json_encode($produto[0]);
    

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.