getJSON - why it didnt work? - php

Why getJSON method works only with local files? If I want to take json from local it works, but if I set url with http it doesnt work. why?
<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$.getJSON("http://www.address.com/getTables.php", function (data) {
$.each(data, function (i, table) {
$("#tables").append("<p>" + table.id + " " + table.tabname + "</p>");
});
});
</script>
<body>
<div id="tables"></div>
</body>
</html>
Returned JSON:
[{ "id":"12", "tabname":"cukry" }, { "id":"11", "tabname":"table" }]

It sounds like you're probably running into the same-origin policy.

Like Matt said it`s because of the same origin policy. Try using JSONP. You just need to add callback to your request URL like this:
$.getJSON("http://www.address.com/getTables.php?jsoncallback=?", function (data) {
$.each(data, function (i, table) {
$("#tables").append("<p>" + table.id + " " + table.tabname + "</p>");
});
});
See more about JSONP here

Related

Json reading data from json call in to a table

I have a script that reads the content of a Json string and creates a table to display the data. This works fine as long as I include the Json string in the JQuery function. What I need to do is call another php file which returns the Json string.
I have written the script that returns the Json string:
[{"ClientName":"Name","RoomName":"Room 2","RoomFromTime":"06:00:00","RoomToTime":"17:00:00"},{"ClientName":"Name","RoomName":"Room 6","RoomFromTime":"06:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 1","RoomFromTime":"07:00:00","RoomToTime":"17:00:00"},{"ClientName":"Name","RoomName":"Room 14","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 12","RoomFromTime":"07:00:00","RoomToTime":"19:00:00"},{"ClientName":"Name","RoomName":"Room 10","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 9","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 8","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 7","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 5","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 3","RoomFromTime":"07:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 4","RoomFromTime":"08:00:00","RoomToTime":"23:00:00"},{"ClientName":"Name","RoomName":"Room 15","RoomFromTime":"08:00:00","RoomToTime":"19:00:00"}]
My JQuery function has the following:
$(document).ready(function () {
var json = $.getJSON("get_data.php", function(data){
var tr ;
for (var i = 0; i < json.length; i++) {
tr = $('<tr/>');
tr.append("<td><div class='clientname-text'>" + json[i].ClientName + "</div></td>");
tr.append("<td><div class='roomname-text'>" + json[i].RoomName + "</div></td>");
tr.append("<td><div class='time-text'>" + json[i].RoomFromTime + " - " + json[i].RoomToTime + "</div></td>");
$('table').append(tr);
}
});
});
Using the call to the other php script does not display the returned data in the table. Now I know I have gone wrong somewhere, but can anyoe see what I am doing incorrectly.
Many thanks in advance for your time.
UPDATE:
Because getJSON by default works asynchronously, the json variable is not filled at the time the callback is run. Change the callback to:
$.getJSON("get_data.php", function(json){
...
It appears there is a wrapper around your actual jason.
Either fix it like this:
$.getJSON("get_data.php", function(json){
json = json[0].data;
...
or fix it in get_data.php.
You can use this 100% working code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("get_data.php", function(data){
$.each(data, function(i, field){
var tr ;
tr = $('<tr/>');
tr.append("<td><div class='clientname-text'>" + field.ClientName + "</div></td>");
tr.append("<td><div class='roomname-text'>" + field.RoomName + "</div></td>");
tr.append("<td><div class='time-text'>" + field.RoomFromTime + " - " + field.RoomToTime + "</div></td>");
$('table').append(tr);
});
});
});
</script>
</head>
<body>
<table></table>
</body>
</html>

Comunication between Express.js and PHP through jQuery Ajax

I'm developing a small project where I have a web page (index.html) loading in Express.js and it sends some data to a PHP script running on a MAMP server. The PHP script processes the data and returns a JSON encoded array back to the web page and finally the Node.js server sends data to connected clients using socket.io.
I have problems with the communication with PHP using jQuery Ajax. I send the data to PHP using POST and I know PHP receives that data but I don't know how to catch the response from PHP to know how the processing went.
I have no experience with Node.js. What can I do to make this thing work?
So far this is the code I have
Node.js - Express.js
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, db = require('./routes/db')
, http = require('http')
, socketio = require('socket.io')
, path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser()); //Middleware
app.use('/', express.static(__dirname + '/public'));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
HTML Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Site</title>
<script src="js/jquery-2.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<div id="formContainer">
<form enctype="multipart/form-data">
<input type="text" name="texto">
<button type="button" id="buttonSend">Enviar</button>
</form><br/><br/>
</div>
<script type="text/javascript">
$('#buttonSend').click(function(e){
e.preventDefault();
$.ajax({
url: 'http://localhost:8080/NodePHP/test.php',
type: 'POST',
dataType: "json",
data: {value: 1},
success: function(data){
if(data.success == true){
alert("Perfect!");
}
else{
alert("Error!");
}
},
error: function(xhr,status,error){
//alert("Error de llamada al servidor");
alert(xhr.responseText);
//$('#botonUsarFoto').css('display','block');
}
});
});
</script>
</body>
</html>
PHP Script
<?php
$number = $_POST['value'];
echo $number;
// move the image into the specified directory //
if ($number == 1) {
$data = array("success"=>"true");
echo json_encode($data);
} else {
$data = array("success"=>"false");
echo json_encode($data);
}
?>
Thanks in advance for any help
In order to make a request with Node, we'll use the http and querystring modules. Here's an example lovingly adopted from the Nodejitsu folks:
var http = require('http');
var querystring = require('querystring');
var data = querystring.stringify({
value: 1
});
var options = {
host: 'localhost',
path: '/myPHPScript',
method: 'POST'
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = http.request(options, callback);
req.write(data);
req.end();
Alternatively, you could use the request module, but first things first.

Passing JSON from PHP to a JavaScript variable

I'm making an aplication with phonegap and I'm stuck trying to send JSON data from the PHP on the server to JavaScript on the device. I want to do something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
the php works fine and returns somethig like:
"[{"id":"1","name":"Art for everyone","image":null,"name2":"June 29, 2013: 11:00am.","description":"With reservation\r\nFree entrance","description2":null}]"
I want that result in a javascript variable to work later with:
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
What I want to do is something like:
var JSON = '{ "Table" : ' + "http://www.hel.net/LoadDB.php=?table=exhibitions" + '}';
var obj = eval ("(" + JSON + ")");
document.getElementById("rName").innerHTML=obj.Table[1].name;
document.getElementById("lname").innerHTML=obj.Table[1].name2;
How can I make the first line work? is it possible to make the first line work?
PS. I do not have much experience with JSON arrays.
Ok I tried ajax and works, I used:
console.log("before");
var jqxhr = $.ajax( "http://www.hel.com/LoadDB.php?table=exhibitions" )
.done(function(data) { console.log(data); })
.fail(function() { console.log("error"); })
.always(function() { console.log("complete"); });
console.log("after");
more info in:
api.jquery.com
I think all you need is var obj = <?php echo $myjsonencodedvar; ?>
or
var obj = <?php echo json_encode($myarray_or_object); ?>
Since I said "I think..." I decided to test it out. I found the following dump() function here on SO.
$arr=array(1,'biscuit'=>'gravy',3,4,5);
$json=json_encode($arr);
?>
<script>
j=<?php echo $json; ?>;
document.write(dump(j));
function dump(obj) {
var out = '';
for (var i in obj) {
out += i + ": " + obj[i] + "\n";
}
return out;
}
</script>
output:
0: 1 biscuit: gravy 1: 3 2: 4 3: 5
Try this:
PHP: (json.php)
<?php
header("Content-Type: text/json");
//the data format your question mentioned
$data = array("Table"=>array(array("id"=>"1","name"=>"Art for everyone","image"=>null,"name2"=>"June 29, 2013","description"=>"With reservation\r\nFree entrance","description2"=>null)));
echo json_encode($data);
?>
Front-end:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$.get("json.php",function(json){
alert(json.Table[0].name);
});
</script>
</body>
</html>
Hope this is helpful for you.
using JSONP (no callbacks), and on the client side use $.getJSON() it will parse it from json string to js object.

Use $.post methods returned function(data) value to variable

Dear Coders!
The purpose of my code:
Get URL of files listed in specific folder, then assign them to an Array in javascript.
How I'm imagining it:
JavaScript function in test.php uses $.post() method to send a value to getURL.php file. After this, getURL.php uses this value to get specific file URLs in a specific folder. I'm getting the result(s) in the $.post() methods function(data) parameter. After this, the resulted value of the "data" is (/would be used) in JavaScript.
The problem:
Inside the $.post() methods function: function(data,status) I'm satisfied with the result of the returned value of the data parameter; the PROBLEM is that I can't assign it's value outside this function:function (data,status)`.
TEST.php
<script src="jquery-1.9.1.js">
</script>
<script type="text/javascript">
var imgPath; // <--He is who should get the value of "data"
function getTargetUrl(szolg){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
imgPath=data;
alert (imgPath);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a);
alert(imgPath);
});
</script>
getURL.php
<?php
if(isset($_POST["x"])){
$queryGlob='img/'.$_POST["x"].'/batch/*.jpg';
foreach (glob($queryGlob) as $filename) {
$imgFiles=json_encode($filename);
$imgFiles=str_replace('\/','/',$imgFiles);
echo $imgFiles;
}
//$data = str_replace('\\/', '/', json_encode(glob('img/'.$_POST["x"].'/batch/*.jpg')));
}
else{
$imgFiles="FAIL";
echo $imgFiles;
}
?>
Note: for testing I'm using Google Chrome.
So that's all I guess, hope someone can give me a solution and possible explanation.
The post call is asynchronous, so in your code here:
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a);
alert(imgPath);
});
...the alert occurs before the post call has completed, and so shows the old value of imgPath. What you want to do is pass a function into getTargetUrl that it will call when the post completes, and put the subsequent code in there.
Something like this:
var imgPath; // <--He is who should get the value of "data"
function getTargetUrl(szolg, callback){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
imgPath=data;
callback();
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a, function() {
alert(imgPath);
});
});
And you can do away with the global variable entirely by doing what post does and passing the data back as an argument:
function getTargetUrl(szolg, callback){
$.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
callback(data);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a, function(path) {
alert(path);
});
});
No, AJAX is asynchronous meaning that the $.post method will return immediately. If you want to use the results of an AJAX call, the only safe place to do so is inside the success callback. Do not attempt to assign the result to global variables.
So you should put the alert inside the success callback.
As explained by others the reason for this behavior is the asynchronous nature of ajax requests.
My solution will to return the ajax promise request from getTargetUrl and use it to register callback methods
function getTargetUrl(szolg){
return $.post(
"getURL.php",
{ x: szolg },
function(data,status){
alert("in function: " + data + " status: " + status);
alert (data);
}
);
}
$(document).ready(function() {
var a="szolg5"; //it will be "user defined", used in getURL.php
getTargetUrl(a).done(function(data){
alert('from callback' + data);
});
});

getting .get() in jquery to work

I have been trying to practice jquery using the .get() function but it's not working. Here is my code:
<html>
<head>
<title>Testing Site</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php", function(data){
$('body')
.append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('background-color', 'red');
}, "json");
});
});
</script>
</head>
<body>
<span id="hello">Hello World!</span>
<input type="button" id="id" value="Click Here"></input>
</body>
</html>
I basically modified the .get() example on the jquery api site. But when I click the button nothing happens! (There must be something wrong because the background color isn't changing either...) I have the correct path names and I copyed the correct php file:
<?php echo json_encode(array("name"=>"John","time"=>"2pm"));
?>
I also tried implementing an example on http://www.chazzuka.com/ajaxify-your-web-pages-using-jquery-88/ which used the .get() which didn't work. On firefox nothing happened and on Google Chrome it only worked part way...
I'm not sure if anyone cares to try to implement that code, but that code made me wonder about this .get() function: how does it work? In that example it is supposed to retrieve info from a plain html file. I assumed that it would only work for something like a php file which made the server send back info when you make the call "echo..."
Since your code is in the head of your page, it will execute prior to the DOM being created. You need to make your code wait until the DOM is ready. You can do this by wrapping your code in document.ready as so:
$(function(){
// code goes here
});
The problem is that the script is not even getting called because the binding happens before the page is fully loaded.
You'll need to wrap your code in a
$(document).ready(function() {
// your code
});
block.
Check out the jQuery website for more on .ready
You're not waiting for DOM ready. When your code runs, $("#id") does not return anything, since that div hasn't been loaded yet.
Wrap your code in $(document).ready(function(){}):
$(document).ready(function(){
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time )
.css('background-color', 'red');
}, "json");
});
});
You need to put the click event binding in the document ready event of jQuery.
With the current code, when you are trying to bind the click event to #id element, #id is not yet available in DOM hence jQuery cannot find the element.
Try this:
$(function(){
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('background-color', 'red');
}, "json");
});
});
Your script is executing before the element exists.
Move the <script> to the end of the <body>.
Wrap your code in $(function(){ }) because element should be available to jQuery for it to attach the event handler. This will execute the code when DOM is ready.
$(function(){
$("#id").click(function(){
$('#hello').css('background-color', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('background-color', 'red');
}, "json");
});
});
Javascript is executed as it is come to in the document. You want to use jQuery's ready function to have your script wait for the DOM to be ready.
$(document).ready(function(){
// Code to execute
});
Or use the shortcut (functions exactly the same as above).
$(function(){
// Code to execute
});
You need to put the eventhandler in $(document).ready(function() {}); and use backgroundColor instead of background-color. In Javascript CSS keys do not have "-" in it, instead they're written together and the second word thick - like backgroundColor or textShadow ;)
$(document).ready(function() {
$("#id").click(function(){
$('#hello').css('backgroundColor', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('backgroundColor', 'red');
}, "json");
});
});
should work (untested)
Is the #id-element embedded in the site, or post-loaded with Ajax? If so, you have to use the following code:
$(document).ready(function() {
$("#id").live({
click: function(){
$('#hello').css('backgroundColor', 'blue');
$.get("test.php",
function(data){
$('body').append( "Name: " + data.name )
.append( "Time: " + data.time );
$('body').css('backgroundColor', 'red');
},
"json"
);
}
});
});

Categories