So Ive check quite a lot of examples and quite a lot of tutorials but it is definitely not working out for me for some unknown reason.
Ive already checked Get JSON data from another page via JavaScript and it didnt work out for me.
So what I want to do is take some information from MySQL and use it on a Jscript function I am using on another .php, this means taking information retrieved from mysql (connect.php) to another file (test.php), but although the information is correctly retrieved from connect.php it is not moving to the other file.
These are my files.
connect.php
<?php
mysql_connect('localhost', 'root', '') or die (mysql_error());
mysql_select_db('dbexample') or die (mysql_error());
$data = mysql_query("SELECT * FROM lugares")
or die(mysql_error());
$arr = array();
while ($obj = mysql_fetch_object($data)) {
$arr[] = array('latt' => $obj->latt,
'lng' => $obj->long,
'nombre' => $obj->nombre,
'direccion' => $obj->direccion,
);
}
echo '{"users":'.json_encode($arr).'}';
?>
test.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
$.ajax({
type: "POST",
url:"connect.php",
async: true,
success: function(datos){
var dataJson = eval(datos);
for(var i in dataJson){
alert(dataJson[i].latt + " _ " + dataJson[i].lng + " _ " + dataJson[i].nombre);
}
},
error: function (obj, error, objError){
//avisar que ocurriĆ³ un error
}
});
</script>
</head>
<body>
<p>Super freak</p>
</body>
</html>
Any help will be greatly appreciated.
EDIT: I modified my script on test.php but something doesn't feel right; I'm losing it here :(
<script type="text/javascript">
$.ajax({
type: "POST",
url:"connect.php",
dataType: "JSON",
async: true,
success: function(datos){
var dataJson = $.parseJSON(datos);
$.each(dataJson, function(){
alert(dataJson.latt + "_"+ dataJson.lng);
}
},
error: function (obj, error, objError){
//avisar que ocurriĆ³ un error
}
});
</script>
Thanks!
there are two issues
your return type looks like json encoded in connect.php so add dataType: JSON in $.ajax
in test.php your success data should be json decoded to Jquery so you can use $.parseJson(data).
please refer this [example]: (http://www.jquerybyexample.net/2012/05/how-to-read-and-parse-json-using-jquery.html)
Try changing alert(dataJson[i].latt to alert(dataJson[i].users.latt
I may be wrong on this, but it looks like you never get inside the users item that you hardcoded into the response.
i see the problem
$.ajax is jquery element so
first include jquery.js file, then add document.ready inside this use $.ajax
the below example worked for me
this is your test.php
$(document).ready(function(){
//start ajax request
$.ajax({
url: "test.php",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var jsonData = $.parseJSON(data);
//now json variable contains data in json format
alert(jsonData.firstName);//access first array
alert(jsonData.series[0]);//access second array elements
}
});
});
your connect.php should return json encoded array:
$php_array = array('firstName'=>'Walter','lastName'=>'White', 'series'=>array('episode1','episode2'));
echo json_encode($php_array);
Related
I want to call the server function from client side via AJAX.
index.php:
<?php
?>
<html>
<head>
...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
...
console.log(position); // there IS a value! good!
console.log(result); // there IS a value! good!
jQuery.ajax({
type: "POST",
url: 'crud.php',
data: {functionname: 'insertLocation', arguments: [position, result]},
success:function(data) {
alert(data);
}
});
crud.php:
<?php
$position = $_POST["position"]; //NOTHING!
$result = $_POST["result"]; //NOTHING!
include ("insert.php");
switch($_POST["functionname"]){
case 'insertLocation':
insertLocation($position,$result);
break;
}
?>
insert.php
<?php
function insertLocation($position,$result){
...
}
?>
I am losing the value when passing it to the server side. I am able to log the value from JS , but then when I am logging in php there is null (or empty string?). Also query to Database works but no value is inserted.
I am beginner with web programming so I apologise in advance for bad smells, etc.
Yes, $_POST has your variables, but they are located in the array $_POST['arguments'] :
$_POST['arguments'][0] == position
$_POST['arguments'][1] == result
If you want to be able to do $result = $_POST["result"] you must change the params in your AJAX request to
...
data: {functionname: 'insertLocation', position: position, result: result},
...
data: {
functionname: 'insertLocation',
position: position,
result: result
}
I would like to know how I can pass a Javascript array from Javascript to PHP through Jquery/Ajax. In fact I created two files: t1.html and moslem3.php . The code of each file is below:
The code of t1.html:
<html>
<head>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: table
});
});
</script>
</body>
</html>
The code of moslem3.php:
<?php
$myArray = $_REQUEST['table'];
echo $myArray;
?>
The file moslem3.php displays this message:
Notice: Undefined index: table in C:\wamp\www\test1\moslem3.php on line 2
So my question is: where is the wrong here exactly?..Is there any one who has any idea?
Thanks in advance.
PHP doesn't inherently know anything about the JavaScript variables being used, such as var table. Its insights for the $.ajax() request are completed limited to the data structure.
So, for PHP to know about a 'table' parameter in $_REQUEST, the data needs to include it that as a named value:
data: { table: table }
This defines the data as an Object with a property table assigned to the value of the variable by the same name.
You can witness the difference using $.param(), which $.ajax() uses:
var table = ["actor", "subject", "object"];
console.log($.param(table));
// "undefined=&undefined=&undefined="
console.log($.param({ table: table }));
// "table%5B%5D=actor&table%5B%5D=subject&table%5B%5D=object"
Change Jquery
<script type="text/javascript">
$(document).ready(function() {
var table = ["actor", "subject", "object"];
$.ajax({
type: "POST",
url: 'moslem3.php',
data: {t_name:table },
success:function(data){
console.log(data);
}
});
});
</script>
Change in moslem3.php
<?php
$myArray = $_REQUEST['t_name'];
print_r($myArray);
?>
Output:
Try this :
$.ajax({
type : "POST",
url: 'moslem3.php',
cache:false,
async:true,
global:false,
data : {
"table": table }
}).done(function(msg) {
alert(msg);
})
I am exploring the ajax synchronous json import into my javascript code.
The JSON source link I want to use is
http://www.nusantech.com/hendak/default.php?m=galaksi&galaksi=1&viewID=1&t=json
But to keep server loads down, a week ago or so I created a static page showing the same data at
http://www.nusantech.com/hendak/noobjson.php
My javascript import is as below:
<head>
<title>Nusantech</title>
<script src="\OpenLayers213\OpenLayers.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
var jsonData = {};
$.ajax({
url: "http://hendak.seribudaya.com/noobjson.php",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
alert("Galaksi value retrieved from JSON (expected: 1) : "+jsonData.galaksi);
</script>
<script type="text/javascript">
function kemasMaklumat(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
</head>
From there I retrieve the values I want on jsonData, eg, (x,y) coordinates as
(jsonData.planets[7].coordinates[0].x,jsonData.planets[7].coordinates[0].y)
It works fine with the noobjson.php link, but when I point it back to default.php, nothing appears. The page took a while to load which make it seem like its loading the json values, but the alert("Galaksi value retrieved") returns undefined.
I copy & pasted the output from the default.php page on a JSON verifier on the web and it showed OK. I don't know why the static link works but the $_GET based link doesn't.
Can someone suggest me what is happening?
EDIT
I have tried:
<script type="text/javascript">
var jsonData = {};
$.ajax({
// url: "http://hendak.seribudaya.com/noobjson.php",
url: "http://hendak.seribudaya.com/default.php?"+encodeURIComponent("galaksi=1&viewID=1&m=galaksi&t=json"),
// url: "http://hendak.seribudaya.com/default.php?galaksi=1&viewID=1&m=galaksi&t=json",
async: false,
dataType: 'json',
type: 'GET',
contentType: "application/json",
success: function(data) {
jsonData = JSON.parse(JSON.stringify(eval("("+data+")")));
alert("Success");
},
error: function(data) {
alert("Failed to download info." + data);
}
});
</SCRIPT>
enter code here
I always get the Failed to download info unless I use the noobjson URL.
It is as if that URL with the GET doesn't exist.
You have to encode the URL component before sending the request. Try:
$.ajax({
url: "http://www.nusantech.com/hendak/default.php?" + encodeURIComponent('m=galaksi&galaksi=1&viewID=1&t=json'),
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
Reference: encodeURIComponent()
I have solved it.
In the default.php, what I have done was:
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
if ($_GET["t"]!="json") { echo "<PRE>\n"; $lb="\n"; }
echo "{\"galaksi\": ".$galaksi.",";
echo $lb."\"hari\": ".$hari.",";
echo $lb."\"planets\": [";
//etc
//etc
}
So I replaced all the individual echoes with $JSONstr like below.
if ($_GET["t"]=="json") {
$viewID=$_GET["viewID"];
$galaksi=$_GET["galaksi"];
$con=mysqli_connect($server, $user, $password, $database);
$sql="SELECT Hari FROM berita WHERE Galaksi=".$galaksi;
$hari=1;
$result = mysqli_query($con,$sql); while(($row = mysqli_fetch_array($result)) ){$hari=$row['Hari']; }
$lb="";
$JSONstr="";
// if ($_GET["t"]!="json") { $JSONstr="<PRE>\n"; $lb="\n"; }
$JSONstr=$JSONstr."{\"galaksi\": ".$galaksi.",";
$JSONstr=$JSONstr.$lb."\"hari\": ".$hari.",";
$JSONstr=$JSONstr.$lb."\"planets\": [";
//etc
//etc
//and at the end:
echo $JSONstr;
}
Then I added the echo $JSONstr; at the end. Originally I did that so that I can do :
echo json_encode($JSONstr);
but this creates {\"Galaksi\" : 1} at the JSON output instead of the intended { "Galaksi": 1 }
So I removed the json_encode and just output the string.
Also I had to remove the
if ($_GET["t"]!="json"){ $JSONstr="<PRE>\n"; $lb="\n"; }
I also used a different JSON tester this time.
Originally I used http://www.freeformatter.com/json-validator.html which says JSON Valid for my initial JSON output. Then I used this one, which said that my JSON output url was invalid, although if I copy+paste the output string it returned valid. http://jsonformatter.curiousconcept.com/
So after making those changes and removing the "<PRE>", the curiousconcept validator gave me a valid status.
Then I used this in the javascript, and I am now able to retrieve expected values.
Thank you all, hope this helps someone else too.
My aim here is to replicate the Hot Towel SPA framework from ASP.NET in PHP.
I have two files in my project: show.js and displaystring.php. What I basically want to do is return whatever is present in the displayString() function. But due to a series of unsuccessful attempts, I inserted the debugger statement in the shows.js file (as marked in the source code below) to find out what's wrong. When I run the project in Google Chrome and open the developer tools (Ctrl + Shift + i), I see that the program flow stops at the debugger statement (as expected) and when I hover my mouse over the data variable in the success property, I see that the displaystring.php file returns me the entire html source code instead of just returning the ".$_POST('string'); statement.
I have gone through many solutions on the internet but to no avail. Can anyone please tell me where exactly am I going wrong? Thank you.
show.js
define(function (require) {
var val = "";
//var moviesRepository = require("repositories/moviesRepository");
$.ajax({
url: "controllers/displaystring.php",
type: "post",
data: {input:"show"},
datatype: 'json',
success: function(data){
val = data;
debugger; // Debugger inserted here.
}});
return {
result: ko.observable(),
activate: function() {
this.result(val);
}
};
});
displaystring.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>String Display</title>
</head>
<body>
<?php
function displayString() {
return "The string passed is: ".$_POST('string');
}
displayString();
?>
</body>
</html>
Try this way
displaystring.php :
<?php
function displayString() {
return "The string passed is: ".$_POST['input'];
}
echo displayString();
?>
First of all you must specify headers:
header('Content-type: text/json');
header('Content-type: application/json');
Second you must to formmat your content for this kind of headers:
<?php
function displayString() {
return json_encode($_POST);
}
echo displayString();
?>
And also you must to read official documentation:
Headers in php
JSON format
You php file must be something like that:
<?php
header('Content-type: text/json');
function displayString() {
return json_encode($_POST);
}
echo displayString();
Okay after banging my head against a stone wall for the whole day, I figured out the solution myself.
I just modified the code a bit to serve the purpose of finding the answer to my question.
show.js
define(function (require) {
return {
result: ko.observable(),
activate: function() {
//var moviesRepository = require("repositories/moviesRepository");
var self = this;
$.ajax({
url: "controllers/displaystring.php",
type: "get",
data: {input:"show"},
dataType: "html",
success: function(data){
self.result(data);
debugger;
}});
}
};
});
displaystring.php
<?php
function display() {
echo 'Hi I am some random '.rand().' output from the server.';
}
display();
//echo "Hello World!";
?>
And that's it! You don't have to type the entire HTML code for the PHP file. Just include the PHP script and you will get the output.
Thank you all very much for your help. :)
Have only PHP script like #tyagi mentioned & change $_POST('string') to $_POST['string].
Make Sure You didn't print the html in config file or constructor or something like that. I got the the same problem. Solution is to create separate file to handle the ajax request.
I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());