JQuery.getJson isn't triggered properly - php

I am trying to use JSON for getting dynamic content to my webpage, using javascript. Something is not correct and I have problem figuring out what it can be. In firebug I can see that the JSON-data is retreived as it should. When looking in Firebug under "DOM", the URL I am accessing for the page (the actual page I have created, not the URL to JSON-data) is coloured red (see screenshot below). Here is my javascript:
$(document).ready(function() {
$('#target').click(function() {
alert("At least I',m reached ");
$.getJSON('http://localhost/timereporting/phpscriptlibrary/get_remaining_hours.php', function(data) {
document.getElementById('errorDiv').innerHTML = "Divtext";
alert("Inside getJason");
});
alert("At least I',m done ");
});
This is the significant part of my php file:
$json_string = "{\"activities\": ";
$json_string = $json_string."[";
for ( $counter = 0; $counter < $num; $counter += 1) {
$json_string = $json_string."[".mysql_result($rows,$counter,'date').", \"".mysql_result($rows,$counter,'activity_id')."\", ".mysql_result($rows,$counter,'hours')."]";
if($counter != ($num-1)){
$json_string = $json_string.", ";
}
}
$json_string = $json_string."]}";
echo $json_string;
I assume that "echo" is the way to "send" the JSON-data to the javascript?
One strange thing is that in firebug the JSON-data is presented in two different ways. If you look at the included screenshots below, the second one has dates like "1988" or similar while on the first one the dates are more complete like "2010-12-10". The first screenshot depicts how it should be and that's how I am trying to send it, and obviously it is received like this at some point.
How come my div-tag isn't updated with the date or that the alert inside the $.getJSON isn't triggered, only the alert before and after?

You don't create your JSON strings properly. Every string has to be enclosed in double quotes. But 2010-12-10 is not and jQuery evaluates this as 2010 - 12 - 10 = 1988.
Don't build your string manually, use json_encode, something like:
$data = array();
while(($row = mysql_fetch_array($result))) {
$data[] = array($row['date'], intval($row['activity_id']), intval($row['hours']));
}
echo json_encode(array('activities' => $data));

Related

Formatting JSON formatted text file in PHP

So I got a HTML page with a button. When I click the button, a separate javascript file sends a GET request to my PHP file, expecting a JSON object in return. My PHP reads a JSON formatted text file and should convert it into a JSONObject and echo it out for my javascipt. I had some code working before, but it doesn't seem to do it anymore since I changed to a Ajax aproach instead of having everything in the same file. This is my code:
readLog.php
<?php
class test{
function clean($string){
return json_decode(rtrim(trim($string),','),true);
}
function getLog(){
header('Content-Type: application/json');
$logLines = file('../../../home/shares/flower_hum/humid.log');
$entries = array_map("clean",$logLines);
$finalOutput = ['log' => $entries];
echo json_encode($logLines);
}
}
?>
My humid.log file looks like this:
{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }
{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }
Now If I press my button, this is the response I get checking the console in my web browser:
Response:
["{\"date\":\"26\/09\/2016\", \"time\":\"22:40:46\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }{\"date\":\"26\/09\/2016\", \"time\":\"23:10:47\",\"temp\":\"16.0\", \"humidity\":\"71.0\" }\n"]
JSON:
"{"date":"26/09/2016", "time":"22:40:46","temp":"16.0", "humidity":"71.0" }{"date":"26/09/2016", "time":"23:10:47","temp":"16.0", "humidity":"71.0" }\n"
obviously something is wrong with the formatting, but I don't know what. As I said, this code worked just fine when I had my php and HTML in the same file.
EDIT:
I have also tried formatting the JSON with something like this, but it just prints the brackets:
function getLog(){
$text = file('../../../home/shares/flower_hum/humid.log');
$textRemoved ="["; //Add opening bracket.
$textRemoved .= substr($text, 0, strlen($text)-1); (Remove last comma)
$textRemoved .="]";//Add closing bracket
$json = json_encode($textRemoved);
echo $json;
}
So I managed to solve it myself. Basicly The formatting of the textfile was wrong and as some commentors said, I don't need to encode it if I am doing it myself. What I ended up doing was in my application that generates the log file to add comma after each row. Then in my PHP I added brackets and removed the last comma.
function getLog(){
header('Content-Type: application/json');
$file = file_get_contents('../../../home/shares/flower_hum/humid.log');
$lengthOfFile = strlen($file)-2;
$subFile = substr($file, 0, $lengthOfFile);
$res ="[";
$res .= $subFile;
$res .="]";
echo $res;
}
You can't just jam two+ JSON strings togther. It's JSON, which means it HAS to be syntactically correct Javascript CODE. If you want to join two json strings together, you HAVE to decode them to a native data structure, join those structures together, then re-encode the new merged structure:
$temp1 = json_decode('{"foo":"bar"}', true);
$temp2 = json_decode('{"baz":"qux"}', true);
$new = array_merge($temp1, $temp2);
echo json_encode($new);
which will produce:
{"foo":"bar","baz":"qux"}
and remain valid JSON/Javascript.
Why? Consider that bare integers are valid json:
json_encode(42) -> 42
json_encode(123) -> 123
If you have two json-encoded integers and jam together, you get a "new" integer:
42123
and on the receiving end, you'll be going "Ok, so where is the split between the two", because 4 and 2123 are just as valid as possible original values as 4212 and 3.
Sending the two integers as distinct and SEPARATABLE values would require an array:
[42,123]

Function reports back to a page after a foreach loop (in PHP)

I am writing a foreach loop which will parse directories/subdirectories/files and search and replace values in the files based on a huge array.
This will take some time....probably around 10 minutes...And i was wondering if there is a way with PHP, AJAX maybe, that when i go to the page that it will show me this (for example):
There are X number of values left.
and that number will decrease on every loop the foreach finishes.
So basically i have:
foreach ($array as $key => $value) {
$contents = file_get_contents($file);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
{do stuff here}
}
$param--; // to report back to the page
}
Depends how you want to do it really. You could store it in the database, and simply have the section of the page show you the number you are after. You'd have to add the query to change the number in the foreach as well. So say you do it like this:
<?php
$now = date("Y-m-d");
$getnum = $db->query("SELECT Num FROM mytable WHERE Jobtime = '$now'");
$result = $getnum->fetch();
$whatyouwant = $result['Num'];
if($whatyouwant > 0) { ?>
<p class="whatyouwant" id="whatyouwant"> <?php echo $whatyouwant;?> </p>
<?php } ?>
And change your foreach to do something like:
foreach ($array as $key => $value) {
$contents = file_get_contents($file);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
{do stuff here}
}
$updatestuff = $db->query("UPDATE mytable SET Num = '$param' WHERE Jobtime = '$now'");
}
The downside to this is you have to reload the page to get the info. To bypass this, you can have the first part of my answer ran in AJAX. So you would do:
var reloadFunction = function () {
$.get("getnum.php", function (result) {
$('#holdingwhatyouwant').html(result);
});
};
$(document).ready(function () {
reloadFunction();
setInterval(reloadFunction, 10000);
});
If you do this, you need to mark the place for it on your page, such as:
<div id="holdingwhatyouwant"></div>
Why? Due to limitations. If you use the first method, and put that code on the page, you need to reload the page to see the update. If you use ajax only (similar to what I wrote here), you need to keep the page open for it to work, as well as have a handler (ajax needs to send data to php to be able to know the progress etc, so ajax has to trigger you function). Using them combined, it's all good. If you reload the page you get information instantly, if you don't, you'll get it every 10 seconds. Mind the 10000 interval expressed in milliseconds. Mind that you don't need the if part of the php, as it will return and empty paragraph.

retrieve json formatted data using xmlhttp request

I was using jQuery and this was done easily but I want to change it to regular javascript because I will be using it with phonegap and I don't want to loop through js frameworks every time I make a request to the server. Maybe it's a bad reason to go away from jQuery but seems like it would make everything faster. So I need some help with this code:
<body onload="init();">
<div id="daily"></div>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState === 4 && xmlhttp.status === 200){
var a = JSON.parse(xmlhttp.responseText);
document.getElementById('daily').innerHTML = a.items;
}
};
xmlhttp.open("GET", serviceURL +"getmainnews.php" , true);
xmlhttp.send();
}
</script>
getmainnews.php
//mysqli query
$daily = array();
while ($r = mysql_fetch_assoc($day)){
$daily[] = $r;
}
echo json_encode(array("items" => $daily, "allitems" => $mainnews,...));
In the Chrome DT, I can see the encoded data which is returned but I can't display the first item into my first div with id="daily". With the code I provided, all I get is [object, Object]. What am I doing wrong?
EDIT:
So my query selects the entire row from my database and it's in an array:
{"items":[{"id":"1","pic":"","topic":"daily","article":" \t\t\t\t\t \t\t\t\t\t\u0417...","link":"http://www....","text_cont":..."}]}
How can I display just the pic and the article without all the other junk? Do I have to modify my php file?
EDIT 2:
$day = mysql_query("SELECT pic, article, link FROM table WHERE topic='daily' ORDER BY id DESC LIMIT 1");
$daily = array();
while ($r = mysql_fetch_assoc($day)){
$daily[] = $r;
}
$exc = mysql_query("SELECT pic, article, link FROM table WHERE topic='exclusive' ORDER BY id DESC LIMIT 1");
$excl = array();
while ($e = mysql_fetch_assoc($exc)){
$excl[] = $e;
}
$mus = mysql_query("SELECT pic, article, link FROM table WHERE topic='must' ORDER BY id DESC LIMIT 1");
$must = array();
while ($m = mysql_fetch_assoc($mus)){
$must[] = $m;
}
echo json_encode(array("items" => $daily, "exc" => $excl, "must" => $must));
That's my full php file with the queries. Items, exc, and must are arrays, so the responseText, I guess, is a multidimensional array? Is that the problem I'm having with displaying it?
EDIT 3:
console.log(a.items) gives me an "undefined" so I logged the xmlhttp.responseText.
Without seeing exactly what your JSON looks like it is hard to know for sure. However since you are encoding an array, I suspect changing:
a.items
to
a[0].items
will do the trick...
Edit
I would do:
document.getElementById('daily').innerHTML = JSON.stringify(a.items);
That will convert your object into a string that can be assigned to the innerHTML of an element. I am not sure if this is exactly what you want to do, but when you find the element you want to display using that method should work.
Edit 2
You could change your PHP to only output what you want. However, you could filter it in your JS as well:
a.items[0].pic
and
a.items[0].article
If those don't display as is you can use the stringify method, but you shouldn't need to since those items appear to be strings.
Also note, if you have multiple items you will need to change the 0 to the index of the item you are targeting.

before waiting a response from other script, echo something on screen in php

I have a structure like:
echo 'something' on x.php;
x.php -> Requests to y.php;
while(x.php -> waiting Response from y.php)
do something;
but it did not work, because server is locked onRequest and after getting response print all
of 'something' on the screen.
Note: It is not like 'loading..' structure that i want, it's completely different.
Edit:
The Request code part is like (does not actual code):
while(5){
echo 'hey hey';
}
$whatIWant = 'wanted string';
$myTopicString = 'topic34593495';
while(strlen($myTopicString)>2){
$url = 'y.php/'.$myString;
$r = request($url);
$response = response($r);
if(strpos($response,$whatIWant))
break;
$myTopicString -= 1;
}
what i want is printing 'hey hey' string on the screen and see it before the request.
It appears you're trying to do something AJAX was built for.
So please check out http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
If your script is heavy and needs some severe loading-time you should consider AJAX. So first show the main screen elements. After that you retrieve data using JavaScript.

AJAX enabled web form

I am new to Jquery and want some help from you guys.
i want to decode json data in jquery as i am able to pass data from php to ajax but after it came back in jquery it is not parsing it says undefined. the code is bellow
JavaSript file
$.post("GetData.php", function(data) {
if(data==false)
var tpl = '<p>no record found<p>'
else
var tpl = DrawTableRowsforSection(data);
$("#result").append($(tpl));
},"json");
function DrawTableRowsforSection(p)
{
alert(p.id[0]);
var o = '<table>';
for (var i = 0; i < p.length; i++)
alert(p.id[i]);
o += '<tr><td>'+p.id[i]+'</td><td>'+p.section_name[i]+'<td></tr>';
o+='</table>'
return O;
}
PHP Script
header('Content-Type: application/json');
mysql_connect('localhost','root','') ;
mysql_select_db('news');
session_start();
$query = 'select id,section_name from section';
if ($result = mysql_query($query)) {
if (!mysql_num_rows($result)==null) {
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$id = ToSring($row['id']);
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
The database has a table named section
fields are as follows
id int(11)
section_name varchar(20)
There are total 5 records there.
What I want is to populate a table using returned data.
Can any one guide me where I am making mistake
Regards
Kashif Afzaal
Be sure that mysql returns results and you can take them through ajax.
Also, I've seen the following mistake:
You are using the variable tpl wrong. It is just a js variable, no need to use $ .
Use this way:
$("#result").append(tpl);
OK, from the top in the PHP script:
The MySQL extension is ancient and decrepit. Use MySQLi or PDO.
You never handle a failed MySQL query, so the response will quite possibly be empty. In 99% of cases, any if block should have a corresponding else block.
The result of mysql_num_rows() is never null. Do if (mysql_num_rows($result) > 0), or better yet, just if (mysql_num_rows($result)).
Never do if (!something == something) - it rarely does what you want it to. Do if (something != something)
You never handle mysql_num_rows() failing/giving no rows, so (again) the response will quite possibly be empty.
You never do anything with the $id variable you create.
I'm pretty sure ToSring should read ToString. But there's actually no such function in PHP - you would have either define it or invoke it as a method of a class/object. Indeed, this is likely to be the problem, as it will result in a fatal error.

Categories