I have a connection to remote DB and I have get some statistical data from the DB. So I have decided to create a web service and get the desired data through it. DB server is SQL Server on Windows and I need to display data in my PHP web page.
First I have written the web service which returns string like
"[
{
"name" : "John",
"Age":"54"
},
{
"name":"Jack",
"Age":"33"
}
]"
I have got that string using PHP's file_get_contents() method.
$json = file_get_contents('http://myurl.org/services.asmx/namelistJson');
But there are some unwanted tags return, in the beginning
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://myurl.org/services.asmx?op=namelistJson">
in at the end
</string>
I clean them using
$json = strip_tags(file_get_contents('http://myurl.org/services.asmx/namelistJson'));
Now I have a json string.
I want to use this string as JSON for javascript in order to create a table.
<?php
$json = strip_tags(file_get_contents('http://myurl.org/services.asmx/namelistJson'));
?>
<script>
var response = $.parse(<?php echo $json; ?>);
$.each(response, function(i, item) {
$('<tr>')
.html("<td>" + response[i].name + "</td>"
+ "<td>" + response[i].Age + "</td>"
)
.appendTo('#nameList');
});
</script>
?>
<table id="nameList" class="table">
</table>
I am getting error about missing ] symbol. FireBug says that
SyntaxError: missing ] after element list
How can I convert string to json properly in order to use it on javascript?
EDIT:
If I modify the line
var response = $.parse(<?php echo $json; ?>);
to
var response = <?php echo $json; ?>;
I get ] error still.
HTML output is as the following:
<script>
...
var response = [{"name" : "John", "Age" : "14"}, {"name" : "40"}, ... ];
...
</script>
No need to create a string and then again convert it to json object, you can directly send json object from webservice and directly use it in the scripts(jquery) as below:
Below is the code in my webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static object GetGridData()
{
DataTable dt = GetRecords(); // Fetch the data from sql in form of a datatable
var returnData = from row in dt.AsEnumerable()
select new
{
Id = row["Id"] // Here the Id in row["Id"] specifies the column in database
name = row["name"],
age = row["age"]
};
return returnData;
}
To access it as object in jquery, use the below code:
$.ajax({
url: 'url of webservice along with method',
dataType: 'json',
contentType: 'application/json; charset=utf-8;',
tyep: 'GET',
success: function (datas) {
var data = datas.d;
$.each(data, function (index, value) {
$('<tr>').html("<td>" + value.name + "</td>"+ "<td>" + value.Age + "</td>"
).appendTo('#nameList');
});
},
error: function (error) {
alert('error occured');
}
});
But if you really want to send it using string and parsing it into json then you can use
var jsonObject = JSON.parse(jsonstring);
or else you can verify if your json string is valid or not by just pasting your json string in jsonlint.com
Hope this helps :)
Related
i have a problem when parsing json from php to javascript
this is my example code :
//function
MethodAjax = function (wsFile, param) {
return $.ajax({
type: "POST",
dataType: "json",
url: '../proses/' + wsFile + ".proses.php",
data: 'param='+param,
error: function (msg) {
return;
},
});
};
//call function
$(document).ready(function() {
$('#getproduk').click(function(){
var param = {
ProdukId : '1',
ProdukName : 'test'
};
CallMethodWithAjax('try', JSON.stringify(param)).done(function(data){
$data = JSON && JSON.parse(data) || $.parseJSON(data);
});
});
//Simple Php code
<?php
$data = $_POST['param'];
$data = (json_decode($data));
$data1['name'] = $data->ProdukName;
$data1['id'] = $data->ProdukId;
$data1['test'] = 'test';
echo json_encode($data1);
?>
//post, response and error at console
response : {"name":"test","id":"1","test":"test"}
post : param {"ProdukId":"1","ProdukName":"test"}
error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
how to solve this probled, i have try the solution that i found at SO and google, but still cannot solve this problem
please someone help
thanks
jQuery's $.ajax() function will yield a JavaScript object if the response is JSON so I believe the error you're seeing is a result of trying to parse a JavaScript object and not a string as you're expecting. In the callback you're providing to the done function, inspect data and you'll find that it's an object and there is no need to JSON.parse the result.
I was wondering if you could help. I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. It is essential that the files stay separate. Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable.
My current code is as follows:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt( $stmt);
?>
Any help would be greatly appreciated.
You could send data using your Ajax request like so.
$.ajax({
url: "http://IP/development/Query01.php",
method: "POST" // send as POST, you could also use GET or PUT,
data: { name: "John", location: "Boston" }
dataType: "json",
success: function(data) {
editors['Contact2'].setValue(data);
}
});
Then in PHP access the sent data:
<?php
print_r($_POST);
/*
[
"name" => "John",
"location" => "Boston"
]
*/
?>
You cannot pass the javascript's variable to php on same page.
You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable.
You can do it in a single Ajax call.
Remove from your code this line:
window.location.href = "http://IP/development/Query01.php?service=" + a;
And modify a bit the Ajax call
$.ajax({
type: 'GET'
data : {
service: sender.getValue();
},
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
I put the same variable name for the Get in the Ajax call. But I don't know if your query01.php should accept to do now both actions in the same call.
Thank you guys for your help. Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job.
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
{
// Variable Declaration
serviceName = sender.getValue();
{
// Use JQuery.Ajax to send a variable to the php file, and return the result.
$.ajax({
// Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
// method to access the javascript variable to apply it within the SQL Query.
url: "http://ServerName/development/DefaultContact1.php?service=" + serviceName,
// retrieve the result, using json.
dataType: "json", // the return type data is jsonn
success: function(data)// <--- (data) is in json format
{
// pre-fill the contact1 field with the result of the PHP file.
editors['Contact1'].setValue(data);
}
// End of Ajax Query
});
// End of function to prefill Contact1 field.
Thank again for your responses!
(Secondary title): ajax array recieved as json encoded PHP array not behaving as javascript array
For some reason, my PHP array gets sent over to JavaScript just fine, but when I try to access an individual key of the array, it doesn't return anything, or it returns some other value which doesn't correspond. I am of course using json_encode() in the corresponding PHP file (echoClientData.php):
$id = $_GET['selected_id'];
$id = str_replace("clientSel","",$id);
$getclientinfo = "SELECT * FROM `clients` WHERE `ClientID` = $id";
if ($result = $Database->query($getclientinfo))
{
$row = $result->fetch_row();
$output = $row;
}
echo json_encode($output);
This code works fine:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data;
$('#client-detail-box').html(test);
}
});
And returns an array into the #client-detail-box div, e.g.
["1566","","Adrian","Tiggert","","","","","","","","","","","","0000-00-00","0000-00-00","0.00","","0","","","102","Dimitri Papazov","2006-02-24","102","Dimitri Papazov","2006-02-24","1","0","0"]
However, when I do
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
}
It returns
5
You may need to do one of two things when returning JSON from PHP.
Either set your content type in PHP before echoing your output so that jQuery automatically parses it to a javascript object or array:
header('Content-type: application/json');
or specify that jQuery should treat the returned data as json:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
dataType: 'json',
success: function(data)
{
var test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
Be aware, that in your current PHP script, in the event that your query fails, you will be json_encodeing an undefined variable.
Also, your PHP code is entirely open to SQL injection. Make sure you sanitize your $id, either by casting it to (int) or by escaping it before sending it through in your query.
Have you tried using JSON.parse on the value you are getting back from PHP?
e.g.
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = JSON.parse(data); // should be "Tiggert"
$('#client-detail-box').html(test[3]);
}
});
That seems like it would be a fix.
This code is working fine my concern is its output
Javascript side
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value;
$.get('includes/getChat.php?chat='+uid + '&rid=' + rid + '&name=' + user,function(data)
{
$("#clog").html(data);
});
}
PHP side
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT * FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$rows = $stmt7->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
the output looks like this:
[{"msgid":"1","message_content":"asd","username":"ab","message_time":"2014-04-02 13:58:03","recipient":"cd"}]
how can I display the JSON result similar to this:
1
asd
ab
2014-04-02
cs
You can use the json dataType in jQuery, then stringify the object with indentation using JSON.stringify and output it in pre tags to keep the spaces and newlines
function AjaxRetrieve(){
var rid = document.getElementById('trg').value,
data = {chat : uid, rid : rid, name : user};
$.get('includes/getChat.php', data, function(result) {
var pre = $('<pre />', {text : JSON.stringify(result, undefined, 4)})
$("#clog").html(pre);
}, 'json');
}
FIDDLE
or to just output a list of the values
function AjaxRetrieve() {
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}
Parse response on client side, and display it.
$.get('includes/getChat.php?chat='+uid + '&rid=' + rid + '&name=' + user,function(data){
var obj = JSON.parse(data);
var temp = obj[0].msgid + "<br>"+ obj[0].message_content + "<br>"+ obj[0].username + "<br>"+ obj[0].message_time + "<br>"+ obj[0].recipient;
$("#clog").html(temp);
});
PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.
Below is the link:
http://php.net/manual/en/function.json-encode.php
<?php
$json_string = json_encode($data, JSON_PRETTY_PRINT);
I have a JQuery AJAX request send off some JSON data to a PHP script, however, when it comes to manipulating the data or even trying to access it, it behaves like a string but I need it to behave like an associative array.
JavaScript
var all_data = [];
$.each($("[id*=card]"), function(i, value) {
var name_a = $(value).find('#story_name_div').text();
var text_a = $(value).find('#story_text_div').text();
var point_a = $(value).find('#story_point_div').text();
var phase_a = $(value).find('#story_phase').val();
var date_a = $(value).find('#story_date').val();
var author_a = $(value).find('#username_div').text();
var story_data = {
"name": name_a ,
"text": text_a ,
"point": point_a ,
"data": phase_a ,
"date": date_a ,
"author": author_a
};
all_data.push(story_data);
});
$.ajax({
url: 'save_server_script.php',
type: 'POST',
processData:false,
dataType: "json",
data: "json=" + JSON.stringify(all_data),
success: function(res){
var json_a = $.parseJSON(res);
console.log(json_a);
},
error: function(err){
console.log("error");
}
});
JSON that is created
[json] => [{"name":"jhb","text":"gjh","point":"jhv","phase":"planning","date":"21/9/2013 - 4:23:16","author":"Created by - ljhlkjhb"}]
PHP
print_r($_POST); // prints out entire JSON
print($_POST["json"][0]["story_name"]);
// Warning : Illegal string offset 'story_name' in C:\xampp\htdocs\save_server_script.php on line 15
print($_POST["json"][0]); // prints out a '['
foreach($_POST["json"] as $hello) { // invalid argument supplied for foreach
print $hello["story_name"];
}
I have also tried decoding via PHP but to no avail.
Try
$json = json_decode($_POST['json']);
echo $json[0]->author;
In your snippet you're referring to story_name, but that's not an element in your JSON string.
You have to decode the json into array in php first:
$arr = json_decode($_POST["json"]);
//now you can use foreach on the array it returned
foreach($arr as $key => $value){
//now you can use $value["text"] , $value["author"] etc
}
The data received by php is in json format that needed to be converted into array format in order to use foreach on it.
PS There is not "story_name" in your json data.