Get a Specfic Answer from MySql in jQuery AJAX Success

Well, I have this ajax code that will return the result from MySql in the Success block.

$.ajax({ type:"POST", url:"index.php", success: function(data){ alert(data); } }); 

My request

 $sql = "SELECT * FROM tablename"; $rs=parent::_executeQuery($sql); $rs=parent::getAll($rs); print_r($rs); return $rs 

My array of answers in AJAX success warning

 Array ( [0] => Array ( [section_id] => 5 [version] => 1 [section_name] => Crop Details [id] => 5 [document_name] => Site Survey [document_master_id] => 1 [document_section_id] => 5 ) [1] => Array ( [section_id] => 28 [version] => 1 [section_name] => Vegetative Report [id] => 6 [document_name] => Site Survey [document_master_id] => 1 [document_section_id] => 28 ) ) 

I want to get only the result of section_name and document_name so that I can add these two values ​​to my list.

+6
source share
4 answers

Do not return the answer with print_r() , use json_encode() :

 echo json_encode($rs); 

Then in Javascript you can:

 $.ajax({ type:"POST", url:"index.php", dataType: 'json' success: function(data){ for (var i = 0; i < data.length; i++) { console.log(data[i].section_name, data[i].document_name); } } }); 
+3
source

change your selection request with

 $sql = "SELECT section_name,document_name FROM tablename"; 
+2
source
 $sql = "SELECT * FROM tablename"; $rs=parent::_executeQuery($sql); $rs=parent::getAll($rs); return json_encode($rs); 

index.php

 $.ajax({ type:"POST", url:"index.php", success: function(data){ alert(data); var data = JSON.parse(data); /* you can use $.each() function here */ } }); 
+2
source

Do it:

 $sql = "SELECT * FROM tablename"; $rs=parent::_executeQuery($sql); $rs=parent::getAll($rs); $resp = array(); foreach( $rs as $each ){ $resp[]['section_name'] = $each['section_name']; $resp[]['document_name'] = $each['document_name']; } return json_encode($resp); 

Note the JSON response as follows:

 for (var i = 0; i < data.length; i++) { console.log(data[i].section_name, data[i].document_name); } 
+1
source

Source: https://habr.com/ru/post/979599/


All Articles