PHP handling data POSTED via AJAX - php

I need to loop through some data that was posted to a PHP page through AJAX. I've read about a dozen answers here and none are working for me. This is what my data object looks like before the post:
{"sessionValues":[{"ProductID":"507","State":"CHECKED"}, {"ProductID":"204","State":"UNCHECKED"}]}
I then post it like this:
$.ajax({
url: 'setSessionValues.php',
type: 'post',
data: {"session" : JSON.stringify(postObj)},
success: function(data) {
console.log(data); // Hello worldData: , Data: ,
}
});
This is the last thing that I tried in PHP:
if (isset($_POST["session"])) {
echo "Hello world";
$session = json_decode($_POST["session"]);
echo "Data: " . $session->sessionValues[0]->ProductID . ", " . $session->sessionValues[0]->State;
$session = json_decode($_POST["session"], true);
echo "Data: " . $session['sessionValues'][0]['ProductID'] . ", " . $session['sessionValues'][0]['State'];
}
Everything I've tried either throws out blanks or errors.
Edit:
Turns out that it doesn't like my data. Syntax Error: Unexpected end of input. Any ideas on that?

The second thing (xdebug is the first one) you should have tried in PHP is
if (isset($_POST["session"])) {
$session = json_decode($_POST["session"]);
print_r($session);

Related

Creating JavaScript variable within PHP retrieving in JavaScript

Basically what I have is, there is an index file, that links to a JS file, which then pulls in a PHP file.
So in the PHP file I have (along with other code) :
echo " <script type='text/javascript'>var paging = [ ";
echo "{";
echo "numrows:'" . number_format($numrows) . "',";
echo "pagenum:'" . number_format($pagenum) . "',";
echo "maxpage:'" . number_format($maxpage) . "',";
echo "record_min:'" . number_format($record_min) . "',";
echo "record_max:'" . number_format($record_max) . "'";
echo "}];</script>";
Then, in a JS file I use ajax:
req.open("GET", "server.php", true);
and within the readystatechange I need to retrieve that paging variable you see from the php file because it contains data from the database.
In the JS file I have tried using a variable instead of echo
var m=<?PHP echo $paging; ?>
but that doesn't work either.
Any suggestions or ideas how to get this to work?
I'd use JSON instead of JS. You should be able to pass a PHP array to the json_encode function. See: http://php.net/manual/en/function.json-encode.php
Also, on the PHP side, you may want to modify your response headers to indicate that the response message body is JSON:
header( 'Content-Type: application/json' );
Then, use jQuery to get the JSON from the server: http://api.jquery.com/jQuery.getJSON/
Another possible solution for you if you don't get direct JSON working (scaled down to two variables)
echo '<div id = "numrows">'. number_format($numrows) . '</div>';
echo '<div id = "pagenum">'. number_format($pagenum) . '</div>';
in the php file
req.onreadystatechange = function(){
if (req.readyState == 4 && req.status == 200){
document.getElementById('return').innerHTML = req.responseText;
}
}
req.open("GET", "server.php", true);
req.send();
n["numrows"] = document.getElementById("numrows").innerHTML;
e = document.getElementByID("numrows");
e.parentNode.removeChild(e);
n["pagenum"] = document.getElementById("pagenum").innerHTML;
e = document.getElementByID("pagenum");
e.parentNode.removeChild(e);
in the javascript
<div id = "return" style="display: none;"></div>
in the html
Not the most elegant solution, but fairly straightforward to follow if you can't get anything else working.
Ok because jQuery makes this easy, here is my example:
$paging = array(
"numrows" => number_format($numrows),
"pagenum" => number_format($pagenum),
"maxpage" => number_format($maxpage),
"record_min" => number_format($record_min),
"record_max" => number_format($record_max)
);
$output = json_encode($paging);
header( 'Content-Type: application/json' );
echo $output;
Then in your javascript page using jquery do this:
function myCallBackFunction(data){
alert(data.numrows);
}
$.getJSON('server.php',myCallBackFunction(data));
Hope this helps.
Edited to use array and json_encode

Can't get custom JSONP pipeline to work

I'm building an audio player that makes 3 different API calls, and I need them all to be in JSONP format, so I made a PHP proxy file that determines the output of the JSON data like so:
$datatype = $_GET["type"];
$artist = urlencode($_GET["artist"]);
$album = urlencode($_GET["album"]);
$content = "";
if($datatype == 'albumart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&album=' . $album . '&format=json');
} elseif($datatype == 'artistart'){
$content = file_get_contents('http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&api_key=037358e302c80571663e6a7a66b1dc05&artist=' . $artist . '&autocorrect=1&format=json');
} else {
$content = file_get_contents('http://cjzn.streamon.fm/metadata/recentevents/CJZN-48k.json');
}
header('Content-type: application/json; charset=utf-8');
echo $_GET['callback'] . '(' . json_encode($content) . ')';
Upon testing the output it seems to work fine, it gets the respective API data, wraps it in the JSONP () and accepts a JSONP callback.
Bur when I try and use it in my Javascript file it doesn't seem to work, but I can't figure out why! Here's an example of one of the functions being used to call the JSON data:
function getAlbumArt(artist,album){
var dataArtist = artist,
dataAlbum = album,
albumArtURL;
$.ajax({
url: 'jsonproxy.php',
dataType: 'jsonp',
data: {
type: 'albumart',
artist: dataArtist,
album: dataAlbum
},
success: function(data) {
if(data.album.image[4]["#text"]){
var albumArtURL = data.album.image[4]["#text"];
$('section.player div.album-artwork').css({'background-image':'url("' + albumArtURL + '")'});
} else {
getArtistArt(dataArtist);
}
},
error: function() {
getArtistArt(dataArtist);
alert('Sorry, unable to retrieve album artwork!');
}
});
}
Can anyone help with why this doesn't work for me?
Edit
I did alert(data); on success, and that returned all of the data from the feed, after that if I did something more specific like alert(data.album.image[4]["#text"]); it returned undefined. Very confused here. Anyone have any thoughts?

<img> not being refreshed with jQuery

I am developing with xhtml, LAMP and jQuery 2.0.2 on Debian 7.0.0.
I am using the following php-generated element
echo "<img id=\"displayImageID\" src=\"" . $DisplayFileName . "\" alt=\"Background\" style=\"margin:10px 0px 10px 5px\"/>";
I am hoping to change it to a different color look up table when the used clicks on a radio button. In order to do this, I use the following code
jQuery.ajax({
type: "POST",
url: "DisplayParameters.php",
data: { LUT:lut }
}).done(function( result ) {
$("#msg").html( " Ajax called" );
});
with the following code in DisplayParameters.php
$LUT=$_POST['LUT'];
$Executable="Executables/changeLUT";
$DisplayImageName="images/display.png";
$Str=$Executable . " -t " . $LUT" . " -o " . $DisplayImageName;
$output=exec($Str, $dummy, $returnValue);
echo "<script language=\"JavaScript\">";
echo "d = new Date();";
echo "jQuery('#displayImageID').attr('src', '" . $DisplayImageName . "?'+d.getTime());";
echo "</script>";
}
to update the image and to reload it into the image element but nothing happens until I refresh the whole page with the Firefox "Reload current page".
I had thought that maybe, due to the asynchronous nature of Ajax, the image is getting loaded before it is replaced by a new image with the same name but different color LUT. However, if this were the case, I would expect the new LUT image to eventually be loaded if I keep clicking on radio buttons after the image that is saved to the disk is changed. This is not the case. I do not get a new image until I reload the page.
Try this:
JS
jQuery.ajax({
type: "POST",
url: "DisplayParameters.php",
data: { LUT:lut },
cache: false //CHANGED
}).done(function( result ) {
$("#msg").html( " Ajax called... and returned " + result );
//('#displayImageID').attr('src', result);
('#displayImageID').attr('src', result+'?'+$.now()); //CHANGED
});
PHP
$LUT=$_POST['LUT'];
$Executable="Executables/changeLUT";
$DisplayImageName="images/display.png";
$Str=$Executable . " -t " . $LUT" . " -o " . $DisplayImageName;
$output=exec($Str, $dummy, $returnValue);
echo $DisplayImageName; //CHANGED

Parse XML in Js for Website

Hy!
I am very new in Web-Dev. I have a mysql db and the controller is made with PHP.
I give the data formated in php back to the html.
My Quest:
How to parse the xml in js right for the HTML based view?
If there are better solutions for the data transfair between PHP and HMTL, please let me know.
I don't wont the have HTML code in the php
Example PHP:
<?php
$id = $_GET['id'];
if (is_numeric($id))
{
include 'db_connect.php';
$sql = "Select * from RECIPES WHERE recipes_id=".$id;
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
while($row = mysql_fetch_array($result))
{
echo "<RECIPE>";
echo "<ID>" . $row['recipes_id'] . "</ID><br />";
echo "<TITLE>" . $row['text'] . "</TITLE><br />";
echo "<TEXT>" . $row['text'] . "</TEXT><br />";
echo "<COUNT_PERSONS>" . $row['count_persons'] . "</COUNT_PERSONS><br />";
echo "<DURATION>" . $row['duration'] . "</DURATION><br />";
echo "<USER_ID>" . $row['user_id'] . "</USER_ID><br />";
echo "<DATE>" . $row['date'] . "</DATE><br />";
echo "</RECIPE>";
}
}
else
{
echo "<ERROR>ID ERROR</ERRORR>";
}
mysql_close($db);
?>
thx
If you just want to transfer data between the browser and the server then it's simpler to use the JSON format. For PHP there are two built in function to decode and encode JSON: json_decode and json_encode.
Modern browser support JSON by default: JSON.parse and JSON.stringify.
I agree with styrr, but if you must use XML then you can use jQuery.parseXML() or simply use jQuery.ajax() with correct type eg.:
$.ajax({
url: "script.php?parameters=abc",
dataType: "xml",
success: function(responseDocument){
var all_ids = responseDocument.getElementsByTagName('ID');
var all_ids_jquery_way = $('ID', responseDocument);
}
});
You can use any othe AJAX framework or even write your own function. Browsers can parse XML and create a document which you can then change as the main document (with DOM functions).
Again with most data JSON is a bit simpler to use and is lighter.

Jquery/Ajax and PHP rendering TR

I am scraping sites, and I am doing this one at a time, and then trying to get the results to display AS I get them. I am trying to render one TR at a time, but instead, it does every single one, and then renders ALL the TRs.
Here is the call to javascript:
<body onload="getOffers(companies , {$scraped}, {$isbn13});">
Here is the JS/Jquery function:
function getOffers($company_ids, $scraped, $isbn)
{
if($scraped)
{
$.ajaxSetup({cache: false});
for(var $id in $company_ids)
{
$.ajax({
url: "../get_offer.php",
data: "id=" + $company_ids[$id] + "&isbn=" + $isbn + "&code=" + $id,
dataType: "html",
success: function(data) {
$("#results tbody:last").append(data);
}
});
}
}
else
{
return true;
}
}
And here is the PHP page:
<?php
require_once 'scrape.php';
require_once 'include.php';
$id = requestValue('id');
$isbn = requestValue('isbn');
$code = requestValue('code');
$page = curlMultiRequest(isbn10($isbn), $id);
$offer = getOffer($code, $page[$code], isbn10($isbn));
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
?>
I tried returning the sting I am printing, but that didn't even work. How can I make it print each table row to the screen as the data is retrieved?
EDIT: so I tried adding this:
print "<tr><td>". $offer['company']."</td><td>". $offer['offer_new'] . "</td><td>" . $offer['offer_used']."</td></tr>";
ob_flush();
flush();
To the PHP and it didn't work. I don't understand, if I throw an alert, it happens on the fly for every ID, but the html rendering does not.
It may have magically fixed itself because your browser was caching some of the javascript. You should use some developer tools to manually flush the cache of resources for the host you are testing on to avoid old code being subtly used ....

Categories