0

I have used Mongodb with Php I want to retrive document from mongo collections with ajax call, so I have tried follwing way but i am strugle with access json object in jquery.. Jquery CODE

$('select[name=trendsName]').change(function(){

    $.ajax({
        url:'getTrendsFullInfo.php',
        type: 'POST',
        dataType: 'json',
        data: {trendsName: $(this).val(), collectionName:'trends_collection'},

        success: function(res){
             for(var i = 0; i < res.trendsArr['LSM'].length; i++){
                $('.resArea').append(res.trendsArr['LSM'][i]);
            }
        }
    });

});

getTrendsFullInfo.php

$finalResultArr = array();
    if(isset($_REQUEST['trendsName']) && isset($_REQUEST['collectionName'])):
        $status = "Sucessfully Retrived From ".$_REQUEST['collectionName']." Record";
        $finalResultArr['LSM'] = array(
                                    '10-12' => 237,
                                    '13-15' => 565,
                                    '16-18' => 825);
        $outputArr = array('status'=>$status, 'trendsArr'=>$finalResultArr);

        echo json_encode($outputArr);   
    endif;  

How to access trendsArr object in jquery?

4
  • Run the browser debugger (F12) set a breakpoint on the line for(var i = 0; i < res.trendsArr['LSM'].length; i++){ and then use the debugger to look at the data returned from PHP in the res variable Commented Oct 18, 2016 at 8:56
  • console.log(res.trendsArr) chk this first, Commented Oct 18, 2016 at 8:56
  • put console.write(res); before the for loop and post what you see. Commented Oct 18, 2016 at 8:56
  • How do you initialize $finalResultArr ? It should be initialised as $finalResultArr = []; before usage to get a valid result. Commented Oct 18, 2016 at 8:57

1 Answer 1

2

The problem is you can't use .length for objects ,it will show you undefined only .So use for in because you don't know what your object key is

$('select[name=trendsName]').change(function(){

    $.ajax({
        url:'getTrendsFullInfo.php',
        type: 'POST',
        dataType: 'json',
        data: {trendsName: $(this).val(), collectionName:'trends_collection'},

        success: function(res){
             for(var i in res.trendsArr['LSM']){
                console.log(" Key => "+ i +" && Value => "+ res.trendsArr['LSM'][i]);
                $('.resArea').append(res.trendsArr['LSM'][i]);
            }
        }
    });

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

2 Comments

it has worked but how to get key and value? Array ( [10-12] => 235 [13-15] => 585 [16-18] => 525 ) i want 10-12 and that value 235
console i that will be key

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.