i am using the following code for pass and get data through ajax.
function passdata(id)
{
var top = document.getElementById("tname").value;
var first = document.getElementById("fname").value;
var font_top = document.getElementById("font_top").value;
var font_first = document.getElementById("font_first").value;
var image_top = document.getElementById("image_top").value;
var image_first = document.getElementById("image_first").value;
var poststr = "id=" + id +
"&top=" + top +
"&first=" + first +
"&font_top=" + font_top +
"&font_first=" + font_first +
"&image_top=" + image_top +
"&image_first=" + image_first +
"&actype=getevent";
var reqAddCart = new Subsys_JsHttpRequest_Js();
reqAddCart.onreadystatechange = function() {
if (reqAddCart.readyState == 4) {
if (reqAddCart.responseJS) {
document.location.href = reqAddCart.responseJS.ajax_redirect;
return;
}
else {
//alert(reqAddCart.responseText);
//showModal('abc');
document.getElementById('data_content').innerHTML = reqAddCart.responseText;
result = (reqAddCart.responseText||'');
var brokenresult=result.split("#");
}
}
}
var senddata = new Object();
var url = 'product.php?'+poststr;
//alert(url);
reqAddCart.caching = false;
reqAddCart.open( 'GET', url, true);
reqAddCart.send( senddata );
return false;
}
i am using the passdata function to pass the data in product page.this function works but i am getting response very slow.
The time taken for an AJAX request to complete is affected by network latency and connection speed on both the server and client, as well as execution time of the script on the server.
I would expect AJAX requests made locally when testing to return a lot faster as it removes the need for transmitting data over the internet.
Related
I have a PHP process which updates files, and writes a status report with each file.
While that is happening, I was hoping to update the user's browser until the final response.
Unless there is a better way, I simply wanted some advice on how to loop infinitely refreshing getJSON() results until the ajax response comes.
What is the best way to do this?
This ended up being the solution I used:
$(document).on('click', "#ss_batch_edit_processing", function (e) {
var ids = get_selected();
var status_location = '<?php echo symbiostock_TMPDIR . '/report.txt' ?>';
if(ids == 0){
return;
}
$('.' + loading_icon_small).show();
var data = {
action: 'ss_professional_ajax',
security: '<?php echo $ajax_nonce; ?>',
reprocessing_action: $('input:radio[name=ss_reprocessing_action]:checked').val(),
ids: ids,
};
var completed = 0;
$.post(ajaxurl, data, function (response) {
$('.' + loading_icon_small).hide();
completed = 1;
});
var get_update = function(){
$.getJSON(status_location, function (data) {
var update = '<ul><li><strong>'+data['title']+'</strong></li><li><strong>Count:</strong> '+data['count']+' / '+data['total']+'</li><li><strong>Last processed</strong>: Image # '+data['last_id']+'</li></ul>';
$('#ss-reprocessing-results').html(update).delay(1000);
});
if(completed == 1){
clearInterval(timed_requests)
return false;
}
};
var interval = 1000; // every 1 second
var timed_requests = setInterval(get_update, interval);
});
I'm using Code Igniter and the Googlemaps library. This library generates a lot of Javascript code dynamically, including the contents of the InfoWindows for each new marker, but I'd like to keep that in a separate template file, like a regular View.
I have this Javascript code (from Googlemaps' library):
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var windowContent = "";
if( _new ) {
var newIW = new google.maps.InfoWindow( { content: windowContent } );
What I want to do is to load windowContent from a template file. I have already succeeded in dynamically generating a form for this variable and using lat and long variables defined just above, but how can I achieve this in Code Igniter? I can't use load->view because I'm not in a Controller's context. And I cannot use include() or readfile() either because of CI's security constraints.
Any hints?
Using pure javascript, get the lat and long, make a url with the lat and long in the query string, and use xhr to do the ajax call.
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var xhr;
var url = "http://myurl.to/script.php?lat="+lat+"&lng="+long;
if(typeof XMLHttpRequest !== 'undefined')
xhr = new XMLHttpRequest();
else {
//Get IE XHR object
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"];
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
}
}
xhr.onreadystatechange = function(){
//This function is called every so often with status updates
//It is complete when status is 200 and readystate is 4
if(xhr.status == 200 && xhr.readyState === 4) {
//Returned data from the script is in xhr.responseText
var windowContent = xhr.responseText;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
};
xhr.open('GET', url, true);
xhr.send();
if using a library like jQuery it would be like
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var url = "http://myurl.to/script.php";
jQuery.ajax({
"url":url,
"data":{ //Get and Post data variables get put here
"lat":lat,
"lng":long
},
"dataType":"html", //The type of document you are getting, assuming html
//Could be json xml etc
"success":function(data) { //This is the callback when ajax is done and successful
//Returned data from the script is in data
var windowContent = data;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
});
I wrote a JavaScript function to convert GeoJson data to WKT format. It works when i get the input value in the javascript code directly. But I don't know how to get the input from the php and send it back.
Here is the php code:
<?php
$geojson=file_get_contents("clipfeature.geojson");
$WKT = $_POST['wkt'];
echo ($WKT);
?>
So it gets geojson data from a file and I want to receive the converted WKT code from the Javascript function.
Please help me finish the JavaScript Code:
function converttoWKT (){
$.ajax({
type: "GET",
url: "readJson.php",
contentType: "application/json"
}).done(function (data) {
var JSONObject = How to give the value from PHP to this Variable;
var coordinate = JSONObject.features[0].geometry.coordinates;
var type= JSONObject.features[0].geometry.type;
var coordinate1 = "";
var coordinate2 = "";
for (var i=0; i< coordinate[0].length; i++) {
coordinate1= coordinate[0][i][0]+" "+coordinate[0][i][1];
coordinate2=coordinate1+","+coordinate2;
}
var WKT= "\""+ type + "((" + coordinate2;
WKT=WKT.substring(0,WKT.length-1);
WKT=WKT+"))\""
sendback ( );
});
function sendback(){$.post("readJson.php",
{'wkt':How to send the value of var WKT back to php 'wkt'
});
}
Basically:
var jsVar= "<? echo $myVariable_value_goes_in_here; ?>";
or, as mentioned above:
var JSONObject = <? echo json_encode($WKT); ?>;
// this NEED TO BE json, otherwise syntax error in JS!
Since you already know your return data will be JSON, you can just use $.getJSON() for convenience. This is a $.get() request paired with JSON.parse(). With $.getJSON(), the JSON is parsed on response. To send the data back, just use use jQuery's $.post().
Here's an edited version of your code.
function converttoWKT() {
$.getJSON('clipfeature.geojson', function(data) {
var coordinate = data.features[0].geometry.coordinates;
var type = data.features[0].geometry.type;
var coordinate1 = '';
var coordinate2 = '';
for(var i = 0; i < coordinate[0].length; i++) {
coordinate1 = coordinate[0][i][0] + ' ' + coordinate[0][i][1];
coordinate2 = coordinate1 + ',' + coordinate2;
}
var WKT = '"' + type + '((' + coordinate2;
WKT = WKT.substring(0, WKT.length - 1);
WKT = WKT + '))"'
sendback(WKT);
});
};
function sendback(data) {
$.post('readJson.php', {
'wkt': data
});
};
I am using AJAX extensively and my PHP based notification system was not sufficient.
I have this function:
<script>
function user_notify($string, $class){
if($class == null){
$class = 'error';
}
$('<div class="' + $class + '"><div class="notification-text">' + $string + '</div></div>').hide().appendTo('#system-notifications').fadeIn('slow');
}
function DeleteTask(SpanName, TaskId){
if (confirm("Are you sure you want to delete this task?")) {
var curDateTime = new Date(); //For IE
var status = document.getElementById('status');
var poststr = "uniqueID=" + curDateTime.getTime() ;
var SpanName = SpanName;
if(SpanName == 'project_todos_complete'){
var showCompleted = 1;
} else {
var showCompleted = 0;
}
//alert (SpanName);
makePOSTRequest('http://*****webdesigns.com/project_manager/include/ajax/global.php?action=delete_task&showCompleted=' + showCompleted + '&id=' + TaskId, poststr, SpanName);
}
if(ajax_status == 4){
user_notify('Task deleted.', 'success');
ajax_status = null;
}
}
</script>
I have a global javascript variable that holds the readyState. If 4 is a response from the server, we can assume the AJAX was successful (I know, not neccessarily the cgi/php is execute if any). So I store that, and within the function that called the AJAX post, if the readyState is 4, I call the user_notify function.
It works beautifully with one exception: the first action that should trigger a notification does not. All consecutive actions successfully generate a message. It's not a specific action that doesn't work, just the first one.
The html:
<body>
<div id="system-notifications"></div>
<div class="wrapper">...</div>
What am I missing here?
UPDATE:
I am in the process of moving legacy javascript/Ajax calls to jQuery/Ajax. Everything works except one aspect: the targeted div does not 'refresh' with the return data from the .ajax jQuery call. The notification pops up (the first time and all consecutive times), the php executes (refreshing the page verfies this), but the div does not update with the html that the PHP script generates.
$('form#addToDoForm').submit(function(){
var project_id = $('#addToDoForm input[name=project_id]');
var assigned_id = $('#addToDoForm input[name=assigned_user_id]');
var description = $('#addToDoForm textarea[name=description]');
var responsible_id = $('#addToDoForm input[name=responsible_user_id :selected]');
alert(responsible_id.val());
return false;
var due = $('#addToDoForm input[name=due]');
var result_div = 'project_todos_' + project_id;
var query_string = 'action=add_to_do&id=' + project_id;
var ajax_url = 'http://avwebdesigns.com/basecamp/include/ajax/global.php?' + query_string;
var successMessage = '<b>' + description.val() + '</b> added.';
var data =
'project_id=' + project_id.val() +
'&assigned_user_id=' + assigned_id.val() +
'&responsible_user_id=' + responsible_id.val() +
'&description=' + encodeURIComponent(description.val()) +
'&due=' + encodeURIComponent(due.val()); // encodeURIComponent()
$.ajax({
type: 'POST',
url: ajax_url,
data: data,
cache: false,
success: function(data){
$('#'+result_div).html(data); // $('#'+result_div).html(data.returnValue);
user_notify(successMessage, 'success');
},
error:function(data){
$('#'+result_div).html(data);
user_notify(failureMessage, 'error');
}
});
return false;
});
Any ideas?
You are missing the non-blocking characteristics of an AJAX call probably. I can't really tell what makePOSTRequest does, but judging from your design I assume you expect it to be synchronous where it probably is not. Due to the asynchronous nature of an AJAX call, you need to pass a callback function to the call that is called when the AJAX request completes.
What probably happens in your case is that makePOSTRequest immediately returns and because the first request hasn't finished yet, ajax_status will not be 4 yet. Then, by the time the second request is sent, your first will have completed and your global variable will have been set to 4, so this time it works and this is also the cause why it works in all subsequent attempts.
This shows another flaw in your design: it's actually a very bad idea to capture the status of an AJAX request in a global variable. These requests are potentially sent in a concurrent fashion so you would have several requests that share one and the same variable - this calls for a 'race condition'. Have a look at the examples in the Ajax section of the jQuery documentation to see how to handle this correctly with the help of a callback function.
Can any one help me in recording time spent by the user in a particular page? I also need to send that data to a PHP file where it will need to be stored in a database.
This is what I have so far:
var time = 1;
function timeHere() {
time = time + 1;
finalTime = time / 10;
}
function sayTime() {
finalTime = time / 10;
sendTimeSpent(finalTime);
}
function sendTimeSpent(finalTime) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/Test/Timer/StoreTime.php?time=" + finalTime, true);
xmlhttp.send();
}
Here i dont need any response from the server...
I just need to send the data to the server...
I would use jQuery, but still I'm not fond on the idea.
var startTime = 0;
$(function() {
startTime = Date.now();
});
$(window).bind('beforeunload', function() {
$.ajax({async: false, // Necessary, because the closing code has
// to be suspended until the ajax succeeds
url: 'store.php',
data: {time: Date.now() - startTime},
success: function(text) {
// This is executed when the response has been received
// text is response data
}
});
});