简体   繁体   中英

Get response array from jquery ajax to php

I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.

// selector de campaña en reporte de clientes mas activos
$(document).ready(function(){
    $('.selector-camp').change(function(){
        var campaing = $('.selector-camp').val();
        $.post( "../campanas/test", { 'camp': campaing },
        function( data ) {
            alert( data.result );
        }, "json");
    });
});

As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do

      function( data ) 
      {
        createTable(data.result); //pass your json array to JS function
      }, "json");
      //here i create js function
      function createTable(array)
      {
         var array = JSON.parse(array); //decoding from json format
         //So if i have numbers in array like [1, 2, 3, 4] and want
         //to create row with them something like this should be done
         var table = document.createElement("table"); //create table
             var tr = document.createElement("tr"); //create row
             for(var i=0; i<array.length; i++)
             {
                 var td = document.createElement("td");
                     td.innerHTML = array[i]; 
                 tr.appendChild(td); 
                 //for each array element creates cell and appends to row
              }
              table.appendChild(tr);
          //Then you can have some empty div and append table to it
          var div = //your empty div
              div.appendChild(table);
       }

Please check below php prototype code as per your requirement. From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.

<?php 
test();
function test(){
    $camp = htmlspecialchars($_POST['camp']);
    isset($camp)&&!empty($camp)?
    $data = array('test_key'=>'test_value');
    echo json_encode($data);
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM