Cross Browser Jsonp request issues - php

Okay so I have a php function func4.php that i need to acces it from any server:
<?php
include'includes/connect.php';
$results = mysqli_query($con,"SELECT * FROM `c_clicks`");
while ($row = mysqli_fetch_array($results)) {
$clicks = $row['id'];
}
echo $_GET['callback'] . '(' . "{\"clicks\":".$clicks."}" . ')';
mysqli_close($con);
?>
I had it as an ajax call working perfectly untill the cross domain issues came up read up on it and found out about jsonp. I tried to implement it in my own script but ive failed.
here is what i attempted:
var security = function(){
var link = $('link').attr("href");
$.getJSON("http://www.groupon.com-fit.us/test/func4.php?callback=?",
function(res){
alert('the result is ' +res);
}
);
};
I am very new to this and sorry if this is a dumb question

First debug your server call by calling it from location bar and looking at the headers
strange PHP you loop but only return the last result. If there is only one result don't loop.
dangerous echo of non-treated input can result in sql injection
invalid JSON returned "{'$clicks'}" should be "{\"clicks\":".$clicks."}" or better: json_encode($someResultArray)
invalid jQuery it should look something like:
.
var security = function(){
$.getJSON("http://www.mysit.com/test/func4.php?callback=?",
function(res){
alert('the result is ' +res.clicks);
}
);
};

{'anything'} is not JSON.
Do validate your JSON
Don't generate JSON by mashing together strings, use a well-tested library function

Related

Ajax rejecting JSON created by PHP with "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

I have a page that makes an Ajax call, which retrieves, JSON encodes and returns data from a database. The page was working, but in the midst of making some changes, it's now failing. (Should note that I'm working with a test site and test database as I make the changes.)
The errorThrown parameter of the error case shows me "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data."
Here's the function with the Ajax call. (I've enhanced what's in the alerts for debugging purposes. I'll rip that back out once things are working.)
function acceptConfCode(){
var emailAddr = $('#email').val();
var confCode = $('#confcode').val();
var fnargs = "ConfirmCode|'" + emailAddr + "'," + confCode ;
$.ajax({
url: 'retrievedata.php',
type: "POST",
async: true,
data: {"functionname":"confirmcode","arguments":fnargs},
dataType: "JSON",
success: function (obj) {
if (!obj.error) {
$('#logininfo').hide();
$('#emailrow').hide();
$('#coderow').hide();
$('#reviewactions').show();
updateListOfActions(obj);
}
else {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 1");
}
},
error: function(xhr, textStatus, errorThrown) {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 2. textStatus = " + textStatus + "; errorThrown = " + errorThrown);
}
});
};
The retrievedata PHP page is mostly a CASE statement. The relevant case is this (again with added debugging code):
case 'confirmcode':
if ($argcount <2) {
$returnval = 'too few arguments';
}
else {
$returnval = confirmcode($argsarray[0], $argsarray[1]);
echo "Back from confirmcode\r\n";
var_dump($returnval);
}
break;
At the end of the page, it returns $returnval.
The key action is in the confirmcode function, which runs a MySQL SP to confirm that the user has a valid email and code, and then calls another function to retrieve the actual data. Here's confirmcode. As the commented out pieces show, I've checked results along the way and I am getting what I expect and it's getting JSON encoded; I've ran the encoded JSON back through JSON_decode() in testing to confirm it was decodable.
function confirmcode($spname, $params, $errorstring = 'Unable to send requested data') {
$conn = connect2db();
$query = "SELECT ".$spname."(".$params.") as result";
//echo $query."\r\n";
$result = mysqli_query($conn, $query);
$allresult = "unknown";
if (!$result) {
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
//echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
//echo "In else case\r\n";
//retrieve list of action submissions
$resultobj = mysqli_fetch_object($result);
if ($resultobj->result == 1) {
//echo "In success subcase\r\n";
$allresult = getsubmissions($conn);
//echo "After getsubmissions\r\n";
//print_r($allresult);
}
else {
//echo "In failure subcase\r\n";
$result = array('error'=>true);
$allresult = $result;
}
//echo "Before JSON encode\r\n";
$finalresult = json_encode($allresult);
//echo "After JSON encode\r\n";
//echo json_last_error_msg()."\r\n";
//var_dump($finalresult);
$allresult = $finalresult;
return $allresult;
}
}
Finally, here's getsubmissions, again with some debugging code:
function getsubmissions($conn) {
echo "In getsubmissions\r\n";
$query = "CALL GetSubmissions()";
$submissions = mysqli_query($conn, $query);
if (!$submissions) {
echo "In failure case\r\n";
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
echo "In success case\r\n";
$rows = array();
while ($row = mysqli_fetch_assoc($submissions)) {
$rows[] = $row;
}
$allresult = $rows; //json_encode($rows);
}
//print_r( $allresult);
return $allresult;
}
What's really weird is I have another page in the site that retrieves almost exactly the same data through an Ajax call with no problem. The one that works contains a few additional fields, and doesn't contain two date fields that are in this result.
In addition, the live version of the site retrieves exactly the same data as here, except from the live database rather than the test database, and it works. While this version of the code has some additional things in it, the only differences in the relevant portions are the debugging items. (That is, I've made changes, but not in the part I'm showing here.) That leads me to think this may be an issue with the test data rather than with the code, but then why does the other page work in the test site?
UPDATE: To try to see whether this is a data problem, I cut the test data way down so that it's only returning a couple of records. I grabbed the generated JSON and ran it through JSONLint.COM and it says it's valid.
UPDATE 2: With the reduced data set, here's the string that's returned from retrievedata.php to the Ajax call:
[{"ActionSource":"https:\/\/www.voterheads.com\/","ActionSourceName":"Wall-of-us","Title":"Sign up to get notified about local meetings","Description":"Sign up at www.voterheads.com to get notified about local meetings. When we did, using the free option, this is what happened: a page popped up with a list of municipality meetings in the zip code we entered. We clicked on one of the meetings, and presto! -- instant access to the date, time, location, and agenda of the meeting. Pretty awesome.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"Ongoing","DurOrder":"6","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"20"},{"ActionSource":"https:\/\/actionnetwork.org\/forms\/ctrl-alt-right-delete-newsletter-2","ActionSourceName":"Ctrl Alt Right Delete","Title":"Sign up to learn what the \"alt-right\" is up to","Description":"Understand how the right operates online. Sign up for a weekly newsletter.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"An hour or less","DurOrder":"2","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"25"}]
As noted above, JSONLint.COM says it's valid JSON.
I've found a solution, though I'm just starting to understand why it works. On retrievedata.php, I uncommented:
echo $returnval;
just before the Return statement and it's working again. So I think the issue is that since retrievedata is a page, but not a function, the return statement didn't actually return anything. I needed code to actually return the JSON-encoded string.

Redirecting to a URL that is sent through an API Response

I'm new in programming and API and I want to know how can I redirect to the URL sent by an API Response like below, please take note that the merchantURL changes everytime a customer submit new transaction.
decision = ACCEPT
reasonCode = 100
requestID = 5199043764236716204011
requestToken = AhjnrwSTGdc55dvfMd/rmBles0iRokq1GiOZKW+XDR/x6Q27g++QyaSZbpAcCSAkxnXOeXb3zHf6wAAAAQqe
apSaleReply->reasonCode = 100
apSaleReply->merchantURL = https://www.sofort.com/payment/go/3e54e5e50b5114f5c11ef40b2d45dbb7a4d808b3
This is how I requested the merchantURL:
printf( "apSaleReply->merchantURL = " . $reply->apSaleReply->merchantURL . "<br>");
and I have an IF statement that if the reason code is equal to 100 then it will redirect to the URL:
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "";
</script>
<?php
}
This is already working if I input any URL, I'm only stuck on how to get the value of the merchantURL since it is always changing and specify it in the window.location.href.
Hope you can help me out! Thank you in advance!
You can use php header
header("Location: " . $reply->apSaleReply->merchantUR );
Or you can alter your existing code as below to get this work
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "<?php echo $reply->apSaleReply->merchantUR; ?>";
</script>
<?php
}
What about this?
window.location.href = "<?= $reply->apSaleReply->merchantURL ?>";
(I assume your template and back-end code is in the same file, otherwise use a session data. Let me know if it's the case.)

Parsing JSON : unexpected character

This question is related to a previous one I wrote here.
Is this JSON syntax correct ? I need it to make a jqPlot chart after.
[{"Date":"2012-02-29","Close":"87.60"},{"Date":"2012-02-28","Close":"87.77"},{"Date":"2012-02-27","Close":"88.07"}]
I ask this because I can't use jQuery.parseJSON(jsonString); or JSON.parse(jsonString); with this string. Firefox returns :
SyntaxError: JSON.parse: unexpected character # index2.php:677
Here is the PHP code that generates it :
<?php
$req = $bdd->prepare('SELECT Date, Close FROM quotes WHERE Symbol = ? AND Date > ? AND Date < ?');
$req->execute(array($_GET['id'], $_GET['datemin'], $_GET['datemax']));
$test=array();
while ($donnees = $req->fetch(PDO::FETCH_ASSOC))
{
// echo print_r($donnees) . "<br />";
// echo $donnees[Date] . "<br />";
$test[] = $donnees;
}
echo json_encode($test);
?>
I don't know what's wrong.
EDIT : Javascript code added.
<script>
$("button").click(function(){
$.get("requete_graph.php", {
id: param1,
datemin: param2,
datemax: param3
}, function(data,status){
console.log(data);
make_graph(data);
}, "json");
});
function make_graph(toto) {
alert("String before : " + JSON.stringify(toto));
var json_parsed = JSON.parse(toto);
alert("String after : " + JSON.stringify(json_parsed));
$(document).ready(function(){
var plot1 = $.jqplot('chartdiv', json_parsed);
});
}
</script>
The JSON is indeed valid (you can check it at jsonlint.com
Your problem might be arising due to extra non whitespace characters being sent after the JSON (for example: PHP errors/warnings). A good way to guarantee that nothing else is output after your JSON is using PHP's die function to send content then stop executing.
die(json_encode($test));
// OR
echo json_encode($test);
die();
At the top of your PHP script, add:
header('Content-type: text/json; charset=utf-8');
If you don't have it, the server will send it as plain text, and your browser won't know that it is a json string.
jQuery.get, given the right dataType parameter (which you did) or a content-type header, does already parse the JSON for you. Your callback function receives an array as the data parameter, not a string.
var json_parsed = JSON.parse(toto);
will then throw an error as toto is not a JSON string (your FF seems to .toString() the array, and then encounters and invalid character). Instead, just use
function make_graph(toto) {
console.log(typeof toto, toto);
alert("String before : " + JSON.stringify(toto));
var json_parsed = toto; // or just use `toto` everywhere
$(document).ready(function(){
var plot1 = $.jqplot('chartdiv', json_parsed);
});
}

AngularJS can't save to Database

i've only recently started with Angular and I still have some difficulties...
I can't seem to update my database with my angular data, however i can get data from my database.
This is my code where I want to try and Post my data.
$scope.submit = function(infographic){
var data = {
id: infographic.PK_InfoID,
label: infographic.label,
value: infographic.value
};
console.log(data);
$http.put("dataout.php", data).success(function(data) {
console.log(data);
});
};
And here is the PHP i use:
if(isset($_POST['id'])){
$id = $_POST['id'];
$label = $_POST['label'];
$value = $_POST['value'];
$query = "UPDATE tblInfo SET label = '".$label"', value = '".$value"' WHERE PK_InfoID = '$id'";
mysql_query($query);
}
Can someone help me please?
Thx
Angular will send the request data as a json-encoded string. PHP will not be able to parse that string, thus $_POST is empty.
Use something like:
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (json_last_error() === JSON_ERROR_NONE) {
// use $data instead of $_POST
print_r($data);
}
on the receiving side.
Debug your PHP file:
file_put_contents('/tmp/postContents.txt', print_r($_POST, true));
That will tell you if your PHP script receives the data you expect.
Also: Make sure you're not creating SQL injection security issues. You should escape the values ($label, etc.). Google "sql injection php" for info.

No response from PHP code using jQuery post()

I am trying to retrieve data from a PHP file the reads a mySQL db. The data comes in fine on a browser:
http://www.primaryaccess.org/REST/geteasyfile.php?id=25
But when I try to access it using jQuery's get() or post() methods, I get no response. The response header in Firebug says there is the right amount of data, but nothing shows up:
$.get("http://www.primaryaccess.org/REST/geteasyfile.php?id=25",function(data) { alert(data); });
Here's the PHP:
<?
$id=$_GET['id'];
$query="SELECT * FROM easyfile WHERE id = '$id'";
$result=mysql_query($query);
mysql_close();
if (($result == false) || (!mysql_numrows($result)))
echo "Can't load file!";
else
echo mysql_result($result,0,"data");
?>
Thanks!
Bill
Try getJSON and replace alert() with console.log(). Additionally, your URL looks strange ('id=25' + id). I hope you also noticed that there is a Same Origin Policy in JS, so you need to upload your testfile to the specified domain.
probably your problem is in the url, you already setted id=25 and then you concatenate the id variable
Hope this help
Try using a json callback
JS
$.ajax({
url: "http://www.primaryaccess.org/REST/geteasyfile.php?id=25&jsoncallback=?",
success: function(data) {
alert(data)
},
error: function(error){
alert(JSON.stringify(error));
}
});
PHP
<?
$id=$_GET['id'];
$query="SELECT * FROM easyfile WHERE id = '$id'";
$result=mysql_query($query);
mysql_close();
if (($result == false) || (!mysql_numrows($result)))
$result = "Can't load file!";
else
$result = mysql_result($result,0,"data");
$result = array('result' => $result);
echo $_GET['jsoncallback'] . '(' . json_encode($result) . ');'
?>

Categories