简体   繁体   中英

How to convert AJAX response to JSON?

I trying to manipulate my AJAX response.

在此处输入图片说明

I need to create a foreach to create cards with the search results.This is my code:

$('#OrdAlf').on("click", function(){
  var value = $(this).data("value");
  jQuery.ajax({
    url: theme_url + '/helpers/filter_index.php',
    type: 'POST',
    dataType: "text",
    data: {ordFilter:value}
  }).done(function(data){
    //console.log();
    var json = JSON.stringify(data);
    alert(json);
    var htmlLoad = '<div class="draggable ui-widget-content card-crm" id="card-crm"><div class="avatar-client"></div><div class="info-content"><p class="name">'+data+'</p><p class="info-contact"></p><p class="when-enter"><span class="ico-enter"></span></p></div><div class="icons-top"></div><div class="clear"></div></div></b>';
    var ajax_load = "<img src='https://i.imgur.com/FpzX0YO.gif' />";
        $("#card-container").html(htmlLoad);
  });
});

How do I organize this data for this loop to happen?

I try alert "alert(json[0]);" and this was the result:

在此处输入图片说明

This is my PHP page:

<?php
require 'conexao.php';

if($_POST['ordFilter'] == 200){
  $selectNegociacaoASC = 'SELECT * FROM wp_crm_contacts WHERE user_id = '.$userId.' AND status is NULL ORDER BY name ASC;';
  $stmtNegociacaoASC = $db->prepare($selectNegociacaoASC);
  $response = $stmtNegociacaoASC->execute();
  $resultNegociacaoASC = $stmtNegociacaoASC->fetchAll(PDO::FETCH_ASSOC);
  $countNegociacaoASC = count($resultNegociacaoASC);

  for($y = 0;$y < $countNegociacaoASC; $y++){
    $name[$y] =  $resultNegociacaoASC[$y]['name'];
    if($name != ""){
      echo json_encode($name);
    }
  }
};

PHP : here i stored your name object into returnarray array variable then i just return the output as json.

$returnarray= array();
for($y = 0;$y < $countNegociacaoASC; $y++){
$name[$y] =  $resultNegociacaoASC[$y]['name'];
if($name != ""){
  $returnarray[]=$name;//storing name object into array
}
echo json_encode($returnarray);

In JQuery - i just convert the json as javascript object and consoled it

jQuery.ajax({
url: theme_url + '/helpers/filter_index.php',
type: 'POST',
dataType: "text",
data: {ordFilter:value}
}).done(function(data){
var json = JSON.stringify(data);
console.log(json) // You can get the object now 
}

Try this let me know your comments

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