jQuery dataTables not loading AJAX JSON data - php

I have a table that is populated via dataTables with information from a MySQL table. The information is prepared via PHP as proper JSON in the way dataTables expects the information.
The problem I'm having is the table no longer loads informations. Even reverting my changes so that the JSON data does not include links to the server description (via view.php) doesn't change anything.
The site can be found here: checkersthecat.com/status The PHP that outputs JSON information can be found here: checkersthecat.com/status/inc/json-servers.php
Here is the code for json-servers.php
<?php
$db = new PDO("mysql:host=localhost;dbname=mcstatus;charset=UTF8", "user", "pass");
$stmt = $db->prepare("SELECT ip, port, category, players, tries, description FROM clients");
$stmt->execute();
$servers = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
$data = array(
"aaData" => array()
);
foreach ($servers as $item) {
$arr = array();
// Address
if (strlen($item['description']) == 0) {
if ($item['port'] != 25565) {
array_push($arr, $item['ip'] . ":" . $item['port']);
} else {
array_push($arr, $item['ip']);
}
} else {
if ($item['port'] != 25565) {
array_push($arr, "<a href='inc/view.php?ip=" . $item['ip'] . "'>" . $item['ip'] . ":" . $item['port'] . "</a>");
} else {
array_push($arr, "<a href='inc/view.php?ip=" . $item['ip'] . "'>" . $item['ip'] . "</a>");
}
}
// Category
array_push($arr, $item['category']);
// Status
if ($item['tries'] == 0) {
array_push($arr, "Up");
} else {
array_push($arr, "Down (" . $item['tries'] . ")");
}
// Players
if ($item['players'] == -1) {
array_push($arr, "?");
} else {
array_push($arr, $item['players']);
}
array_push($data['aaData'], $arr);
}
header("Content-type: application/json");
echo json_encode($data);
?>
The snippet of javascript that actually initializes and sets up the dataTable is here:
// init load of table
serverTable = $("#servers").dataTable({
"bProcessing": true,
"bStateSave": true,
"sPaginationType": "two_button",
"sAjaxSource": "http://checkersthecat.com/status/inc/json-servers.php"
});
It literally worked, I changed one small item relating to the description length in the javascript relating to a jQuery modal dialog form, I refreshed the page, and suddenly dataTables no longer loads my JSON information.
I'm at a total loss as to why it will not work. Even reverting to my old code without the hyperlinks in the JSON data and previous description limits doesn't make a difference. It still gives me an endless "Processing" and "Loading". When I try to search it merely says "No data available" which is ludicrous as the JSON information is right there at the URL and is valid.
I've tried debugging the javascript and PHP with firebug and turning on error reporting respectively, but apparently there isn't anything wrong with it all as far as I know.
Any help is very appreciated as this has had me tearing my hair out. If there's any other details that you may need, please let me know.

It works, but I'm unsure what exactly the problem was.

Related

PHP Batch upload array data

I am working with a client API (master API) that does not have a bulk feature.
I have taken data from 2 different API's (client API's) and merged it into one JSON file that is properly formatted. Checked in online JSON Validator.
The JSON File is 1100 records of merged customer data. Taking one record at a time, I have built a function that submits the data successfully to the master API.
I have now built a PHP script that loops through the JSON File and takes the row data (each client record) and submits it to the master API successfully. After about 90 rows, the PHP script times out.
I have set the following code on the page
#ini_set('zlib.output_compression', 0);
#ini_set('implicit_flush', 1);
set_time_limit(600);
#ob_end_clean();
And am buffering each update to return a JSON status code returned from the master API.
What should I be doing to get the PHP to not time out after about 100 records and keep updating the buffer response on the page.?
Thanks in advance.
Jason
I've taken a few of different approached to this kind of problem in the past. The only quick fix for this is if you can change the php.ini settings on the server to increase the timeout enough to allow your batch to complete. This is not a great solution, but it is a solution.
The next option (in ascending order of effort) is to set up a loop between the browser and your server where your browser makes a request, the server sends a portion of the records, then returns to the browser with a cursor indicating where the process left off, the browser makes another request to the server, sending the cursor back as a parameter, and this continues until the batch finishes. This is nice because you can display a progress bar to the user.
Finally, you could have an agent running on the server that waits for batch jobs to be submitted and runs them completely outside of the HTTP request lifecycle. So your browser makes a request to kick off a batch job, which results in some sort of record in a database that can keep track of the status of the job. The agent picks up the job and sets it to a pending state while it works, then sets the completion status when it finishes. You can set set something up that allows you to poll the server from the browser periodically so you can alert the user when the process finishes. Of you can just have the agent send an email report to the user when the batch completes. This is the most solid option with the least risk of something interrupting the processing, and it can leave an audit trail without any effort at all. But it's clearly more complicated to set up.
Thanks Rob.
Your response sent me in the right direction.
I sort of used your backend idea on the frontend. I just looped through 20 records at a time and then refreshed the page via javascript and started at 21 to 40 etc. Threw in a progress bar for fun as well.
Thanks for helping me get my head around the idea. Not the right way to do it, but my Python is just as bad as my PHP.
<?php
#ini_set('zlib.output_compression', 0);
#ini_set('implicit_flush', 1);
set_time_limit(600);
#ob_end_clean();
require("header.php");
require_once('nav.php');
function sync_systems($sfData){
$dataPost = $sfData;
$postID = $dataPost['ID'];
$epcall = update_profile($dataPost);
$epResult = json_decode($epcall, true);
if($epResult['status'] != 404){
$sfStatus = updateSFOpportunity($epResult['client_id'], $epResult['ep_id'] );
if($sfStatus == 1){
$datamsg = " Success! The sync was a success in both Salesforce and other system. OtherSystem Record " . $epResult['ep_id'] . " was created or updated.<br/>";
} else {
$datamsg = " Success! The sync was a success in other system, but failed in Salesforce<br/>";
}
echo json_encode(['code'=>200, 'msg'=>$datamsg]);
} else {
$datamsg = " Failure! The sync did not work.<br/>";
echo json_encode(['code'=>404, 'msg'=>$datamsg]);
} // end epResult
}
function sync_ep($sfData){
$dataPost = $sfData;
$postID = $dataPost['ID'];
$epcall = update_profile($dataPost);
$epResult = json_decode($epcall, true);
if($epResult['status'] != 404){
// $sfStatus = updateSFOpportunity($epResult['client_id'], $epResult['ep_id'] );
if($sfStatus == 1){
$datamsg = " Success! The sync was a success in both Salesforce and other system. Other System Record " . $epResult['ep_id'] . " was created or updated.<br/>";
} else {
$datamsg = " Success! The sync was a success in other system, but failed in Salesforce<br/>";
}
echo json_encode(['code'=>200, 'msg'=>$datamsg]);
} else {
$datamsg = " Failure! The sync did not work.<br/>";
echo json_encode(['code'=>404, 'msg'=>$datamsg]);
} // end epResult
}
$ju = "CustomerData20Fall.json";
//read json file from url in php
$readJSONFile = file_get_contents($ju);
//convert json to array in php
$jfile = json_decode($readJSONFile);
//print_r($jfile);
//convert json to array in php
$epSync = array();
$oldValue = 0;
$total = count($jfile );
?>
<!-- Progress bar holder -->
<div id="progress" style="width:500px;border:1px solid #ccc;"></div>
<!-- Progress information -->
<div id="information" style="width"></div>
<?php
if(isset($_REQUEST["NEXTVALUE"])){
$nextValue = $_REQUEST["NEXTVALUE"];
} else {
$nextValue = 1;
}
$refreshValue = $nextValue + 20;
$displaycounter = $nextValue;
$timeRemaining = 0;
$updatedRecords = 0;
foreach ($jfile as $key => $jsons) {
$newKey = $key;
if($oldValue != $newKey){
if($newKey >= $nextValue && $newKey < $refreshValue){
// echo "Updated: " . [$oldValue]['EPID'] . "<br/>";
// echo "<hr>" . $nextValue . " >= " . $newKey . " < " . $refreshValue;
print_r($epSync[$oldValue]);
$displaycounter = $newKey;
echo sync_systems($epSync[$oldValue]);
usleep(30000);
flush();
} else {
if($key == ($refreshValue)){
$theURL = "sf-ep-sync.php?NEXTVALUE=" . $refreshValue . "&RAND=" . rand();
// echo "<hr>" . $newKey . " = " . $refreshValue . " " . $theURL ."<br/>";
echo "<script>location.href = '" . $theURL . "';</script>";
exit;
}
}
$oldValue = $newKey;
$i = $nextValue + 1;
if(($i + 1) == $total ){
$percent = intval($i/$total * 100)."%";
$timeRemaining = 0;
} else {
$percent = intval($i/$total * 100)."%";
$timeRemaining = (($total - $displaycounter)/60);
}
usleep(30000);
echo '<script language="javascript">
document.getElementById("progress").innerHTML="<div style=\"width:'.$percent.';background-color:#ddd;\"> </div>";
document.getElementById("information").innerHTML="'.$displaycounter.' row(s) of '. $total . ' processed. About ' . round($timeRemaining, 2) . ' minutes remaining.";
</script>';
// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
}
foreach($jsons as $key => $value) {
$epSync[$newKey][$key] = $value;
}
}
Thanks,
Jason

Ajax rejecting JSON created by PHP with "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"

I have a page that makes an Ajax call, which retrieves, JSON encodes and returns data from a database. The page was working, but in the midst of making some changes, it's now failing. (Should note that I'm working with a test site and test database as I make the changes.)
The errorThrown parameter of the error case shows me "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data."
Here's the function with the Ajax call. (I've enhanced what's in the alerts for debugging purposes. I'll rip that back out once things are working.)
function acceptConfCode(){
var emailAddr = $('#email').val();
var confCode = $('#confcode').val();
var fnargs = "ConfirmCode|'" + emailAddr + "'," + confCode ;
$.ajax({
url: 'retrievedata.php',
type: "POST",
async: true,
data: {"functionname":"confirmcode","arguments":fnargs},
dataType: "JSON",
success: function (obj) {
if (!obj.error) {
$('#logininfo').hide();
$('#emailrow').hide();
$('#coderow').hide();
$('#reviewactions').show();
updateListOfActions(obj);
}
else {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 1");
}
},
error: function(xhr, textStatus, errorThrown) {
success = false;
alert("The confirmation code you entered didn't match or has expired. Please try again. Type 2. textStatus = " + textStatus + "; errorThrown = " + errorThrown);
}
});
};
The retrievedata PHP page is mostly a CASE statement. The relevant case is this (again with added debugging code):
case 'confirmcode':
if ($argcount <2) {
$returnval = 'too few arguments';
}
else {
$returnval = confirmcode($argsarray[0], $argsarray[1]);
echo "Back from confirmcode\r\n";
var_dump($returnval);
}
break;
At the end of the page, it returns $returnval.
The key action is in the confirmcode function, which runs a MySQL SP to confirm that the user has a valid email and code, and then calls another function to retrieve the actual data. Here's confirmcode. As the commented out pieces show, I've checked results along the way and I am getting what I expect and it's getting JSON encoded; I've ran the encoded JSON back through JSON_decode() in testing to confirm it was decodable.
function confirmcode($spname, $params, $errorstring = 'Unable to send requested data') {
$conn = connect2db();
$query = "SELECT ".$spname."(".$params.") as result";
//echo $query."\r\n";
$result = mysqli_query($conn, $query);
$allresult = "unknown";
if (!$result) {
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
//echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
//echo "In else case\r\n";
//retrieve list of action submissions
$resultobj = mysqli_fetch_object($result);
if ($resultobj->result == 1) {
//echo "In success subcase\r\n";
$allresult = getsubmissions($conn);
//echo "After getsubmissions\r\n";
//print_r($allresult);
}
else {
//echo "In failure subcase\r\n";
$result = array('error'=>true);
$allresult = $result;
}
//echo "Before JSON encode\r\n";
$finalresult = json_encode($allresult);
//echo "After JSON encode\r\n";
//echo json_last_error_msg()."\r\n";
//var_dump($finalresult);
$allresult = $finalresult;
return $allresult;
}
}
Finally, here's getsubmissions, again with some debugging code:
function getsubmissions($conn) {
echo "In getsubmissions\r\n";
$query = "CALL GetSubmissions()";
$submissions = mysqli_query($conn, $query);
if (!$submissions) {
echo "In failure case\r\n";
$errmessage = mysqli_error($conn);
$allresult = $errmessage;
$allresult = json_encode($allresult);
echo $errmessage;
die( print_r( mysql_error(), true));
}
else {
echo "In success case\r\n";
$rows = array();
while ($row = mysqli_fetch_assoc($submissions)) {
$rows[] = $row;
}
$allresult = $rows; //json_encode($rows);
}
//print_r( $allresult);
return $allresult;
}
What's really weird is I have another page in the site that retrieves almost exactly the same data through an Ajax call with no problem. The one that works contains a few additional fields, and doesn't contain two date fields that are in this result.
In addition, the live version of the site retrieves exactly the same data as here, except from the live database rather than the test database, and it works. While this version of the code has some additional things in it, the only differences in the relevant portions are the debugging items. (That is, I've made changes, but not in the part I'm showing here.) That leads me to think this may be an issue with the test data rather than with the code, but then why does the other page work in the test site?
UPDATE: To try to see whether this is a data problem, I cut the test data way down so that it's only returning a couple of records. I grabbed the generated JSON and ran it through JSONLint.COM and it says it's valid.
UPDATE 2: With the reduced data set, here's the string that's returned from retrievedata.php to the Ajax call:
[{"ActionSource":"https:\/\/www.voterheads.com\/","ActionSourceName":"Wall-of-us","Title":"Sign up to get notified about local meetings","Description":"Sign up at www.voterheads.com to get notified about local meetings. When we did, using the free option, this is what happened: a page popped up with a list of municipality meetings in the zip code we entered. We clicked on one of the meetings, and presto! -- instant access to the date, time, location, and agenda of the meeting. Pretty awesome.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"Ongoing","DurOrder":"6","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"20"},{"ActionSource":"https:\/\/actionnetwork.org\/forms\/ctrl-alt-right-delete-newsletter-2","ActionSourceName":"Ctrl Alt Right Delete","Title":"Sign up to learn what the \"alt-right\" is up to","Description":"Understand how the right operates online. Sign up for a weekly newsletter.","StartDate":null,"EndDate":null,"UrgencyDesc":"Anytime","UrgencyColor":"#00FF00","UrgOrder":"5","DurationDesc":"An hour or less","DurOrder":"2","CostDesc":"Free","CostOrder":"1","Issues":"Advocacy","Types":"Learn","States":"ALL","iID":"25"}]
As noted above, JSONLint.COM says it's valid JSON.
I've found a solution, though I'm just starting to understand why it works. On retrievedata.php, I uncommented:
echo $returnval;
just before the Return statement and it's working again. So I think the issue is that since retrievedata is a page, but not a function, the return statement didn't actually return anything. I needed code to actually return the JSON-encoded string.

Queries not working/ running on live server

Well at first you got to believe me on this: the queries I am using are all correct (tested it way to much and also everything works perfectly on the localhost). Lets start explaining my problem: I am running a small application (for fun and learning) and I do a lot of stuff with ajax requests, which works I can see it in the developer tools "sending, those requests go to a function.php file and should run. The code in the function file looks a bit like this:
if (isset($_POST['search'])) {
// Do stuff like running a query
}
All the requests go through the if statement but then all the following queries fail, while correctly writen. So I tried turning on showing erros on the live server but I can't seem to get it done (tried ini_set display errors, with htacces, and messed alot around in the server settings), so I can't see any errors only that the query fails because of this piece of code:
if ($query = mysqli_query($conn, "sql query bla bla")) {
// Dp stuff
} else {
// return error Message
echo "<p style='color:red;'>Something went wrong, please try again!</p>";
}
I get somehting went wrong all the time?
For orientation:
I have a folder, called functions, with multiple function.php files in it all connecting to the database indivitualy, maybe this has something to do with it?
This problem doesn't occurre on only one file but all the function.php files don't work. while If I put php code on origin file itself everything works fine
Hope someone can help me with this, I am out of suggestions
PS my English is not that great hope you will understand! if not let me know or if you need more information also let me know!
Edit
<?php
include_once'/../includes/dbconfig.php';
// If something is posted
if (isset($_POST['search'])) {
$word = stripVariables($_POST['search']);
$querySearch = "SELECT name, description, group_id FROM groups WHERE name LIKE '%$word%'";
$resultSearch = mysqli_query($conn, $querySearch);
$numberSearch = mysqli_num_rows($resultSearch);
// If something is found
if ($numberSearch >= 1) {
$end_result = '';
// Fetch search values, create search results
foreach ($resultSearch as $row) {
global $word;
// Get group values
$name = $row['name'];
$description = substr($row['description'], 0, 40);
$groupId = $row['group_id'];
// Make typed in word bold
$bold = '<b>' . $word .'</b>';
$fullWord = str_ireplace($word, $bold, $name);
// Create list items for each search result
$end_result .= "<li class='search-item'><div class='list-text'>" . $fullWord . "<br><b style='font-size:10pt; font-weight:normal'><span id='group_id'>" . $groupId . "</span> , " . $description ."...</b></div><div class='list-join'><div id='send_request'><p>Send Request</p></div><div><p>Cancel</p></div></div></li>";
}
echo $end_result;
} else {
// Nothing found five error
echo "<li style='color:red; padding: 10px; border: none;'>No results found!</li>";
}
}
// Prevent injections
function stripVariables($input){
$var = trim($input);
$var = strip_tags($var);
$var = stripslashes($var);
$var = htmlspecialchars($var);
return $var;
}
?>
And I use this method with ajax/ javascript
$(".join-inner input[name='submit']").click(function(){
// Get value user input
var inputSearch = $(".join-inner input[type='text']").val();
// Setup datastring
var dataString = "search=" + inputSearch;
// If inputSearch is not empty
if (inputSearch) {
// Ajax call
$.ajax({
type: "POST",
url: "functions/searchGroup.php",
data: dataString,
cache: false,
beforeSend: function(html) {
$('.results').html("");
},
success: function(html){
$('.results').html(html);
}
});
} else {
$('.results').html("<li style='color:red'>Type something to search</li>")
}
return false;
});
Are you sure that $conn is valid ?
$conn = mysqli_connect("localhost", "my_user", "my_password", "my_db");
/* check connection */
if (mysqli_connect_errno()) {
echo("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Then your code:
if ($query = mysqli_query($conn, "sql query bla bla")) {
// Dp stuff
} else {
// return error Message
echo "<p style='color:red;'>Something went wrong, please try again!</p>";
}

PHP script to pull from Facebook events from multiple pages

Bonjour everyone,
Currently, the script below is on my server as a PHP page (pull.php). It reads the events from a Facebook page using its ID, e.g: 12345678, and outputs them to a file, e.g: 1234568.ics.
What I'd like to ask this community for help with:
1) how would one modify the code below to read from many Facebook pages (an array where I would put in the page ID manually, e.g: 12345678, 24681357, 12348765) and output to many files 12345678.ics, 24682357.ics, 12348765.ics
2) I'm looking for these .ics files to be created and updated (crushed) right on my server, at the same location as where the script runs. The idea is that I'll run a CRON job that would run this script nightly. I then have a plugin on my Facebook page that updates events on the website based on the .ics feed.
CODE:
$access_token = MY_ACCESS_TOKEN;
$page = "12345678";
// We don't want to query the Facebook Graph API over and over, so we'll cache our results. You can force the cache to update by visiting the script and appending "?f=true", otherwise it will only run (rather than display the cache) if the cache is older than 3600 seconds (one hour).
$cache = $page . ".cache";
$f = false;
if($_GET['f'] == "true"){
$f = true;
}
if(!file_exists($cache) || filemtime($cache) <= time()-3600 || $f){
// Get and decode the data - your page's event list - from the API
$graph_url = "https://graph.facebook.com/" . $page . "/events?access_token=" . $access_token;
$data = file_get_contents($graph_url);
$data = json_decode($data);
if(!empty($data->error)){
echo '<b>$data error</b><br />';
echo $data->error->type . " error (" . $data->error->code . "/" . $data->error->error_subcode . "): " . $data->error->message;
exit;
}
// Go through the list of events, and get and decode more detailed information on each event.
foreach ($data->data as $event){
$event_data = file_get_contents("https://graph.facebook.com/" . $event->id . "?access_token=" . $access_token);
$event_data = json_decode($event_data);
if(!empty($event_data->error)){
echo '<b>$event_data error</b><br />';
echo $event_data->error->type . " error (" . $event_data->error->code . "/" . $event_data->error->error_subcode . "): " . $event_data->error->message;
exit;
}
// Store it in an array for later use.
$events[] = $event_data;
}
// We're now done fetching the data from Facebook's Graph API. Now we'll have to create an iCal file.
// This requires the iCalcreator PHP class, which you can downloead from kigkonsult at kigkonsult.se/iCalcreator/index.php
require_once("icalcreator/iCalcreator.class.php");
// Create the calendar, set up some basic properties
$c = new vcalendar(array('unique_id' => $page));
$c->setProperty('X-WR-CALNAME', $page . ' events');
$c->setProperty('X-WR-CALDESC', 'Facebook events for ' . $page);
$c->setProperty('X-WR-TIMEZONE', $events[0]->timezone); // We assume all of the events use the same timezone.
// Loop through the events, create event components in the calendar
foreach($events as $key => $event){
$e[$key] = & $c->newComponent('vevent');
$e[$key]->setProperty('summary', $event->name);
$e[$key]->setProperty('dtstart', $event->start_time);
$e[$key]->setProperty('dtend', $event->end_time);
if (!isset($event->end_time)) {
$e[$key]->setProperty('dtend', $event->start_time);
}
$e[$key]->setProperty('description', $event->description . "\n\nhttp://www.facebook.com/events/" . $event->id);
$e[$key]->setProperty('location', $event->location);
}
// Remove the cache if it exists
if(file_exists($cache)){
unlink($cache);
}
// Open (create) the cache file
if(!$handle = fopen($cache, 'w')){
echo "Cannot open output file: " . $cache;
exit;
}
// Write the calendar to the cache
if(fwrite($handle, $c->createCalendar()) === FALSE){
echo "Cannot write to output file: " . $cache;
exit;
}
// Close the cache file
fclose($handle);
}
// Now we've got the calendar in the cache file, either newly generated and stored there just a few lines ago or from earlier. Now we'll just display it.
header("Content-Type: text/calendar; charset=UTF-8");
header("Content-Disposition: filename=" . $page . ".ics");
require($cache);
?>
Might anyone have a clue how to do this?
Thanks in advance! Upvotes your way if you can help me out!
You can use a FQL query to get results for multiple pages at once, like this:
select eid, creator, name, description, start_time, end_time, timezone, location from event where creator in ({PAGE1_ID}, {PAGE2_ID}, ...) and start_time > now() order by creator asc
You can issue the (URL encoded) query via the
GET /fql?q=...
endpoint like this (replace Page IDs!):
http://graph.facebook.com/fql?q=select%20eid%2C%20creator%2C%20name%2C%20description%2C%20start_time%2C%20end_time%2C%20timezone%2C%20location%20from%20event%20where%20creator%20in%20(1234,5678)%20and%20start_time%20%3E%20now()%20order%20by%20creator%20asc
But then you have to restructure your code a little bit, because the result will look like the following:
{
"data": [
{
"eid": 2289962603,
"creator": 1146614804,
"name": "eventname",
"description": "descr",
"start_time": "2014-05-30T21:00:00+0200",
"end_time": null,
"timezone": "Europe/Berlin",
"location": "thelocation"
},
...
]
}
You then have to react on changes of the value for the creator field, which then indicated that there's a new calendar to be created (creator = page_id)

AJAX XMLHttpRequest 'bouncing back' when sending vars to PHP

I apologize if I don't articulate my problem correctly, but I'll give it my best shot. I've been looking all over the net for info which can help me with this issue, to no avail.
Just a bit of background. I'm an experienced web coder, though haven't done webwork in a few years prior to this, I have done a fair bit of work in PHP and javascript before and these days I work with C++, so I'm fairly experienced with programming principles.
I'm building some blog software, and inb4wordpress and jQuery, I simply don't care. So spare it please... I'm loading some blog entries into an element through a simple AJAX request function. This function is detailed below: ( It's been changed to a 3 function example I found on the net while I was trying to debug this issue, no one's 'simple' code seems to work. )
The problem is detailed beneath the code.
var httpObject = null;
function getHTTPObject(){
if(window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if(window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function setOutput(){
if(httpObject.readyState == 4){
document.getElementById("entries").innerHTML = httpObject.responseText;
}
}
function loadEntries(s) {
httpObject = getHTTPObject();
if (httpObject != null) {
httpObject.open("GET","entries.php?" + s,true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
Simple stuff? I can't seem to see any errors there. This is how the function is called:
<div id='entries'>
<script type="text/javascript">
loadEntries('blog=<?php echo $process['id']; ?>&page=0');
</script>
</div>
also simple.
Here's the PHP code for 'entries.php':
<?php
require_once('inc/bloginc.php');
if(isset($_GET['page'])) {
$page = intval($_GET['page']);
} else $page = 0;
$entries = 3;
$init = $page * $entries;
$limit = $entries + $init;
if(!isset($_GET['blog'])) die("WTF DIE");
else $blog = mysql_real_escape_string($_GET['blog']);
$tag = '';
if(isset($_GET['tag'])) {
$tag = mysql_real_escape_string($_GET['tag']);
echo "<span class='blogEntryBody'>viewing entries tagged with: '" . $tag . "' / <a href='' onclick=\"";
echo "loadEntries('blog=" . $blog . "')";
echo "\">clear?</a></span></br>";
echo "<hr>";
}
$numposts = nResults($blog, $tag);
buildEntries(getEntries($blog, $tag, $init, $limit));
if($numposts > $entries) {
echo "</br><span class='blogEntryBody'>";
if($page > 0) {
echo "<a href='' onClick=\"";
echo "loadEntries('blog=" . $blog;
if(isset($_GET['tag'])) echo "&tag=" . $tag;
echo "&page=" . (--$page) . "')";
echo "\">Previous Entries</a>";
echo " / ";
}
echo "<a href='' onClick=\"";
echo "loadEntries('blog=" . $blog;
if(isset($_GET['tag'])) echo "&tag=" . $tag;
echo "&page=" . (++$page) . "')";
echo "\">Next Entries</a>";
echo "<br></span>";
}
?>
okay, now here's where things get tricky:
When sending vars to 'entries.php', such as: entries.php?blog=walk&page=1
They intermittently work, some of these work, but some don't.
I know it's not the PHP code, since loading entries.php up in a new window and manually passing these vars elicits the desired results. What happens is that the HTTP GET request returns 'undefined' in Firefox webdev console, such as this:
[14:47:33.505] GET http://localhost/meg/entries.php?blog=walk&tag=lorem [undefined 2ms]
^ The 'tag' variable usually works, it's normally the 'page' variable that sends everything haywire.
What happens is, after clicking 'next page', you quickly see a blank div, and then it quickly bounces back to the previous state. You see all this loading in the console. It'll return 'undefined' then reload the previous state. Which is just puzzling.
I don't understand why this would be occurring.
I hope I've provided enough information, and set it out in an easy to understand format. I'm new to asking questions. I usually just 'googleit' or RTM. But I think maybe this time someone else will have seen this before.
Oh, and I've tested in chrome, same issue. I'm really puzzled, but open to the possibility that maybe I've overlooked something small and crucial.
Thanks!
Well it happens few times that ajax doesn't works in chrome & explorer so my suggestion to use jquery because in jquery they already include codes for explorer and chrome.
you can use
$.get , $.post or $.ajax methods easily.

Categories