Home > Enterprise >  Accessing PHP array value in jQuery.ajax is not working
Accessing PHP array value in jQuery.ajax is not working

Time:05-09

I am using jQuery.ajax to send user input to PHP and get an array back. While I alert/console.log the response, it perfectly shows the array in the alert. But while trying to access an individual element of the array, I am getting undefined error. I need to access individual element of the array. What am I doing wrong? Please help.

instagram.php

$nola = array("mediac" => $bola, "userc" => $bola2);
echo json_encode($nola);

jquery ajax file

var formData = jQuery('#myForminstagram').serialize();
jQuery.ajax({
        url:'instagram.php',
        type:'POST',
        data: formData,
        success: function(response) {
                var myuser = response.userc;
                alert(response); //works & shows the array as {"mediac" => $bola, "userc" => $bola2}
                alert(myuser); // doesn't work & show undefined error
                }
    });

CodePudding user response:

It's because your jquery code read the response as text, not json, so you have to tell it to read as json, by doing this:

1.You can add header('Content-Type:application/json; charset=utf-8'); to your instagram.php.

Or

2.You can add dataType: 'json' to your jquery ajax file.

  • Related