i want to fetch country source and destination from XML files , it works perfectly in localhost but not in server , in server it shows different destination country if i move cursor fastly on map.
in jquerymap.php I am calling price_by_countries.php file on mouseover and mouseclick event and I am also passing 2 variables in price_by_countries.php and in this file i am loading XML document , I think by loading XMLfile each and every time may cause this problem .. I am new to programming and wants to sort it out this issue asap .. thanks
jquerymap.php file code
jQuery.ajax({ type: "POST",
url: "price_by_countries.php",
data: "s="+source+"&d="+destination,
dataType: 'HTML',
success: function (msg) {
jQuery("#rightinput").html(msg);
}
});
price_by_countries file code
$xml = simplexml_load_file("rd.xml") or die("Error: Cannot create object");
function processXML($node){
foreach($node->children() as $books ){
if($books['source'] == trim(ucfirst($_REQUEST['s'])) &&
$books['destination'] == trim(ucfirst($_REQUEST['d'])))
{
echo "<pre>";
//echo $books ;
echo 'Source Country from XML file = '.$books['source'] . ' ------ Source Country from Textbox = '. trim(ucfirst($_REQUEST['s'])) ;
echo '<hr>';
echo 'Destination Country from XML file = '.$books['destination'] . ' ------ Destination Country from Textbox = '. trim(ucfirst($_REQUEST['d'])) ;
exit();
}
}
}
processXML($xml);
website url : http://realwebit.com/jquerymap/jquerymap.php
The problem seems to be bound to the datarequests on onmouseover. If you move the cursor too fast onmouseover triggers many requests at the same time to the server ! That works on localhost because there is no delay, but not ! You should install firebug for firefox and take a look at the requests made to the server.
If you dont want to load the xml every time you need a cache:
Save the response of the price_by_countries.php on the client side in an array using source & destination as keys !
If someone clicks or hovers over a country don't call the jquery ajax function right away. Check the array first if you already requested the data and return it ! If not do the ajax request. If it's successfull store the data in the array !
Lucian
Related
I want to load a view in another view using AJAX in CodeIgniter. I have written this code in the view.
<button class="btn btn-primary shadow" id='add_items'>Add Items</button>
<div class="row-fluid sortable shadow">
<div id="#show"></div>
</div>
$('#add_items').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "<?=base_url();?>Items/add_items",
type: 'get',
dataType: 'html',
success: function(output) {
$('#show').html(output);
}
});
});
This is the controller from which I want to load view inside the <div id="show">
public function add_items()
{
$this->show('admin/Items/index');
}
I think this example of my code with ur Object Oriented Programming skills can help u weel .
just create an xml file content a fiew of views u need, and tage everyone of them by an unic id .
this is a part of my xml file saved on the path :
{project folder}/src/CentralAppView.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<view id="adduser"><!-- choose ur id as libel of ur view must be unic -->
<!-- u can edit/insert everything u need here -->
<fieldset>
<form ...>
....... Content View ....
</form>
</fieldset>
</view>
</root>`
Now
1) u have to create an XMLHttpRequest instance called for example "xmlserver " be like :
var xmlserver = new XMLHttpRequest();
2) When u create this Object instance , u ll must to define for it the abstract methode called :
onreadystatechange
because u need to make a contol for every server state you get it , in this point , you need to check if u get the needed reponse for doing your traitment to your text response using tow XMLHttpRequest object attributes are changing values every server states changing :
xmlserver.status and xmlserver.readyState ( you can change 'xmlserver' by 'this' if you have something ambiguse about ) .
nice , now , u must to know which values can have there attributes and what is the best server state make you ready to do what you need by your server response .
lets begin by the attribue 'status' :
status is a integer attribute and have a values been got from the server juts to indicate the server response tag , there values may be enter an interval that accorded to your server behavior and fonctionality , for your using server , it may be 100 .. 600 , every value have an indicator .
we have a very knew value example :
404 request was not found on this server , so , 'request was not found on this server' is the indicator/meaning accorded to the value 404 of the attribute ' status ' .
200 is the indicator/meaning accorded to a succed access and response .
Now , lets move to the readyState attribute :
readyState is also an integer attribute , its just have the count of ur states got from ur server , his interval is fixed between 0..4 , 0,1,2,3 means an faild network access to ur server and the value 4 is accorded to the access connecting .
i think is also related to the server connection ping count .
Now , if u got 200 states value and 4 readystates , u ll able to do ur traitment and make ur view insert using ur server text response , because it s the only response format using for all servers ( propably) .
See the code and i think u ll understand more :
xmlserver.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
// do ur response traitment and ur view insert here
}
}
After that , u need to specify which file or which php page u need to load from it ur view contient just by using the XMLHttpRequest Object instance methode 'Open' with passing the following args :
ur sending mode : Get/POST , get is used to get data from , and post used to send text data as an argment of the send method that we ll talk about it later .
.
ur file / content path : in ur situation it must be {project folder}/src/CentralAppView.xml or the same path u used it .
Attention : wrong path can or server shutdown state can return the unwanted values that we tolk about it ago .
and
ur synchronisation level : true/false .
the code ll be :
xmlserver.open("GET", "./src/Containts_Dialogs.xml", true);
finaly in the Ajax part
call the method send to begin transaction between the server and ur browser for getting ur need view from ths server .
xmlserver.send(); // arg is undefined because we used the GET sending mode in the open methode
finaly with DOM to insert ur view in ur Div element
Using predefined XMLDocument Object instance , his getElementById() methode and innerHtml attribute .
getting the DOM element wich have the id 'show' from the XMLDocument
Object instance called document and affect it in a new variable
called for example viewelm.
Updating the view by the new Content ajax response .
Now , we just return to ower 'onreadystatechange' and insert this traitment in the comment that i make it for u , to get the code :
var xmlserver = new XMLHttpRequest();
xmlserver.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
document.getElementById("show").innerHtml = xmlserver.responseText;
}
}
xmlserver.open("GET", "./src/Containts_Dialogs.xml", true)
xmlserver.send();
Warrning : delete # from your html div id attribute element , to run the code correctly .
Good programing mate :) .
In the controller, You load the html string of the view page you want to load as :
$output = array(
'result' => $this->load->view('admin/Items/index','',true)
);
You send the output as the response to the ajax request :
print(json_encode($output));
You receive the response clientside like :
success: function(output) {
$('#show').html(output.result);
}
After the comment from #Danish, I realized the ajax expects the response to be HTML, in this implementation the server responds with json data.
To be able to use this solution, you need to change the response type of the ajax call to Json.
$('#add_items').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "<?=base_url();?>Items/add_items",
type: 'get',
dataType: 'JSON',
success: function(output) {
$('#show').html(output.result);
}
});
});
Hope This works.
I'm playing around with AJAX long-polling and trying to read/update a simple counter (number) value in an MySQL cell by clicking on a button.
The PHP creates an infinite while loop and is checking if the value in the according cell has been modified (MySQL "current_timestamp", UNIX). If it has and the current_timestamp value is bigger then the timestamp the AJAX call was made, it's breaking the loop and sending the updated value and the updated current_timestamp to the client. The AJAX processes the data.
The Problem: It works but after a while I get a 503 error. I guess it's obviously the while loop or other open connections through multiple windows in other browsers (for testing).
PHP-File text.php:
// Connect to database
$con = mysql_connect('XX', 'XX', 'XX');
if (!$con)
{
die('Error' . mysql_error());
}
mysql_select_db('X', $con);
// Get data
$query = mysqli_query("SELECT counter_value, last_modified FROM content WHERE X = 'X' ORDER BY X DESC");
// Start infinite loop
set_time_limit(0);
while (true)
{
// The timestamp of the last ajax call = the last modified timestamp
$last_ajax_call = $_GET['timestamp'];
clearstatcache();
// Get the value of the counter and the last modified timestamp
while($row = mysql_fetch_array($query))
{
$counter_value = $row['counter_value'];
$last_modified= strtotime($row['last_modified']);
}
// If the time of the last modified timestamp is bigger/later than the last ajax call
if ($last_modified > $last_ajax_call)
{
$result = array(
'counter_value' => $counter_value,
'timestamp' => $last_modified
);
$json = json_encode($result);
echo $json;
break;
// If not, try again in 3 seconds
} else
{
sleep(3);
continue;
}
}
// Close database
mysql_close($con);
AJAX Part in js-File:
function getContent()
{
// get timestamp of last modified stored in attribute. The initial/first timestamp attribute is set beforehand.
var timestamp = $('#timestamp').attr('data-timestamp');
$.ajax(
{
type: 'GET',
url: 'test.php',
async: true,
cache: false,
data: {timestamp:timestamp},
success: function(data){
var obj = jQuery.parseJSON(data);
$("#counter").text(obj.counter_value);
$("#timestamp").attr("data-timestamp", obj.timestamp);
getContent();
}
}
);
}
getContent();
So the result is a 503 error which goes away after ca. 10 Minutes and it's working again.
(Any typos/formatting might be the result of cleaning up the code.)
I just started learning PHP and JS, so there might be a few newbie mistakes or weird lines in there, please be nice. Any advice on optimising the code is very appreciated!
It dies because PHP doesn't work the way you think it does.
You have intentionally put an infinite loop into your php in the assumption it will make your code keep looping around and rechecking the next GET request on each loop.
The reality is that the code is executed once for each request, and until execution of the code completes the server doesn't respond.
AJAX long polling requires no special handling in php, it's just an AJAX request in a loop. You might want to include a slight delay in your AJAX code otherwise your server will be hammered with requests.
To be honest this isn't what long polling is for, the idea of it is to update pages without any user interaction to display unread message notifications etc.
If you want to monitor user events like button clicks then bind your AJAX function to the clicking of the button.
Complete rewrite of my question
The task I am trying to do is update the display of five variable without reloading the whole page.
I have a php file (check_conf_update.php) which runs a query that produces data and I am scripting it into JSON.
In the PHP file that runs the query I have at the end:
echo json_encode($record);
The JSON result looks like this:
[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]
I now need to use the data on a page called "template.php). How can I read the data from the Json result and assign each of the result elements in variables I can use on my "template.php" page. I need the Json script to run every x seconds so the display is always shows up todate information.
I have five php variables:
$CientName
$ImageName
$DisplayText
$FromTime
$ToTime
which I use on my web page to display the data on the same page as the script below.
$(document).ready(function() {
function runupdate() {
$.ajax({
url: 'check_conf_update.php',
type: 'GET',
data: 'record',
dataType: 'json',
success: function(data){
// not sure what I need to do here
}
});
};
// run it initially
runupdate();
// run it every 30 seconds
setInterval(runupdate, 30 * 1000);
});
Sorry if have confused anyone, and it looks like I did.
Can anyone help. Many thanks in advance for your time.
Regards
It's not really clear on what happens in your PHP script that produces the data. If you can update the post with the complete code for PHP also, it would be helpful. However, I'm assuming you want to use the data in the produced json string to populate the PHP variables in the destination file (check_conf_update.php)? In this case,
// check_conf_update.php
// $_POST['record'] == '[{"ClientName":"Another","RoomFromDateTime":"2016-02-25 01:00:00","RoomToDateTime":"2016-03-13 23:00:00","ClientImageName":"anothernew.png","DisplayText":"System Testing"}]'
$json = $_POST['record'];
$array = json_decode($json, true)[0];
$ClientName = $array['ClientName'];
$ImageName = $array['ClientImageName'];
$DisplayText = $array['DisplayText'];
$FromTime = $array['RoomFromDateTime'];
$ToTime = $array['RoomToDateTime'];
echo $ClientName . ', ' . $ImageName . ', ' . $DisplayText . ', ' . $FromTime . ', ' . $ToTime;
Edit:
All the PHP code in the template.php file is run on the server side before its rendered in the browser, so it will be too late to assign the updated json data into PHP variables by then. The only way to update information without reloading the page is to replace text or elements with javascript. After each successful ajax request, you can update the values in the page,
$('.clientname').html(data[0].ClientName);
$('.childbox').html(data[0].ClientImageName);
$('.clientndisplaytext').html(data[0].DisplayText);
$('.clientndisplaytime').html(data[0].RoomFromDateTime);
$('.clientndisplaytime').html(data[0].RoomToDateTime);
Ok so I'm experimenting with the in HTML5 and have made a simple "paint" application in Javascript to draw where the user's mouse is on the screen. Works fine.
I then wanted to save the coordinates to a file. My program already had an array of the x coordinates and an array of the y coordinates from the Javascript code.
When the user presses a button, the onClick calls a function in the Javascript, which using jQuery, as in the Top Answer here How to get JavaScript function data into a PHP variable attempts to pass this into a php file to save.
However it isn't working. Should I be passing the data back into the original php document that contains the canvas? If so how do I then get it to do the code to save as the PHP is run when the document is loaded no?
CODE:
Ok this is in the original php file which contains the HTMl for the webpage including the canvas. Here's the relevant save button:
<button type="button" onclick="saveDrawing()" id="saveButton">Save</button>
This calls the following in a separate JS file
function saveDrawing(){
// First check that not drawing and have data
if (!readyToDraw && clickX!=null){
// If ready then pass back to the PHP file the data
$url = 'file_save_test.php';
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()});
}
else {
alert("Please add some coordinate points and press Finish before saving");
}
}
and file_save_test.php contains only the following
<?php
// retrieve data from the JS
$buffer_data['x_coords'] = $_GET['x_coords'];
$buffer_data['y_coords'] = $_GET['y_coords'];
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
// first want to open a file
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'w');
// now to loop through arrays and write!
/*for ($i = 0; $i < sizeof($x_s); i++){
fwrite($file_handler, "$x_s[i], ");
fwrite($file_handler, "$y_s[i]\n");
} */
fclose($file_handler);
?>
In your PHP file it looks like your fwrite code is commented out. Are you expecting it to write to that data_test.txt file? Try changing your PHP file to print the results and have it echoed back to your javascript to see if the data is getting communicated properly.
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()},
function(data){
alert("Data Loaded: " + data);
});
PHP
print_r($_GET);
EDIT
Change your PHP file to something like this if it's alerting the data properly (it should append the coords to your file):
<?php
// retrieve data from the JS
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'a');
fwrite($file_handler, "$x_s, $y_s \n");
fclose($file_handler);
?>
EDIT 2
Update your for loop to your original code
for ($i = 0; $i < count($x_s); $i++){
fwrite($file_handler, $x_s[$i] . ", ". $y_s[$i] . "\n");
}
What I would do is have your save button call jQuery's $.post() method. Post the data to another PHP file that either inserts it into a database or saves it as a file. I don't recommend using the original document to post the data to because the client would have to download the entire DOM and the server would run any other code that you don't need.
That's as much as I can really help you without seeing any of your code.
I would send the data into a new php script called saveCoords.php or something..
You say you already have the coordinates in a JavaScript array, so it would look something like this...
//JAVASCRIPT FUNCTION which will request php file to store info
function storeCoords(xCoordArray, yCoordArray){
var xCoords = JSON.stringify(xCoordArray);
var yCoords = JSON.stringigy(yCoordArray);
var request = new XMLttpRequest(); //will need to change for older ie
request.onreadystatechange = function(){
//functions to handle returning information from php file..
}
request.open("GET","saveCoords.php?xCoords="+xCoords+"&yCoords="+yCoords, true);
request.send();
}
And then saveCoords.php file would look something like this:
<?php
$xCoords = json_decode($_GET['xCoords']);
$yCoords = json_decode($_GET['yCoords']);
//now you have a php array of xCoords and yCoords, which you can store
?>
Thats a skeleton but I think it hits on the major points, but comment with any questions.
I have an AJAX request that can have two possible outcomes:
The server responds with a message which I should place in a <div>
The server responds with an HTML page, in this case I need to substitute current page with a new one and change the address (the client knows the address before a request).
What would be the solution if I have the AJAX request that needs to handle both of these cases?
url = "http://example.com"
ajax.request(callback)
function callback(response) {
if (case2(response)) {
history.pushState({}, "New page", url);
document.innerHTML = response
} else {
updateDiv(response)
}
}
I'm interested in a correct way to implement the first branch, or if the server can somehow compose a headers that will make browser to handle a response as a usual HTTP response and update a page location and content, something like redirect with given content.
I understand that the server can return a link instead of a page, but in this case one additional stage will be needed on a client - redirect and then populating the new page on the server.
Quite frankly, I think that approach is basically broken by design. You shouldn't have to make that decision at that place. For example, the ajax response could only signal that a whole new page should be loaded and the new content then be generated on a second (non-ajax) request to a new URL.
In case you're forced to take the way you already go, and provided the response content is not very large, you could try Javascript-URIs. Basically, an URI in the form of javascript:"string" will load a new page which that string is the source code for. So, if response already is a string, just assigning javascript:response to window.location.href should suffice. Maybe you have to do some escaping beforehand. And I don't know, how cross-browser-compatible this approach is.
load
is also possible.
A variant of this is building the URL not with the variable name, but with the actual string data. Like
function source2url(src) {
// make valid javascript string from source text
var esc1 = src
.replace(/\\/g, '\\\\')
.replace(/\'/g, '\\\'')
.replace(/\x0A/g, '\\x0A')
.replace(/\x0D/g, '\\x0D');
// make valid url from that
return "javascript:'" + encodeURIComponent(esc1) + "'";
}
window.location.href = source2url(response);
This will, of course, generate pretty large URIs. And you'll always have the Javascript-URI in the address bar.
UPDATE
A similar approach is to use base64 encoding in a data URI. The Wikipedia entry explains how it works, including a javascript example. However, you'd have to base64-encode the content somehow. (Note: You can use data URIs with or without the base64 encoding. You have to see what gives you shorter URIs for your specific content.)
I had a similar issue once. A full error page was returned instead of a simple HTML snippet. We eventually fixed this by changing the logic, but here is one of the solutions I found:
document.open();
document.write(responseText);
document.close();
The reason we abandoned this is that on IE there were some problems. I didn't loose any time to investigate why, but it threw an 'Access denied' exception when attempting to write the string. I think there were some <meta> tags that confused IE, or maybe conditional comments, I'm not sure. (It worked when I used some simple pages...)
Bottom line is: you shouldn't have to do this, but if there is nothing else you can do (like returning an url string) the code above might work.
It's really easy if the response is valid XML.
var new_doc = (new DOMParser).parseFromString(response, "application/xml");
document.replaceChild(document.adoptNode(new_doc.doctype), document.doctype);
document.replaceChild(document.adoptNode(new_doc.documentElement), document.documentElement);
Since the request is for an updated answer, here's my solution using HTML5's History API with jQuery. It should run easily by combining the PHP and HTML parts into one file.
My solution allows for AJAX to return the following:
A message through AJAX, which updates a <div> container.
A URL, which causes the browser to redirect to the URL
A complete HTML page, which calls the History API's history.pushState() to add the current URL to the browser's history and replaces the entire HTML on the page with the HTML returned from AJAX.
PHP
This is just a sample of what the PHP script will need to return when it is invoked via AJAX. It shows how to encode flags to determine whether the AJAX call should update the container or load a new page, and how to return its result via JSON through json_encode. For completeness, I named this script test.php.
<?php
// Random messages to return
$messages = array(
'Stack Overflow',
'Error Message',
'Testing'
);
// If the page was requested via AJAX
if( isset( $_POST['ajax']))
{
$response = array(
'redirect' => // Flag to redirect
( rand() % 2 == 0) ? true : false,
'load_html' => // Flag to load HTML or do URL redirect
( rand() % 2 == 0) ? true : false,
'html' => // Returned HTML
'<html><head><title>AJAX Loaded Title</title></head><body>It works!</body></html>',
'title' => 'History API previous title',
'message' => // Random message
$messages[ (rand() % count( $messages)) ]
);
echo json_encode( $response);
exit;
}
JS
Since I am using jQuery, lets start with that. The following submits an AJAX POST to the server, to the above PHP script at URL test.php. Note that it also sets the POST parameter ajax to be true, enabling the PHP script to detect that it received an AJAX request. The dataType field tells jQuery that the server's response will be in JSON, and that it should decode that JSON to a JSON object in the response callback. Finally, the success callback, which is fired when the AJAX response is successfully received, determines what to do based on the flags sent from the server.
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
// Output the HTML
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
HTML
Here is the complete HTML source of my tested file. I tested it in FF4 - FF8. Note that jQuery provides the ready method to prevent the JS from executing until the DOM is loaded. I've also used Google's hosting of jQuery, so you do not need to upload a copy of jQuery to your server to test this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<title>Default Page</title>
<script type="text/javascript"">
$( document).ready( function() {
$('#ajax_link').click( function() {
var redirect_url = "/test.php";
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
})
});
</script>
</head>
<body>
<div id="message">The default contents of the message</div>
<a id="ajax_link" href="#">Fire AJAX</a>
</body>
</html>
Give an id to body <body id="page"> and your other div will be <div id="message"></div> now your ajax will look like
$.ajax({
url:'myAjax.php',
data:{datakey:datavalue},
dataType:"JSON",
success: function (response) {
if(response.message=="your message")
{
$('#message').html(response.content);
}
else
{
$('#page').html(response.content);
}
}
});
as T-Bull say... the whole process is wrong here....
you simply are over-complicating things and you know that infact:
I understand that the server can return a link instead of a page, but
in this case one additional stage will be needed on a client -
redirect and then populating the new page on the server.
stop complicating and start do it well...
Client open the page first time, so, track it $_SESSION['tmp_client_id'] = 'client_'.session_id(); obviously is better if the client is already subscribed, anyway, put stuff in temp table OR into another session var etc...
Client fill in the form;
Client submit the form;
Make the AJAX request;
Store $_POST variable inside tmp_client_tbl with it's unique tmp_client_id OR just $_SESSION['client_'.session_id()] = json_encode($_POST);
Outcome #1 ? display message in a </div>
Outcome #2 ? refresh page and check if( isset($_SESSION['client_'.session_id()])) { if so let's display the form again with filled fields: } else { display empty form;
SELECT * FROM tmp_client_tbl WHERE tmp_client_id = '{$_SESSION['tmp_client_id']}' OR json_decode($_SESSION['client_'.session_id()]);
$form_data = $mysql_rows; OR $json_array;
foreach($form_data as $name => $value) { echo "<input name='$name' value='$value' />" } in a ninja way that assume you have such kind of form builder array where $form = array('text' => array('name','lastname'), 'select' => array('countries'), ... ), OR simply by <input name='lastname' value='{$lastname}' /> where the fields values are pre-polutated with empty vars;
time elapsed, error occurred, browser closed? session_destroy(); or unset($_SESSION['client_'.session_id()]);