Please can anyone assist I'm trying to get my JSON data displayed on my html5 localhost page,
I'm still new to JSON
I get the following returned but no data is loading on the page.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
Please if anyone can assist.
Below is my php script
`mysql_select_db($database_xxx, $xxx);
$rsfet = "SELECT * FROM cs_tracking ";
$fet = mysql_query($rsfet, $xxx) or die(mysql_error());
$json = array();
while($r=mysql_fetch_array($fet)){
$json[] = $r;
}
header('Access-Control-Allow-Origin: *');
echo $callback ='('.json_encode($json).')';`
and my javascript to display the table data
`
$(document).ready(function(){
$.ajax({
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: true,
success: function(data){
$.each(data,function(i,photo){
var tblRow =""
+""+data.CS_Track_Child+""
+""+data.CS_Track_Date+""
+""+data.Tracking_Status+""
+""+data.CS_Tracking_ID+""
+"" ;
$(tblRow).appendTo("#userdata tbody");
});
},
});
});`
The $callback variable is not magically declared in your script (at least, it shouldn't be); you can access the value via $_GET['callback'] but make sure to sanitize its value:
if (isset($_GET['callback']) && preg_match('/[A-Z]\w*/i', $_GET['callback']) {
header('Content-Type: application/javascript');
header('Access-Control-Allow-Origin: *');
printf('%s(%s);', $_GET['callback'], json_encode($json));
}
You have two GET parameter of callback one is valid but empty and second is invalid.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
So remove your parameter and try with this:
url: 'http://xxxxxxxxxxx.com/getCheck.php',
Related
SOLVED - EDIT: I ended up not having to do json parse nor stringify with return from php because I can already do data[i]["filesize"]
code below is only showing me http://pastebin.com/DZ4UyHjC
if I change code to dataType:text then it outputs http://pastebin.com/pZg2W2aL which validates on site jsonformatter.curiousconcept.com . So with datatype:text, i would try to manually parse it with JSON.parse(result), this brings me back to original issue/output in first paste.
I've tried the suggestion of setting utf8 encoding, setting header in php before echo but still the same issue. Any help?
if(mysqli_num_rows($fres)){
$row = array();
while ($frow = mysqli_fetch_assoc($fres)) {
$row[] = array("path"=>myhtmlspecialchars($frow['path']),"filesize"=>mksize($frow['filesize'])); }
echo json_encode($row);
///end of php
$.ajax({
type: 'POST',
url: './getFilesList.php',
data: {id : varId},
dataType: 'JSON',
cache: false,
success: function(data){
alert(data);
}
});
I need to call php and get data from another server and I am using proxy.php to call from ajax.
proxy.php
<?
header('Content-type: application/json');
$url=$_GET['url'];
$json=file_get_contents($url);
echo $json;
?>
And my code looks
function scanFunction(){
var url="http://address/scan.php?user=user1&video=video1";
console.log(url);
url = 'proxy.php?url='+url;
$.ajax({
url: url,
type: "POST",
data: {
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
}
else{
console.log(" error...");
}
}
});
}
And this code works fine when I use one parameter to the url passing to proxy.php where as second argument missing
That is
echo $url; inside proxy.php print
http://address/scan.php?user=user1
event I pass two argument like,
proxy.php?url="http://address/scan.php?user=user1&video=video1"
That is second argument video missing inside proxy.php and so I am not getting expected result.
You may be having issues with your GET variables in the GET['url'] variable.
Try encoding your url when you send it to proxy.php to avoid such issues.
var url = encodeURIComponent("http://address/scan.php?user=user1&video=video1");
url = 'proxy.php?url='+url;
Then on the PHP side you need to decode it.
$url=$_GET['url'];
if (is_string($url)) {
$url = urldecode($url);
}
proxy.php cannot know which arguments are meant for it, and which are meant for scan.php. Eg, When you call url:
proxy.php?url=http://address/scan.php?user=user1&video=video1
Your proxy scripts thinks that the query parameters are:
url:"http://address/scan.php?user=user1"
video:"video1"
But your intent was for everything after url to be one parameter. A better approach is to use POST parameters instead of URL query parameters.
$.ajax({
url: url,
type: "POST",
data: {
resource_url: "http://address/scan.php?user=user1&video=video1"
},
....
});
Now, in proxy.php:
<?php
header('Content-type: application/json');
$url=$_POST['resource_url'];
$json=file_get_contents($url);
echo $json;
?>
Use the data: property of the ajax call to pass as much or as many parameters as you like
function scanFunction(){
$.ajax({
url: 'proxy.php',
type: 'POST',
data: {
url: 'http://address/scan.php',
user: 'user1',
video: 'video1'
},
dataType: "JSON",
success: function (jsonStr) {
if(jsonStr.length>0){
var obj = jsonStr;
console.log(obj);
} else {
console.log(" error...");
}
}
});
}
Then build whatever you want from those parameters in the php script
Oh and you used type: 'POST' in your javascript, so you should be using the $_POST array in your PHP script.
proxy.php
<?php
$url = $_POST['url'] . '?user=' . $_POST['user'] . '&video=' . $_POST['video'];
$json=file_get_contents($url);
header('Content-type: application/json');
echo $json;
?>
Right now I need to use phonegap to call on a php script on another webserver to retrieve data from a database i have. Running the script with hard codes retrieves the data correctly but it appears as tho either the ajax call is not returning anything or not even getting the data as post. Currently in the console I am getting "Origin null is not allowed by Access-Control-Allow-Origin. "
$(document).ready(function() {
$('.check').click(function(){
alert("Step1");
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "POST",
url: "http://csmaster.sxu.edu/group2/group2/CougarLunch/retrieveColumn.php",
data: { ID: thisID},
cache: false,
async:true,
datatype: "json",
success: function(data)
{
console.log(data);
alert(data.ItemID);
}
});
});
});
PHP if it is relevent I doubt it tho
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
function retrieve($ID)
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
Add this line to the top of php file to allow access:
header("Access-Control-Allow-Origin: "*");
you need to pass in AndroidManifest.xml
<access origin="*" />
phonegap doc
My php has header('Content-type: application/json') and a json_encode.
The ajax code I use to send the data to the php file has dataType: 'json' and I am sending the data as a string (json.stringify).
The problem is, I can't make $_POST['data'] work on a string.
Any way to convert it to an object?
edit: What I am trying to achieve is, sending data from ajax to php where a query looks up the information from the database and the php file sends an array using JSON to the ajax and the ajax displays it.
Ajax:
function op_prof(obj) {
var xval = obj.id;
$.ajax({
type: "POST",
url: '../script/profile.php',
dataType: 'json',
data: JSON.stringify({'u_search':'xval'}),
cache: false,
success: function(data) {
console.log(data);
alert(data);
alert({u_search:xval}['u_search']);
$("#co_profile").html(data).show();
}
});
};
PHP:
<?php include(dirname(__FILE__). '/../script/config.php');
session_start();
$id = $_POST['u_search'];
foreach($pdo->query("SELECT * FROM Users WHERE ID='$id'") as $row) {
$fullname = $row['FullName'];
$data = array("u_data"=> true,"inpt"=>"<p>My name is " . $fullname . "</p>");
header('Content-type: application/json');
echo json_encode($data);
?>
<?php $pdo = null; ?>
I'd also like to know any other way of achieving this (even without using JSON)
Try json_decode("php://input");
I have an AJAX Request, that essentially queries a database then posts the data back to the JS, however I can't print individual bits of data.
My code is as follows:
$.ajax({
type: 'POST',
url: '_process/offerrespres.php',
dataType: 'json',
data: {
msgid: msgid,
usrid: usrid
},
success: function(){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}
});
The PHP:
<?php
include_once 'connect.php';
if ($_POST) {
$msgid = mysql_escape_string($_POST['msgid']);
$usrid = mysql_escape_string($_POST['usrid']);
$getmsgq = mysql_query("SELECT * FROM booking_requests WHERE receiver_id = '$usrid' AND msg_id = '$msgid'");
$getmsg_info = mysql_fetch_array($getmsgq);
$data['success'] = true;
$data['date_sent'] = $getmsg_info['date_sent'];
$data['pro_name'] = $getmsg_info['pro_name'];
$data['accept_decline'] = $getmsg_info['accept_decline'];
}
header("Content-Type: application/json", true);
echo json_encode($data);
mysql_close();
?>
As you can see I've tried this:
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
the error in the console says "data not defined". The output from the PHP file is correct and how it should be, I just can't print one single piece of data.
Your callback function isn't accepting the return data as an argument
The line that reads success: function(){ should be success: function(data){
Also, the true isn't needed in your call to header("Content-Type: application/json", true);. The default action of this function is to replace headers, so true is already implied. That argument is only necessary if you don't want to replace the previous Content-Type. Makes no difference to your code, just a tip.
You didn't specify the data variable in the success function.
It should be:
success: function(data){
console.log(JSON.parse(data.pro_name));
console.log(data.accept_decline);
}