I'm trying to pull json data via ajax from a PHP script, but it is not working.
while ($row = mysql_fetch_array($result)) {
$response = array(
'hello' => $row['name']
);
$responses[] = $response;
}
echo json_encode($responses);
Then I use this JavaScript
$('.clickme').click(function() {
$.ajax({
url: 'http://example.com/testFixGet.php?department=1',
dataType: 'json',
data: 'manufacturer=alpine,kicker',
success: function(json) {
alert(json['hello']);
$('.result_new').html(json);
}
});
});
The dialog presents: 'Undefined'
But, if I actually load the php page the data is json decoded and it looks like this:
[{"hello":"Rand McNally Soft Case for Most 5\" GPS"}]
You'll notice your JSON payload contains an array with one object element. Try
alert(json[0]['hello']);
Also, getJSON() is much more concise
$('.clickme').click(function() {
$.getJSON('http://example.com/testFixGet.php', {
department: 1,
manufacturer: 'alpine,kicker'
}, function(json) {
// loop over results
for (var i = 0; i < json.length; i++) {
var response = json[i];
console.log(response);
}
});
});
Try this:
$('.clickme').click(function() {
$.getJSON('testFixGet.php', { manufacturer: "alpine,kicker", department: "1" }, function(json) {
alert(json[0].hello);
$('.result_new').html(json);
} );
}
Are you setting the content type?
header('Content-type: application/json');
ANd by the way
[{"hello":"Rand McNally Soft Case for Most 5\" GPS"}]
it is an array so it would be
alert(json[0]["hello"]);
To loop
var bar = [{"a":"1"},{"a":"2"},{"a":"3"}]
$.each( bar, function(i, jObj){
alert( jObj.a );
});
Related
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?
When I use JSON.stringify, the data that is in it can't be send for some reason. But when I remove JSON.stringify, it does send and I would like to know why? Is there a way to controll the json data in PHP file without using stringify? Any help is much appreciated!
$(document).ready(function(){
$.ajax({
dataType: "jsonp",
url: "***/server/jsonp/data",
callback:"test",
success: jsonSuccess
});
function jsonSuccess( data ){
for( var i = 0; i < data.length; i++ ){
if ( i == 0 ) {
var formData = {name:"tolga",age:"25"}; // test object
$.ajax({
type: "POST",
url: "wp-content/themes/flex/saveJsonInfo.php",
data: { info: JSON.stringify(data[i]) }
}).done(function(data2) {
console.log(data2);
});
}
}
}
});
The json data that I receive is something like this:
test([{"EniNumber":"22325326","Name":"Test Fi","StartDate":"\/Date(1381788000000)\/","Rows":[{"T":42878,"Y":51.880965,"X":4.395925,"D":14.56},{"T":42879,"Y":51.880967,"X":4.395925,"D":14.56},{"T":42880,"Y":51.880967,"X":4.395925,"D":14.59}]}, {"EniNumber":"12312312","Name":"Test Fi 2","StartDate":"\/Date(13817880021300)\/","Rows":[{"T":42878,"Y":51.880965,"X":4.395925,"D":14.56},{"T":42879,"Y":51.880967,"X":4.395925,"D":14.56},{"T":42880,"Y":51.880967,"X":4.395925,"D":14.59}]}])
This is how my PHP example file looks:
$json_data = $_POST['info'];
if( isset($json_data) ){
echo json_encode( $json_data );
} else {
echo json_encode( "What happened?" );
}
Hey I have a script that is creating and echoing a JSON encoded array of magento products.
I have a script that calls this script using jQuery's ajax function but I'm not getting a proper response. When the GET request is performed firebug displays
GET http://localhost.com/magento/modules/products/get.php 200 OK then a **red cross** then 361ms
This is the script that creates the array:
// Load product collection
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('price');
$products = array();
foreach ($collection as $product){
$products[] = array("price" => $product->getPrice(),
"name" => $product->getName() );
}
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($products));
Here is my jQuery:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://localhost.com/magento/modules/products/get.php",
success: function(products)
{
$.each(products,function()
{
var opt = $('<option />');
opt.val(this.name);
opt.text(this.price);
$('#products').append(opt);
});
}
});
})
</script>
I'm getting a response from this but I'm not seeing a any JSON. I'm using firebug. I can see there has been a JSON encoded response but the response tab is emtyp and my select boxes have no options.
Can anyone see and problems with my code?
Here is the response I should get (and do get when I run the script manually via the browser):
[{"price":"82.9230","name":"Dummy"},{"price":"177.0098","name":"Dummy 2"},{"price":"76.0208","name":"Dummy 3"},{"price":"470.6054","name":"Dummy 4"},{"price":"357.0083","name":"Dummy Product 5"}]
Thanks,
Billy
use cache: false, as one of your AJAX parameters...
I know when i used JSON in AJAX, i had to do this:
success: function(data) {
$(".custName, .projectDesc").empty();
for(var x in data) {
$(".custName").append(data[x].message1);
$(".projectDesc").append(data[x].message2);
}
I'm not sure if this will help you or not :)
The PHP you're returning is not an array of objects, which is the way you are treating it in your javascript.
Change your PHP to:
$products = array();
foreach( $collection as $product ) {
$products[] = array( "price" => $product->getPrice(),
"name" => $product->getName() );
}
This should return JSON that looks like:
[{"price":"82.9230","name":"Dummy"},{"price":"177.0098","name":"Dummy 2"}, etc ]
jQuery.each should then be able to iterate over the returned array of objects:
success: function(products)
{
jQuery.each(products,function()
{
var opt = jQuery('<option />');
opt.val(this.name);
opt.text(this.price);
jQuery('#products').append(opt);
});
}
$.each(products,function(index, arr)
{
var opt = $('<option />');
opt.val(arr[name]);
opt.text(arr[price]);
$('#products').append(opt);
});
I hope it helps you
Try to add data type property on $.ajax configuration object:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://localhost.com/magento/modules/products/get.php",
dataType : 'json',
success: function(products) {
$.each(products,function() {
var opt = $('<option />');
opt.val(this.name);
opt.text(this.price);
$('#products').append(opt);
});
}
});
})
</script>
Maybe, $.ajax function doesn't know the response data type...
Add dataType: 'json' in jQuery.ajax parameter
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!