Sending JSON jQuery Ajax to PHP and back - php

I'm having problems sending a JSON jQuery array via Ajax to a PHP script. What is the problem here:
var tee = $('#voting_image img').attr('id');
var vote = 1;
var thing = {tee: tee, vote: vote};
var encoded = $.toJSON(thing);
$.ajax({
url: '/vote_save.php',
type: 'POST',
dataType: 'json',
data: 'vote='+encoded,
success: function(data)
{
var back = $.evalJSON(data).name;
$('#voting_hint_name').html(back);
$('#voting_buttons').html('<div id="voting_buttons">PRINT ITDON\'T PRINT IT</div>');
},
error:function ()
{
$('#voting_buttons').html('<div id="voting_buttons">PRINT ITDON\'T PRINT IT</div>');
alert("There was a problem, your vote was not saved, please try again!");
}
});
This is the PHP
if (isset($_POST['vote'])&&isset($_SESSION['user']))
{
$tee_data = json_decode($_POST['vote']);
$the_tee = $tee_data['tee'];
$responce = array('name'=> 'Alex Wow', 'test'=> '1');
echo json_encode($responce);
}
else {
echo "error";
}
The error I am getting in Firebug is:
Error: JSON.parse

AFAIK, there is no $.toJSON method in jQuery, you are probably looking for $.parseJSON and by the way you are already creating JSON here:
var thing = {tee: tee, vote: vote};

I think the problem is that you send data as object, try to send as array
var thing = {tee: tee, vote: vote}; to array

Check out this question: Serializing to JSON in jQuery
The accepted answer links to a JSON serialization plug-in recommended by John Resig (the creator of jQuery). It doesn't really address your specific bug, but perhaps using that plug-in will help you arrive at a stable solution.
From looking at it briefly, if you use that plug-in, it appears you would then replace this line:
var encoded = $.toJSON(thing);
with this:
var encoded = JSON.stringify(thing);
Hope that helps!

Thanks for your responces, I went with:
$.getJSON(
'/vote_save.php?vote='+encoded,
function(data)
{
$('#voting_hint_name').html(data.bob);
$('#voting_buttons').html('<div id="voting_buttons">PRINT ITDON\'T PRINT IT</div>');
}
);
instead of $.ajax and it worked.

Related

Use Jquery AJAX to get PHP Object

To try and be as short and sweet, yet as descriptive as possible i am having issues grabbing a PHP Object through Jquery Ajax.
I am a semi-new PHP developer and i have created an object containing some strings and variables as shown here:
calculation.php
$return = new stdClass;
$return->success = true;
$return->errorMessage = "Oops, something went wrong!";
$return->Score = number_format($scoreFromSheet,1);
$return->roi = number_format($roiFromSheet,1);
$return->dvScoreAnalysis = $scoreAnalysis;
$return->className = $className;
$json = json_encode($return);
echo $json;
I have constructed a very crude Ajax call to the PHP file to try to access the json_encoded object. As shown here:
finalPage.php
$(document).ready(function(){
var data;
$.ajax({
dataType: "json",
url: './dvs_calculation/calculation.php',
data: {data:data},
success: function (json) {
alert('working');
console.log(json[0].Score);
},
error: function(xhr, textStatus, errorThrown) {
alert( "Request failed: " + textStatus );
}
});
});
I have echo'd the object to the DOM to display the output of my object, and it looks pretty solid:
$json output
{
"success":true,
"errorMessage":"Oops, something must've gone wrong!",
"Score":"65.5",
"roi":"25.8",
"ScoreAnalysis":"High Deal Viability"
}
When using the Ajax function i receive a parse error and it prints out nothing from the success function. Not sure where i am going wrong. Any help or reference greatly appreciated.
Access the Score value from the json response as
json.Score //gives you the value of Score key from json
Also according to the code provided, you aren't passing anything to the php side as the data variable is just defined

javascript image upload via datauri and php base64 decode

I am trying to make an image upload where the JavaScript posts DataURI of an image via AJAX and the PHP receives it to decode it into an image.
The problem is, everything is working fine except that the end product is not an image file.
Please have a look at the following example code.
JavaScript:
dataString='encodedimg='+e.target.result.match(/,(.*)$/)[1]+'&type='+type;
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
data: dataString,
success: function(data){
//print success message
});
PHP:
$encodedimg = $_POST['encodedimg'];
file_put_contents('asdf.png', base64_decode($encodedimg));
There is no problem with $_POST['encodedimg'] as it produces the right image using online base64 converter. So I am assuming that there is a misuse with file_put_contents() or base64_decode().
Appreciate the help!
To read image on PHP i used a function like this
function rcd($data) {
$p = strpos($data, ',');
$d = base64_decode(substr($data, $p+1));
$rfn = md5(mt_rand(1,123123123));
file_put_contents($rfn, $d, LOCK_EX);
return $rfn;
}
Usage example:
$img_file_name = rcd($_POST['image_data']);
On JS part it is tricky (different browsers, etc). First of all You need to have the image data. Now You do not precise how this is sourced and the code example does not give a hint. We can assume some options
Simple You get dataString properly populated by whatever means neccesary, then Your example should basically work
imgdata = .... // any means of getting the data
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
});
Not so simple You have a Canvas object on the screen which was populated by any means and You want to send that data. Whatever above is true, however the way to get image data would be
var canv = document.getElementById('id_of_canvas');
imgdata = canv. toDataURL('image/jpeg', 0.88); // last arg is quality
However, as some browsers (mobiles) might not be so lucky to support this, you might want to find JPEGEncoder for JS and add it, along with the code below, to Your project.
var tdu = HTMLCanvasElement.prototype.toDataURL;
HTMLCanvasElement.prototype.toDataURL = function(type,param1)
{
var res = tdu.apply(this,arguments);
if(res.substr(0,11) != "data:image/")
{
var encoder = new JPEGEncoder();
return encoder.encode(this.getContext("2d").getImageData(0,0,this.width,this.height), (param1 ? param1*100 : 88));
}
else return res;
}
Hope this helps!
FOr #Marcin Gałczyński:
$.ajax({
url: 'uploadhandler_ajax.php',
type: 'POST',
image_data: imgdata,
success: function(data){
//print success message
}
})
I think jQuery.ajax didnt have image_data jQuery.ajax

Passing javascript array to php to print values does not work

I want to pass a javascript array to php to print the values, but it is not working. What am I doing wrong?
javascript
$('#Enviar0').click(function() {
var buttons0 = [];
for(var i=0;i<4;i++){
buttons0[i]+= $('butEnv'+i).val();
alert($('butEnv'+i).val());
}
var array=buttons0.toJSONString();
$.ajax({
type:"POST",
url:"pintaParte.php",
data: {encapsulado:array},
success: function(data) {
$("#pinta").html(data);
}
});
});
php
$buttons0=parseJSON($_POST['encapsulado']);
foreach ($buttons0 as $value) {
echo $value.'<br>';
}
use JSON.stringify() on the client side:
$.ajax({
type:"POST",
url:"pintaParte.php",
data: JSON.stringify({encapsulado:array}),
success: function(data) {
$("#pinta").html(data);
}
});
Do you check if your array is ok in the php side (after the ajax call) ?
If you can't get your array in the php side, maybe in your javascript try to simply use...
data : "encapsulado=" + array
And in your php code, try to put all values of the array in one string and just make only one echo and then a return.
$str = "";
foreach ($buttons0 as $value) {
$str = $str.$value.'<br>';
}
echo $str;
return;
Try to use a tool like firebug or the Chrome dev tool to see parameters and responses in your http requests and be abble to localize the error (in the client side or in the server side).
Hope this helps !

How to send a json string back to jquery

I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.
This is the jQuery code that sends the data to the external page:
function LoadImageData(url)
{
$.ajax({
url: 'get_image_data.php',
dataType: 'json',
data: {'url': url },
success: SetTag()
});
}
This is the PHP code htat receives the data and is required to send some data back:
<?php
require_once('FaceRestClient.php');
$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);
$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);
return $photos;
?>
So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.
Thanks in Advance,
Mark
You need to echo the resulting JSON:
echo $photos;
If $photos is not already JSON, use json_encode:
echo json_encode( $photos);
One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?
You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.
Try this:
$.ajax({
url: 'get_image_data.php',
type: 'POST',
data: {'url': url }
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('Your ajax just failed');
});
Open the console, and see what is printed
At the end of a PHP function I tend to do :
exit(json_encode($someData));
To return the data as JSON, but anything that prints the data is ok.
try this
echo json_encode( $photos);
you need to echo
echo $photos;
and as metntoned by #nickb if $photo is not already a json then convert it into json first and then echo.
echo json_encode($photos)
in jQuery if you want to fetch the data
onSuccess: function(data, status) {
//var data contains the returned json.
}

Xml reply from PHP to post of jquery Ajax

i have a javascript code that requests a php page to provide it with list of names that are currently online and update a Table, but i have a problem sending it back in form of an array, someone told me that this is usually done using XML, but i dont know how to start.
javascript Post method:-
$.post( "updateTable.php", POSTdata,
function( data ) {
$("#mytable").last().append('<tr><td>'+data+'</td></tr>');
}
);
the php file:-
include("connect.php");
$query1 = "SELECT * FROM formtable";
$result_id = mysql_query($query1, $global_dbh)
or die ("display_db_query:" . mysql_error());
while ($table_array = mysql_fetch_object ($result_id))
{
$rows[] = $table_array;
}
foreach ($rows as $temp ) {
if ($temp->isOnline==1)
$newRow[] = $temp->name;
}
echo "$newRow";
mysql_close($global_dbh);
Please excuse any syntax or semantics in my code, i am a beginner.
How can i populate my table using ajax callback function, and in what form the data will arrive there, and how can i use xml to help me.
Many thanks in advance.
A quick example of json:
var table = $("#mytable").last();
$.ajax({
type: 'post',
url: "updateTable.php",
dataType: 'json',
data: POSTdata,
success: function(data){
jQuery.each(data, function(i, row){
//console.log(row);
table.append('<tr><td>'+row.name+'</td></tr>');
});
}
});
and in php file, instead of :
echo "$newRow";
replace with:
echo json_encode($newRow);
That's it!

Categories