I am trying to make a search box in my web application, and I used ajax post to make a request to my server. My question is:
Is it possible to send looped array values from PHP to my JavaScript?
I want to get all of the results from my server.
CLIENT SIDE: Ajax POST request
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
type: "POST",
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
// Get the search result
}
});
});
</script>
SERVER SIDE (after retrieving the post from ajax, and making queries):
while ($result = mysql_fetch_assoc ($query))
{
$resultName = $result['name'];
$resultAddress = $result['address'];
}
$results = array();
while ($result = mysql_fetch_assoc ($query)) {
$results[] = $result;
}
echo json_encode(array('results' => $results));
In your success callback you can then iterate over result.results which contains an object with the column names from your query as attributes.
success: function(result) {
$.each(results, function(i, row) {
console.log(row.name, row.address);
})
}
It is also advisable to use dataType: 'json' in your $.ajax({...}); arguments to avoid unnecessary guessing of the response type.
In case you have more columns in the SQL resultset than you want to forward to the client, you could add a custom array in the loop:
$results[] = array('name' => $row['name'], 'address' => $row['address']);
yes you can you can return a json string :
$.ajax({
type: "POST",
dataType: 'json', // return type is json ;
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
$.each($result,function(index, value){
// use params
}
}
});
and on your php side you use json_encode()
Related
My PHP file retrieves data from a PostgreSQL DB. I have to send them back to my jQuery function in two different arrays. One is passed by using:
echo json_encode($tb);
and works fine, in my js file i get data correctly by using:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb) {
console.log(tb);
})
console output is as expected.
The other is always a PHP array, but I have to replace chars:
str_replace(array('[', ']'), '', htmlspecialchars(json_encode($ltb), ENT_NOQUOTES));
but if I write:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb, ltb) {
console.log(tb);
console.log(ltb);
})
console.log(ltb) simply outputs
success
what I'm I getting wrong?
The second parameter of succes is the response staus. This is the reason because you get success when logging tlb.
You can only return one JSON at at time, so combine them:
echo json_encode(array("other stuff", "tb" => $tb, "tbl" => array("some" => "data")));
On JS side you can simple acces them by index or key:
tb[0]; // "other stuff"
tb.tb; // content of $tb variable
tb.tbl; // {some: "data"}
The final working code:
PHP:
$tb = array();
$ltb = array();
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
array_push($ltb, $row["x"], $row["y"]);
array_push($tb, $row["z"],$row["t"]);
}
echo json_encode(array('tb'=>$tb,'ltb'=>$ltb));
JS
$.ajax({
type: "POST",
url: './DB/lb.php',
dataType: 'json', // this is what I forgot!!!
data: {d_p: oa}, // passes variable for PHP function
success: function (response) {
console.log(response.tb+" "+ response.ltb);
$.each(response.tb, function( i, item ) {
// iterate over tb array
}
$.each(response.ltb, function( i, item ) {
// iterate over ltb array
}
});
I am using jQuery .ajax() to submit some values to db.php page where I retrieve additional records from my db. I use a class that returns the query results in a form of an object. I need to return that object back to original page in response and output it.
$.ajax({
type: 'POST',
url: '/db.php',
data: {
'item': myItem
},
dataType : 'json',
async: true,
success: function (response) {
// need returned values here
}
});
db.php
$results = $db->get_results("
SELECT *
FROM t1
WHERE id = " . $id );
// if I were to output my results here I'd do
// foreach ($results AS $res) {
// $item = $res->item;
// }
echo '{ "res": '.$results.' }';
Now sure if I need to encode anything before passing it back to my JS...
how about json_encode()
echo json_encode($result);
js:
success: function (response) {
console.log(response)
for(var i=0; i <response.length; i++){...}
}
edit: make sure you add application/json; charset=utf-8 header, if not you'll need to parse the response JSON.parse(response)
you can do something like this with the result:
echo json_encode(array(
'result' => $result,
));
and in your success: function(response)
success: function(response){
response = JSON.parse(response);
console.log(response);
}
I want to pass through an array of "Blocks" with Ajax. I created "Blocks" with a PHP class: I know how to pass an array with numbers, with JSON, but I dont know how to pass an array with objects.
Will I have to recreate a class in Javascript that mimiks the "Blocks" class and then pass every value through?
class RequirementsEntity {
public $num;
public $name;
function __construct($num, $field, $name, $desc, $bool) {
$this->num = $num;
$this->name = $name;
My code for PHP:
$result = [];
while ($row = mysql_fetch_array($query)) {
$num = $row[0];
$name = $row[1];
$ablock = new BlockEntity($num, $name);
array_push($result, $arequirement);
}
echo json_encode($result);
My code for jQuery:
$('#selProgram').on('change', function() {
var id = this.value;
if (id != "None") {
$.ajax({
type: "POST",
url: "assets/php/fetch_req.php",
data: "id="+id,
datatype: "json"
success: function(data) {
alert(data);
GenerateRequirements(data, 1);
}
});
}
});
From the php.net docs
The JSON standard only supports these values when they are nested inside an array or an object.
json_encode turns the variables from an object into JSON variables, so if you save the name and number in the BlockEntity object they would show up.
With the help of the responses, if anyone in the future has the same issue, you should:
Call Ajax with a parameter data-type: "json", and making sure to parse the data after you receive it:
$('#selProgram').on('change', function() {
var id = this.value;
if (id != "None") {
$.ajax({
type: "POST",
url: "assets/php/fetch_req.php",
data: "id="+id,
datatype: "json",
success: function(data) {
JSON.parse(data)
}
});
}
});
Also, encode into JSON when sending with php:
echo json_encode($result);
Thanks!
This helped a lot How to return an array from an AJAX call?
How do I use AJAX to return a variable in PHP? I am currently using echo in my controller to display a price on dropdown .change in a div called price.
However I have a hidden field which I need to return the row id to on change. How do I assign the return var in jQuery so that I can echo it in my hidden field?
jQuery
$(document).ready(function() {
$('#pricingEngine').change(function() {
var query = $("#pricingEngine").serialize();
$('#price').fadeOut(500).addClass('ajax-loading');
$.ajax({
type: "POST",
url: "store/PricingEngine",
data: query,
success: function(data)
{
$('#price').removeClass('ajax-loading').html('$' + data).fadeIn(500);
}
});
return false;
});
});
Controller
function PricingEngine()
{
//print_r($_POST);
$this->load->model('M_Pricing');
$post_options = array(
'X_SIZE' => $this->input->post('X_SIZE'),
'X_PAPER' => $this->input->post('X_PAPER'),
'X_COLOR' => $this->input->post('X_COLOR'),
'X_QTY' => $this->input->post('X_QTY'),
'O_RC' => $this->input->post('O_RC')
);
$data = $this->M_Pricing->ajax_price_engine($post_options);
foreach($data as $pData) {
echo number_format($pData->F_PRICE / 1000,2);
return $ProductById = $pData->businesscards_id;
}
}
View
Here is my hidden field I want to pass the VAR to every-time the form is changed.
" />
Thanks for the help!
Well.. One option would be to return a JSON object. To create a JSON object in PHP, you start with an array of values and you execute json_encode($arr). This will return a JSON string.
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
{"stack":"overflow","key":"value"}
Now in your jQuery, you'll have to tell your $.ajax call that you are expecting some JSON return values, so you specify another parameter - dataType : 'json'. Now your returned values in the success function will be a normal JavaScript object.
$.ajax({
type: "POST",
url: "...",
data: query,
dataType: 'json',
success: function(data){
console.log(data.stack); // overflow
console.log(data.key); // value
}
});
echo json_encode($RESPONDE);
exit();
The exit is not to display other things except answer. RESPONDE is good to be array or object.
You can access it at
success: function(data)
{ data }
data is the responde array or whatever you echo..
For example...
echo json_encode(array('some_key'=>'yesss')); exit();
at jquery
success: function(data){ alert(data.some_key); }
if u are returning only single value from php respone to ajax then u can set it hidden feild using val method
$("#hidden_fld").val(return_val);
I am learning Cakephp and I've been trying to delete multiple (checked) record using checkbox, but still not success. here's my jQuery :
var ids = [];
$(':checkbox:checked').each(function(index){
ids[index] = $(this).val();;
alert(ids[index]);
});
//alert(ids);
var formData = $(this).parents('form').serialize();
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data:"id="+ids,
success: function() {
alert('Record has been delete');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
and here is code in controller :
function multi_delete() {
$delrec=$_GET['id'];
//debuger::dump($del_rec);
foreach ($delrec as $id) {
$sql="DELETE FROM tickets where id=".$id;
$this->Ticket->query($sql);
};
}
anybody will help me please. thank
you could try a .join(',') on the array of IDs and then an explode() on the server side to get the array of IDs passed to the script.
e.g.
var idStr = ids.join(',');
pass it (idStr) to the ajax call
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: {id:idStr},
//more code cont.
on the server side:
$ids = explode(',',$_POST['ids']);
OR
check the jquery.param() function in the jquery docs. Apply and to the IDS array and then pass it to $.ajax({});
Note: You are using POST and not GET HTTP METHOD in the code you provided
use json encode and decode for serialized data transfer
Since JSON encoding is not supported in jQuery by default, download the JSON Plugin for jQuery.
Your javascript then becomes:
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: { records: $.toJSON(ids) },
success: function() {
alert('Records have been deleted.');
},
});
In the controller:
var $components = array('RequestHandler');
function multi_delete() {
if (!$this->RequestHandler->isAjax()) {
die();
}
$records = $_POST['records'];
if (version_compare(PHP_VERSION,"5.2","<")) {
require_once("./JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$selectedRows = $json->decode(stripslashes($records));//decode the data from json format
} else {
$selectedRows = json_decode(stripslashes($records));//decode the data from json format
}
$this->Ticket->deleteAll(array('Ticket.id' => $selectedRows));
$total = $this->Ticket->getAffectedRows();
$success = ($total > 0) ? 'true' : 'false';
$this->set(compact('success', 'total'));
}
The RequestHandler component ensures that this is an AJAX request. This is optional.
The corresponding view:
<?php echo '({ "success": ' . $success . ', "total": ' . $total . '})'; ?>
Wish you luck!