I am trying to parse the JSON string sent as ajax response from PHP file using jQuery / JavaScript.
Ajax call:
<script>
$(document).ready(function(){
var query = $("#editor").html().replace(/(<([^>]+)>)/ig,"");
$.ajax({
type: "POST",
url: "app/query_db.php",
data: "q="+query,
success: function(resp){
if(resp) {
alert("Response : "+resp);
$("#res_data").html(resp);
}
else{
alert("Response: Failed")
}
});
return false;
});
});
</script>
PHP file :
$db_conn = new db_connect();
$conn = $db_conn->connectToDB($DBHost,$DBName,$DBUser,$DBPwd);
$query_res = array();
if (fill_numeric_array_with_query_assoc($query_res, $sql_query, $conn)) { // Function to execute the query and fill the result
//do nothing
} else {
echo("Error description: " . mysqli_error($conn)); // Error message to display if failed to fetch the data
exit();
}
$data = json_encode($query_res);
echo $data;
Result: [{"uid":"admin","pwd":"xyz"},{"uid":"guest","pwd":"abc"}]
Whenever I try to parse the above JSON string I am ending up with 0 and 1 as keys and the other stuff as values. The strange thing is when I copy this result and assign it to a variable in JavaScript it's parsing the string correctly.
Don't know what's going wrong when trying to parse it as AJAX response.
Table format when parsed the JSON string as AJAX response:
Response when assigned to variable in javascript :
uid pwd
admin xyz
guest abc
This will take the data and turn each object into a row in a table. I'm going to assume that #res_data is an empty <table> element.
$.ajax({
type: "POST",
url: "app/query_db.php",
data: "q=" + query,
dataType: "json",
success: function(resp) {
if (resp) {
alert("Response : " + resp);
$("#res_data").empty();
if (resp.length > 0) {
var header = "<tr>";
for (var key in resp[0]) {
"<th>" + key + "</th>";
}
header += "</tr>";
$("#res_data").append(header);
var rows = "";
for (var i=0; i< resp.length;i++) {
rows += "<tr><td>" + resp[i].uid + "</td><td>" + resp[i].pwd + "</td></tr>";
}
$("#res_data").append(rows);
}
else { alert("No data returned"); }
} else {
alert("Response: Failed")
}
}
});
Note the extra ajax option: dataType: "json". This is important. Because your PHP doesn't send any header to tell the client to interpret the response as JSON, it likely interprets it as text. So you have to add dataType:"json" so jQuery knows what to do, and makes the response directly into a JS object. Then you should have no problem. If you don't, then it will see it as a string, and then loop through it one character at a time, which will result in the strange output you showed in the question.
Related
previously I was sending a single value from controller to view and it was successfully got. Now I want to send two values by using JSON data.
Controller
$batch_wise_stock = sprintf('%0.2f',(!empty($pur_product_batch->purchase_qty)?$pur_product_batch->purchase_qty:0)-(!empty($sellt_prod_batch->sale_qty)?$sellt_prod_batch->sale_qty:0));
$batch_wise_rate = $pur_product_batch->rate;
$json_product[] = array('qty'=>$batch_wise_stock,'rate'=>$batch_wise_rate);
echo json_encode($json_product);
AJAX
$.ajax( {
url: base_url + "invoice/invoice/batchwise_productprice",
method: 'post',
dataType: "json",
data: {
prod_id: prod_id,
batch_no:batch_no,
csrf_test_name:csrf_test_name,
},
success: function( data ) {
var obj = jQuery.parseJSON(data);
console.log(obj);
if (parseInt(data) >= 0) {
$(".available_quantity_" + sl).val(data.toFixed(2,2));
}else{
var message = "You can Sale maximum " + available_quantity + " Items";
toastr["error"](message);
$("#total_qntt_" + sl).val('');
var quantity = 0;
$("#total_price_" + sl).val(0);
for(var i=0;i<taxnumber;i++){
$("#all_tax"+i+"_" + sl).val(0);
}
}
}
});
error
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Try looping through your returned data... (then compare with obj later)
$.each(data, function(index, value ){
$('#item_qty' + sl).val(value.qty); //console.log() or alert();
$("#item_price" + sl).val(value.rate);
});
I have a JSON code that send a form to on PHP file and I want to use data in PHP
the code is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/yadavari/test.php?";
var json_text = JSON.stringify($("form[name='add']").serialize(), null, 2);
var datas = JSON.parse(json_text);
ajx = $.ajax({
url: url,
type: 'post',
data: datas,
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r);
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error msg');
alert( "ERROR: " + err + " - " );
}
Now I want to fetch data from this JSON code in my PHP page.
I searched but every body just said that $string='{"name":"John Adams"}'; and so.
But I dont know that how can I have this $string in my PHP.
You should have something like:
<?php
echo $_POST["INPUTNAME"];
?>
Care about this, it suffers from security injection.
You need to call the php json_decode function on the returned string. This will convert it into an associative array:
$json2array = json_decode($json_text);
echo $json2array['name']; // "John Adams"
I have a js script that does an ajax request and posts the data to a php script, this script with then echo something back depending if it works or not.
here is the JS
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
}, 6000);
});
here is the php:
if(isset($_POST["json"]))
{
$json = json_decode($_POST["json"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
So basically, i thought the response in the `success: function(response)' method would be populated with either "IT WORKED!!!" or "NOT POSTED" depending on the if statement in the php. Now everything seem to work because the js script manages to go into the success statement but prints this to the console:
Response was null
I need to be able to get the return from the server in order to update the screen.
Any ideas what I'm doing wrong?
Try:
if(isset($_POST["markets"]))
{
$json = json_decode($_POST["markets"]);
if(!empty($json))
{
echo "IT WORKED!!!!";
}
else
echo "NOT POSTED";
}
use this in your php file
if(isset($_POST["markets"]))
{
}
instead of
if(isset($_POST["json"]))
{
.
.
.
.
}
Obiously the if(isset($_POST["json"])) statement is not invoked, so neither of both echos is executed.
The fact that the function specified in .ajax success is invoked, only tells you that the http connection to the url was successful, it does not indicate successful processing of the data.
You are using "success:" wrong.
Try this instead.
$.post("signals.php", { markets: post_data }).done(function(data) {
/* This will return either "IT WORKED!!!!" or "NOT POSTED" */
alert("The response is: " + data);
});
Also have a look at the jQuery documentation.
http://api.jquery.com/jQuery.post/
Look, You send data in market variable not in json. Please change on single.php code by this.
$json_data = array();
if(isset($_POST["markets"]))
{
// $json = json_decode($_POST["markets"]);
$json = ($_POST["markets"]);
if(!empty($json))
echo "IT WORKED!!!!";
else
echo "NOT POSTED";
}
And change on your ajax function
$(document).ready(function(){
var post_data = [];
$('.trade_window').load('signals.php?action=init');
setInterval(function(){
post_data = [ {market_number:1, name:$('.trade_window .market_name_1').text().trim()},
{market_number:2, name:$('.trade_window .market_name_2').text().trim()}];
$.ajax({
url: 'signals.php',
type: 'post',
// contentType: 'application/json; charset=utf-8',
data:{markets:post_data},
dataType: "json",
success: function(response){
console.log("Response was " + response);
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
},6000);
});
You have to you change you $.ajax call with
//below post_data array require quotes for keys like 'market_number' and update with your required data
post_data = [ {'market_number':1, 'name':'name1'},
{'market_number':2, 'name':'name2'}];
//console.log(post_data);
$.ajax({
url: "yourfile.php",
type:'post',
async: true,
data:{'markets':post_data},
dataType:'json',
success: function(data){
console.log(data);
},
});
and you php file will be
<?php
if(isset($_POST['markets']))
{
echo "It worked!!!";
}
else
{
echo "It doesn't worked!!!";
}
//if you want to work with json then below will help you
//$data = json_encode($_POST['markets']);
//print_r($data);
?>
in your php file check the $_POST:
echo(json_encode($_POST));
which will tell if your data has been posted or not and the data structure in $_POST.
I have used the following code to covert the posted data to associative array:
$post_data = json_decode(json_encode($_POST), true);
After a week of googling and search.I am hard to find even a single tutorial about long polling from a database table instead of from a flat text file named data.text. Currently, I write manually anything in data.text and it instantly appears in the browser.
This is the question: Long polling using database? is not answered properly even in StackOverflow. (I found a lot here but in vain.).Example of this is also here
filemtime alternative for MySQL
How can I modify getdata.php to make it enable for fetching data from database?
$sql=mysqli_query($database,"SELECT * FROM messages where time>=$curr_date ORDER by time DESC");
while($row=mysqli_fetch_array($sql)){
$messages=$row['messages'];
$id=$row['id'];
echo $messages;
}
Messages table is as follows
id fro to mesg time status last_modified
I am here listing an example.
In this example, three files are being used.
index.html
getdat.php
data.text
Is there any need to make a fourth file to get data from database(mysql)? if not, then what type of changes are necessary in the getdata.php or data.text to use dynamic data from database?
Here is my Javascript
<script type="text/javascript" charset="utf-8">
var timestamp = null;
function waitformsg() {
$.ajax({
type:"Post",
url:"getdata.php?timestamp="+timestamp,
async:true,
cache:false,
success:function(data) {
var json = eval('(' + data + ')');
if(json['msg'] != "") {
$("#messages").append(json['msg']);
}
timestamp = json["timestamp"];
setTimeout("waitformsg()", 1000);
},
error:function(XMLhttprequest, textstatus, errorthrown) {
alert("error:" + textstatus + "(" + errorthrown + ")");
setTimeout("waitformsg()", 15000);
}
});
}
$(document).ready(function() {
waitformsg();
});
</script>
Here is the getdata.php file
<?php
include("../model/includes/classes.php");
$filename='data.php';
$lastmodif=isset($_GET['timestamp'])?$_GET['timestamp']:0;
$currentmodif=filemtime($filename);
while($currentmodif<=$lastmodif){
usleep(10000);
clearstatcache();
$currentmodif=filemtime($filename);
}
$response=array();
$response['msg']=file_get_contents($filename);
$response['timestamp']=$currentmodif;
echo json_encode($response);
?>
I have done something very similar recently. I did use jQuery .ajax call instead of the generic XMLhttprequest but the idea is the same:
recentFunction(container, lastDate){
var lastDate = "";
return $.ajax({
type: "POST",
url: "getData.php",
cache: false,
data: { 'request': 'recent',
'param': lastDate },
dataType: "json",
success: function(data){
if(data != null){
$.each(data, function(key, value){
if(key == 0){
lastDate = value['date_added'];
}
var html = "some html here";
// append html to dom element here
// and delete any old items here if needed
});
}
},
complete: function(){
setTimeout(function(){recentFunction(container, lastDate)}, 7000);
}
});
}
in the getData.php file I have query with a where clause that gets any items from db that are more recent than last element. Default value for $lastDate is set to 0, so it returns all items if no date is submitted.
<?php
$lastDate = 0;
$recent = array();
$recentQuery = "SELECT id, date FROM someTable WHERE date > '" . $lastDate . "'";
$recentResults = $db->query($recentQuery);
while($r = $recentResults->fetch_array(MYSQLI_ASSOC)){
$recentMovies[] = $r;
}
echo json_encode($recentMovies);
?>
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}