Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing PHP array value in jQuery.ajax is not working

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
                }
    });

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading