JSON working one place but not another - php

I'm redesigning my site to base it off WordPress, and in the process, I need to import some PHP/jQuery. I find that it works fine on the original page but not the new one.
Here are the results of the JSON dumps:
Old - empty as it should be because no data
New - doesn't like using $_POST['club'] to import
The code in both instances is:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "post",
url: "eventinfo.php",
data: $('#club').serialize(),
success: function(data) {
$('#right_inside').html('<h2>' + $('#club').val() + '<span style="font-size: 14px"> (' + data[0].day + ')</h2><p>Entry: ' + data[0].entry + '</p><p>Queue jump: ' + data[0].queuejump + '</p><p>Guestlist closes at ' + data[0].closing + '</p>');
},
dataType: "json"
});
});
$('#club').change(function(event) {
$.ajax({
type: "post",
url: "eventinfo.php",
data: $(this).serialize(),
success: function(data) {
$('#right_inside').hide().html('<h2>' + $('#club').val() + '<span style="font-size: 14px"> (' + data[0].day + ')</h2><p>Entry: ' + data[0].entry + '</p><p>Queue jump: ' + data[0].queuejump + '</p><p>Guestlist closes at ' + data[0].closing + '</p>').fadeIn('500');
},
dataType: "json"
});
});
</script>
And my eventinfo.php is:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
include('guestvibe_functions.php');
connect();
$night = $_POST['club'];
$night = mysql_real_escape_string($night);
$query = "SELECT * FROM nights WHERE name = '" .$night. "'";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$items[] = array("entry"=>$row['entry'], "day"=>getLongDateString($row['day']), "queuejump"=>$row['queue jump'], "closing"=>$row['closing']);
}
}
mysql_close();
// convert into JSON format and print
echo json_encode($items);
?>
It's late so I hope I've explained this alright. Any ideas what's wrong?
EDIT
I should add that both are on the same server / hosting plan. The new one is just one directory up.

see this answer for clues
I think you probably have either a newer version of PHP or different server settings on the new PHP server.

I see two possibilities.
The first is that on the new site the club= variable is not populated by AJAX when in the old site it is. Then you must discover why the serialize() does not include a variable called 'club'.
The second is that the club= variable wasn't necessarily populated even in the old site, and you just didn't get the notice warning.
In this case, modifying the code from
$night = $_POST['club'];
in
$night = isset($_POST['club']) ? $_POST['club'] : '';
should solve the problem.
UPDATE
I checked the site, but the eventinfo URL I received is different from the one you quote. What my Firefox got was:
http://www.guestvibe.com/wordpress/eventinfo.php
...which results in a 404 Error.

Related

how to parse id from php page to html-jquery page via jsonp

I have problem to get jsonp from my server by id.
I am sure that my php is good, but i don't know how to parse id from php server to htlm-jquery.
My php page is:
<?php
header('Content-type: application/json');
include 'config.php';
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Could not connect: " . mysql_error());
mysql_select_db($dbname, $con);
$id=$_GET['id'];
$sql = "select * from ios where id=$id";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
////////////////////
?>
And this works great, i got json object by id in php.
You can check for example http://www.dr-trkuljic.com/tekst.php?id=1 (you can try with id 2, 3, and 4) you will get result.
But i don't know how to parse that in jquery in my html page
I am using this in my html page:
$(document).ready(function(){
var output = $('.nesa');
$.ajax({
url: 'http://www.dr-trkuljic.com/tekst.php',
dataType: 'jsonp',
data: 'id',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
So, my question is how to parse (show) by id in my html page?
To be precise how that result from my server http://www.dr-trkuljic.com/tekst.php?id=1 get in my html page?
Thank you.
1 If you are on the same domain
In php change
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
to
echo json_encode($records);
JS success:
success: function(data, status){
var jsonData = JSON.parse(data);
var total = jsonData.length;
for(var i = 0; i < total; ++i){
var ispis = jsonData[i].naziv + " " + jsonData[i]item.tekst;
console.log("My ispis ", ispis);
}
}
2 if you want to use JSONP. (get response from another domain or phonegapp )
When you need a response from another domain you can't use AJAX request, what you can do is load a new script in document for example in tag, You load that script as js script with your response. Inside that js script you put your response in some variable, and also you can call some function that is defined in already loaded js file. for example
echo "var myVar = " . json_encode($records) . '; myCallbackFunc();';
Than load that file as js file to your document
and somewhere in that or where ever js that you want to get response - myVar will contain your response that you can use, and when response load your callback function will be called
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.dr-trkuljic.com/tekst.php?id=1';
head.appendChild(script);
function myCallbackFunc(){
// Do something with myVar
var total = myVar.length;
for(var i = 0; i < total; ++i){
var ispis = myVar[i].naziv + " " + myVar[i]item.tekst;
console.log("My ispis ", ispis);
}
}
EDIT
Just double check if server response - javascript syntax is ok.
As I felt my previous answer was incorrect, allow me to edit:
After you remove the '(' and ')' from around the json array, you can simply use this quick and easy shorthand format for your jQuery http call: (all parsing is already performed because of the Content-Type header). You are then free to access the appropriate properties of the object.
For further examples on how to use jQuery's $.get() and $.post(), etc... visit this link:
http://api.jquery.com/category/ajax/shorthand-methods/
$(document).ready(function(){
var output = $('.nesa');
var idNumber = 1;
$.get('http://www.dr-trkuljic.com/tekst.php', {id: idNumber}, function(data, status){
$.each(data, function(i,item){
//var ispisi = '<li>' + item.naziv + '</li>' ;
var ispisi = item.naziv + item.tekst;
output.append(ispisi);
});
}).fail(function(){
output.text('There was an error loading the data.');
});
});
To overcome cross-domain errors, you can send this header in your php file with the appropriate url of where you're working from:
header("Access-Control-Allow-Origin: http://your-domain-or-localhost");

PHP: Cannot stream CSV file to client in response to AJAX call

I am displaying a report to the client. I have made an ajax call that passes in a "delivery" variable, which is either "display" or "download".
Here is the ajax call:
$.ajax({
type: 'POST',
url: 'ajaxController.php',
dataType: 'json',
data: {
e: "getReport",
reportName: reportName,
delivery: delivery
},
success: function (data) {
if (delivery === 'display') {
$("#reportDisplayTableHeader").html('');
$("#reportDisplayTableBody").html('');
Lifestyle.selectedReportRows = data;
$.each(Lifestyle.selectedReportRows, function(key, row) {
rowHTML = '<tr>';
$.each(row, function(parameter, value) {
if (isHeader) {
rowHTML += '<td>' + parameter + '</td>';
} else {
rowHTML += '<td>' + value + '</td>';
}
});
rowHTML += '</tr>';
if (isHeader) {
$reportHead.append(rowHTML);
isHeader = false;
} else {
$reportTableBody.append(rowHTML);
}
});
$("#reportCaption").show();
}
}
});
And here is the server side PHP:
if ($delivery == 'display') {
echo json_encode($return);
} else if ($delivery == 'download') {
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header('Content-Description: File Transfer');
header("Pragma: no-cache");
header("Expires: 0");
echo "record1,record2,record3\n";
}
In the case of "display" it returns the json just fine and the client side displays a table.
In the case of "download", I want it to pop up a download dialog where it can save off the CSV that I echo'd to them.
But what is happening is that the call is completing and the headers / csv is crossing the wire (thanks Fiddler), but no download dialog is appearing and the client does not know that I pushed csv to them.
What do I need to do in order to get the download dialog to pop up?
Thanks.
An Ajax call can not download something, or at least it is really hard.
Better is to open a new window to the location of the php file (Then you should be using GET though) and then the user will be promted to download it.

$_POST not working

I cannot get my $_POST to work for some reason..Here is the code:
*Javascript that gets called from href onClick event:*
function feedVote(postId, vote) {
if(vote == "1") {
document.getElementById('voteUpSpan' + postId).innerHTML = "Thank you for voting!";
document.getElementById('voteDownSpan' + postId).innerHTML = "";
var i = new Image();
var d = new Date();
i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;
}
}
So it spoofs a image and runs my voteUp.php page passing the parameters without changing the current page.
<?php
$id = $_POST['postId'];
$con = mysql_connect("localhost", "username", "password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("database", $con);
$update = mysql_query("UPDATE posts SET upvote = upvote + 1 WHERE id = '$id'");
mysql_close($con);
echo "$id";
?>
The echo "$id"; returns nothing so its obviously not even putting a variable in $id which is why my sql statement is not being run but why...
When I run the code in Google Crome, I use the network tracking feature under Inspect source code and this is the url it fires off when it runs my spoof image.
test.com/voteUp.php?time=1327644851907&postId=35
**I editted some of the information out like my database name and username/password and website url.
Those parameters are known as GET params, not POST.
Use the $_GET super global (use it in the same way as $_POST) to access them.
If you want post, do some jquery ajax post, like this:
Instead of:
var i = new Image();
var d = new Date();
i.src = "voteUp.php?time=" + d.getTime() + "&postId=" + postId;
change it with this:
$.ajax({
url: "voteUp.php",
cache: false,
type: 'POST',
data: {time: d.getTime(), postId: postId},
success: function(data){}
});
Note: you need jquery on that webpage!
Variables that appear in the query string of the URL (i.e. after the ? character) are accessed using the $_GET array rather than $_POST.

AJAX POST handler causing "uncaught exception"

So I've been banging my head against my desk for a few hours on this one and i'm not getting anywhere so help would really be appreciated.
The code below has two jquery event handlers which fire off an ajax request. The first one uses GET and the data it gets back from the server is JSON encoded - it works fine. The second one ( "button#addTx" ) returns causes Firebug to produce this error:
uncaught exception: [Exception...
"prompt aborted by user" nsresult:
"0x80040111 (NS_ERROR_NOT_AVAILABLE)"
location: "JS frame ::
resource://gre/components/nsPrompter.js
:: openTabPrompt :: line 468" data:
no]
Line 0
which is no help to at all. The server side script is printing raw html to the screen and the aim is that a jquery html replace will be used to update to the page which initiates the request. The data is POSTed correctly as the database updates but beyond that I have no clue. I have rewritten it to try a GET and still produce the same error :-(
Help would be amazing - thank you, Simon
$(document).ready(function(){
$("button.delete").click(function(){
var txid = this.id;
var amountID = "#amount" + txid;
var amount = $(amountID).html();
// <![CDATA[
var url = "delete.php?txid=" + txid + "&am=" + amount;
$.ajax({
type: "GET",
url: url,
success: function(msg){
txid = "ul#" + txid;
$(txid).hide();
var values = msg;
var e = "#" + values.category + "AmountLeft";
var a = values.amount;
$(e).html(a);
}
});
});
$("button#addTx").click(function(){
// <![CDATA[
var url = "addTran.php";
//var dataV = var data = "category=" + document.getElementById("category").value + "&what=" + document.getElementById("what").value + "&amount=" + document.getElementById("amount").value + "&date=" + document.getElementById("date").value;
$.ajax({
type: "POST",
url: "addTran.php",
//async: false,
data: "category=Groceries&what=Food&amount=2.33&date=2/3/2011",
success: function(msg){
$("transList").replaceWith(msg);
}
});
});
});
and here is the server side script
<?php
session_start();
include('functions.php');
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
$category = $_POST['category'];
$what = $_POST['what'];
$amount = $_POST['amount'];
$date = $_POST['date'];
$category = mysql_real_escape_string($category);
$what = mysql_real_escape_string($what);
$amount = mysql_real_escape_string($amount);
$date = mysql_real_escape_string($date);
$date = convertDate($date);
//add trans to db
include('dbcon.php');
$query = "INSERT INTO transactions ( category, what, amount, date) VALUES ( '$category','$what','$amount','$date');";
mysql_query($query);
//grab the remaining amount from that budget
$query = "SELECT amount_left FROM cards WHERE category = '$category';";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$oldAmountLeft = $row["amount_left"];
//update the amount left
$amountLeft = $oldAmountLeft - $amount;
mysql_free_result($result);
//add new value to db
$query = "UPDATE cards SET amount_left = '$amountLeft' WHERE category = '$category';";
mysql_query($query);
//generate the list of remaining transactions, print to screen to send back to main page
$query = "SELECT txid, what, amount, date FROM transactions WHERE category = ('$category');";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$d = convertDateReverse($row["date"]);
$what = $row["what"];
$amount = $row["amount"];
$txid = $row["txid"];
?>
<li><ul class="trans" id="<? echo $txid; ?>"><li class="date"><? echo $d; ?></li><li class="what"><? echo $what; ?></li><li class="amount" id="amount<? echo $txid; ?>"><? echo $amount; ?></li><button class="delete" id="<? echo $txid; ?>">Delete</button><li></li></ul></li>
<?
}
mysql_free_result($result);
mysql_close();
header("Content-type: application/x-www-form-urlencoded"); //do I need this? I have a " header("Content-type: application/json"); " in the working one
?>
PROBLEM SOLVED: so in the html markup the form that holds the fields of data should have an
onsubmit="return false;"
in it!
Thanks for all the help guys, I have implemented all your suggestions and my code is now soooo much smaller and easier to manage!
Cheers
Simon
Thx for posting the solution. Similarly banged my head for a while trying to solve a similar problem with NS_ERROR_NOT_AVAILABLE without luck. Useful for for people using Django <--> Javascript to do XMLHttpRequests as well. On the Django side, there is an
error: [Errno 32] Broken pipe
...that corresponds with the NS_ERROR that appears in the firebug console for the JS failure.(googleBait) It's hard to know where to start tracing the problem - server side or client side.
Thx again.

prototype ajax not properly executing query

So I decided to start using prototype and here's my first question. I'm trying to send out an ajax request to a php page which updates s single record. When I do this by hand (ie: typing the address + parameters it works fine but when I use this code from javascript:
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
The onSuccess fires and displays the correct information from php, but the update is not made. What the php returns is the UPDATE string, so I'm checking the parameters and they look fine. Does anyone see a problem? Thanks...
Total javascript:
/*This file handles all the user-based computations*/
//variable declarations to be used throughout the session
var untimedSongArray = [];
function beginProcess(){
new Ajax.Request('php/getUntimed.php', {
method: 'get',
onSuccess: function(transport){
var response = transport.responseText || "no response text";
untimedSongArray = response.split("+");
alert(response);
getFlashMovie("trackTimer").timeThisTrack(untimedSongArray[0]);
//alert("Success! \n\n" + response);
//var html = response;
},
onFailure: function(){ alert('Something went wrong...') }
});
}
function getFlashMovie(movieName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName]; }
function setSongTime(track, time){
alert("track " + track + " has a time of " + time);
//$.get("php/setSongTime.php", { trackname: track, tracktime: time } );
var pars = 'trackname=' + track + '&tracktime=' + time;
new Ajax.Request('php/setSongTime.php', {
method: 'get',
parameters: pars,
onSuccess: function(transport){
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
},
onFailure: function(){ alert('Something went wrong...') }
});
}
Total php code:
<?php
//turn on error reporting
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
//header('Content-Type: text/xml');
/////////////Main script
//pull variables
//need to do some error checking here
$trackname = ($_GET['trackname']);
$tracktime = ($_GET['tracktime']);
//remove leading track information
$trackname = str_replace('../music_directory/moe/moe2009-07-18/', '', $trackname);
$trackname = str_replace('.mp3', '', $trackname);
//echo $trackname;
//connect with database
$con = mysql_connect("localhost","root","");
if(!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("musicneverstopped", $con);
//end connecting to database
//////////////////////////////////////////
//update given song time
$sql = "UPDATE songs SET length = ".$tracktime." WHERE unique_song_id = ".$trackname;
echo $sql;
mysql_query("UPDATE songs SET length = '$tracktime' WHERE unique_song_id = '$trackname'");
//error check
//if(!$attempt){
//die(mysql_error());
//}
//////////////////////////////////////////
//close database connection
mysql_close($con);//close mysql connection
?>
Anyone see any failing errors?
Try echoing the exact same SQL you actually run in mysql_query (store it in $sql then pass that into the query, instead of writing out the query twice).
Then try running the query that gets echoed out in the response directly in the mysql command line on your server and see what happens.
Also, just to echo Max on the importance of escaping your SQL queries, I would add to the input sanitisation that you should use bind variables in your query, rather than just concatenating your user input with the rest of the SQL.
Something like this would ensure your variables are suitably escaped to avoid an SQL injection attack.
$sql = "UPDATE songs SET length = '%s' WHERE unique_song_id = '%s'";
$query = sprintf(
$sql,
mysql_real_escape_string($tracktime),
mysql_real_escape_string($trackname)
);
mysql_query($query);
Found it! Somehow I was getting an extra space before the finalized $trackname. ltrim fixed it right up. Thanks to everyone and thanks to those that mentioned security features. I'll definitely implement those. Dan

Categories