0

Use an array in an AJAX jquery function from json-encode();

Hi, I'm new to AJAX

I have un page where i want to call an ajax request to add something on this page. export.php

<div class="row">
    <div class="span12">
        <select id="listTable" name="listTable">
            <option value="appel">Appels</option>
            <option value="dossier">Dossiers</option>
            <option value="commande">Commandes Fournisseur</option>
         </select>
    </div>
</div>

<div class="row">
    <div class="span12">
         <button class="btn btn-primary" onClick="selectTable()">Select</button>
    </div>
</div>

<div id ="columns" class="row" style="display:none;">
    <div class="span12">
         <div id="columns-check" style="">
            <!-- Here will be displayed the content of the ajax request-->
         </div>
    </div>
</div>

<script type="text/javascript" src="_module/ExportFichier/exportFile/ajax/requestExport.js"></script>

Here's my ajax function

function selectTable(table){

    var table = $("#listTable").val();

        $.ajax({

            url: "_module/ExportFichier/exportFile/ajax/requestColumns.php",
            type: "POST",
            data: "table="+table,
            dataType: 'json',

            success: function(data){

                $('#columns').css('display','block');
                $('#columns-check').empty();

                for(i=0; i<data; i++){
                    $('#columns-check').prepend('<div>I would like to display here the content of my array</div>');
                }
            },

            error: function(){
                alert('The Ajax request did not works!');
            }


        });

}

requestColumns.php

header("content-type: application/json; charset=utf-8");

require_once '../requirements.php';

$tableName = $_POST["table"];

$objService = new ExportFileService($tableName);
$columns = $objService->get_columns();

echo json_encode($columns);

I didn't get the way I can return an array from my requestColumns.php file to my jquery Ajax request and after use it to modify the DOM of my page export.php. Thanks for your help.

Kevin
  • 4,823
  • 6
  • 36
  • 70
  • You can find how to loop though an object here [http://stackoverflow.com/questions/684672/loop-through-javascript-object] – cmorrissey Oct 17 '14 at 14:49
  • Is $columns an array or an object? – Marvin Saldinger Oct 17 '14 at 14:51
  • $columns it's an Array. – Kevin Oct 17 '14 at 14:55
  • 1
    The response from the PHP script (your array encoded as JSON) is passed as the first argument of the `success` callback function, which you've called `data`, so you need to iterate through data. What you do afterwards kind of depends; you haven't told us what the JSON looks like or exactly what you want to do with it that I can see so it's difficult to be more precise than that. – Anthony Grist Oct 17 '14 at 14:58

4 Answers4

0

Maby this will help? jQuery JSON

It will become something like this:

for (var i in data.<YOUR_KEY>) {
     $('#columns-check').prepend('Line: ' + data.<YOUR_KEY>[i]);
}
sanderbee
  • 694
  • 7
  • 24
0
function selectTable(table){

var table = $("#listTable").val();

    $.ajax({

        url: "_module/ExportFichier/exportFile/ajax/requestColumns.php",
        type: "POST",
        data: "table="+table,
        dataType: 'json',

        success: function(data){

            $('#columns').css('display','block');
            $('#columns-check').empty();

            for(i=0; i<data.length; i++){
                $('#columns-check').prepend('<div>' + data.arraykey + '</div>'); //change arraykey with your index name
            }
        },

        error: function(){
            alert('The Ajax request did not works!');
        }


    });
}

data.length in the for loop is the thing that was missing.

Marvin Saldinger
  • 1,290
  • 1
  • 16
  • 34
0

You can try change my code based on your needs. But the general ideas is this:

//Your php code

   //Retrieiving data from AJAX
   $selctValue = $_POST["table"];

    //Send data from php to javascript. Using JSON you can send what you want.
    $arrToJSON = array(
        "dataPHPtoJs"=>"yourData",
        "asYouWant"=>"<div class=\".class1\">soemting</div>"    
    );  
    echo json_encode(array($arrToJSON));


    //Your javascript function
    function selectTable(){



    //Data you want to send to php. As many as you want.....
    var dt={ 
              table:$("#listTable").val()
            };



    var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
                            url: "_module/ExportFichier/exportFile/ajax/requestColumns.php",
                            type: "POST",
                            data: dt,
                            dataType: "json"
                        });     



        //Ajax Done catch JSON from PHP 
        request.done(function(dataset){

            //Retrieiving information from php using JSON. Note, you can create html objects here as you did, or if you want your project more dinamicaly you can send html code from php (as I do)

            for (var index in dataset){ 
                 dataPHPtoJsJS=dataset[index].dataPHPtoJs;
                 asManyasYouWantJS=dataset[index].asYouWant;

                 $('#columns-check').prepend('<div>asManyasYouWantJS</div>');

             }

             //JavaScript conditions. Here you can control the behaivior of your html object, based on your PHP response
             if(dataPHPtoJsJS test your condition){
                //Do what you want to do..... 
                $('#columns').css('display','block');
                $('#columns-check').empty();
             }

        });     

  }
IgorAlves
  • 5,086
  • 10
  • 52
  • 83
0

Thanks everyone for you anwser. It helped me to did it that way. Here my code:

function selectAllColumns(){

    var table = $("#listTable").val();

        $.ajax({

            url: "_module/ExportFichier/exportFile/ajax/requestAllColumns.php",
            type: "POST",
            data: "table="+ table,
            dataType: 'json',

            success: function(data){
                console.log('The Ajax request WORKS!');

                $('#columns').css('display','block');
                $('#columns-check').empty();

                for (var key in data) {
                    if (data.hasOwnProperty(key)) {
                        var id = Math.random();
                        $('#columns-check').prepend('<div style="display: inline-block; margin: 20px 20px 20px 0;"><input type="checkbox" id="'+id+'" class="field" value="'+data[key]+'" style="display: inline-block; margin:0 5px -1px 0;"><label for="'+id+'" class="field" style="display: inline-block;">'+data[key]+'</label></div>');
                    }
                }
            },

            error: function(){
                console.log('The Ajax request did not works!');
            }
        });
}
Kevin
  • 4,823
  • 6
  • 36
  • 70