PHP: Retrieving JSON via jQuery ajax help - php

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

Related

take data array from jquery ajax

I'm trying to get a simple callback in a direct way
$(function(){
$("input[name='inputs_picture']").on("change", function(){
var formData = new FormData($("#frn_pic_id")[0]);
var ruta = "image-ajax.php";
$.ajax({
url: ruta,
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(datos)
{
var $directions = datos;
var $prov_rut = $directions['prov_rut'];
$("#picture_product").html($prov_rut);
$("#ajax_res").attr("style", "visibility: visible");
}
});
});
});
var $directions is an array that I create in a very simple way
$src = $folder.$name;
$directions = array();
$directions["prov_rut"] = $prov_rut;
$directions["destino"] = $src;
echo $directions;
What I want to do is simply get the values of the array and use them later, I've tryed everything
Thank you in advance for taking a minute to take me out of this blocked.
Echoing an array doesn't do anything useful, it just prints the word Array. You need to use JSON.
echo json_encode($directions);
Then in the $.ajax() code, use:
dataType: 'json',
to tell jQuery to parse the JSON result. Then you'll be able to use datos.prov_rut and datos.destino in the success: function.
you can use json_encode function to encode convert your php array to json array
echo json_encode($directions);
To parse the json in ajax success you can use
var response = JSON.parse(datos);
response will be json object
so what kind of array are we talking here if its single diamention array lek [10,20,30]
then you can do
for(var i=0 ;i< datos.length; i++)
{
var val = datos[i];
}
if its array of object (json) [{id:1,nam:Rahul}] then
$(datos).each(function()
{
val = this.objectName
})

Accessing an array in PHP from Javascript/jQuery

I have all my html, php and javascript/jquery code in a single file. I have an array $arr in php (json_encode($arr)) which when printed shows the data in php. How do I access it in javascript. The array contains all the rows from the resultset of a query execution. I have looked up jsonParse and var json_obj = but have not got any results. I am newbie so any help is appreciated. My code so far in php :
$result_again = $conn->query($sql_again);
if ($result_again->num_rows > 0)
{
$resultarray = array();
while($row_again = $result_again->fetch_assoc())
{
$resultarray[] = $row_again;
}
}
echo json_encode($resultarray);
My code in the .js file :
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(data) {
alert("Result: " + data);
}
});
});
Step 1:
Render json_encode($arr) into javascript string variable.
var json = '<?= json_encode($arr) ?>';
Step 2:
Parse JSON string into javascript object.
var obj = JSON.parse(json);
Or if you're using jQuery:
var obj = jQuery.parseJSON(json);
You now have a javascript object which you can access properties of like below :)
alert(obj.title); // show object title
alert(obj[0].id); // grab first row of array and show 'id' column
Edit -- in reply to slugspeeds update
Ok, so looks like you're doing this the AJAX way using jQuery. Since your PHP script is using json_encode() the jQuery $.ajax() should return an javascript array object.
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(arr) {
console.log(arr); // show array in console (to view right-click inspect element somewhere on screen, then click console tab)
$.each(arr, function( index, row ) { // loop through our array with jQuery
console.log('array row #'+index, row); // show the array row we are up to
// you can do what you want with 'row' here
});
}
});
});
For reference:
https://developer.chrome.com/devtools/docs/console

how do I get my ajax data into a php array?

I have the following data in a JS script:
$("#holdSave").live('click', function () {
var arr = {};
var cnt = 0;
$('#holdTable tbody tr').each(function () {
arr[cnt] = {
buyer: $(this).find('#tableBuyer').html(),
sku: $(this).find('#tableSku').html(),
isbn: $(this).find('#tableISBN').html(),
cost: $(this).find('#tableCost').val(),
csmt: $(this).find('#tableConsignment').val(),
hold: $(this).find('#tableHold').val()
};
cnt++;
}); //end of holdtable tbody function
console.log(arr);
$.ajax({
type: "POST",
url: "holdSave.php",
dataType: "json",
data: {
data: arr
},
success: function (data) {
} // end of success function
}); // end of ajax call
}); // end of holdSave event
I need to send this to a php file for updating the db and emailing that the update was done. My console.log(arr); shows the objects when I run it in firebug, but I can't get any of the information on the php side. Here is what I have for php code:
$data = $_POST['data'];
print_r($data); die;
At this point I am just trying to verify that there is info being sent over. My print_r($data); returns nothing.
Can anyone point me in the right direction please?
dataType: "json" means you are expecting to retrieve json data in your request not what you are sending.
If you want to send a json string to be retrieved by $_POST['data'] use
data: {data: JSON.stringify(arr)},
Use the json_encode() and json_decode() methods
Use the next way:
data = {key1: 'value1', key2: 'value2'};
$.post('holdSave.php', data, function(response) {
alert(response);
});
Note: haven't tested it, make sure to look for parse errors.

ajax json decode returning undefined not data

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 );
});

jquery: calling invisible php-mailer? ajax?

hey guys,
i know how to create a simple php file that mails some information to me.
However what I don't know is how to call that php-file with jquery and hand over a variable.
Handing over a variable might work with isset()...
How can I call this PHP mailer from jquery and do that HIDDEN from the user. So there should not pop up a new window and shouldn't be a page refresh or anything like that.
$('a.report').click(function(e) {
e.preventDefault();
var id = $(this).attr('href');
//call mail script and pass along the "id" variable
//change text (maybe in a callback function IF THE MAILING WAS A SUCCESS.
$(this).parent().text('Thank you for reporting.');
})
So I have this a.report Link which should trigger the email script. In my email script I need to access the "id" variable set in jquery. And it would even be nice to have a callback function if the php script did it's thing so I could output "Thank you for reporting".
How to do that?
Thank you guys.
I would use $.post():
<script type='text/javascript'>
$(function(){
function onReportPosted(data) {
// data.status - either 'error' or 'success', from mailer.php
// data.message - some text, from mailer.php
$('.result').text(data.message);
}
$('a.report').click(function(e) {
$('.result').text('sending report...');
var data = {
text: $('textarea[name=text]').val()
};
$.post(
'mailer.php',
data,
onReportPosted,
'json'
);
return false;
});
});
</script>
And in mailer.php:
<?php
if ( isset($_POST['text']) ) {
// mail()...
$result = array(
'status' => 'success',
'message' => 'thank you for reporting',
);
} else {
$result = array(
'status' => 'error',
'message' => 'some error occurred',
);
}
header('Content-Type: application/json');
echo json_encode($result);
exit;
Update: here's a way how to "tie" callback to a specific element:
<script type='text/javascript'>
$(function(){
$('a.report').click(function(){
var htmlElement = $(this).parent();
var data = {
// ...
};
$.post(
document.location.toString(),
data,
function(data) {
htmlElement.html(data.message);
},
'json'
);
return false;
});
});
</script>
see $.post to know how to call and pass the id to the php script (http://api.jquery.com/jQuery.post/)
It will be somthing like
$.ajax({
context: $(this),
type: 'POST',
url: 'script.php',
data: {id: id },
success: function() {
$(this).parent().text('Thank you for reporting.');
}
});
And in the php script, $id = $_POST['id'];
try:
$.post('script.php', {variableName: value, variable2Name: value2});
in php: $value = $_REQUEST['variableName']; $value2 = $_REQUEST['variable2Name'];
jQuery provides some great AJAX methods for us under the AJAX API catagory. I think $.post would be what you're looking for. This is how I send JSON data to a simple PHP script in my Grooveshark userscript:
$.ajax({
type: 'POST',
url: 'http://path/to/script.php',
data: JSON.stringify({key: 'value', array: ['one', 'two', 'three']),
dataType: 'json',
success: function(data){
console.log('Mailer returned with object ', JSON.parse(data) );
}
});
And here's how I parse it in PHP:
$incoming = json_decode(file_get_contents("php://input"), true);
This returns nested associative arrays for the JSON content, very easy to parse! I highly recommend using JSON as your data interchange format. Much better than XML.

Categories