I am using a javascript function to generate a random string:
function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
/*$.ajax({
type: "GET",
url: "uuid.php",
cache: false,
success: function(html){
return html;
}
});*/
return (S4()+S4()+S4()+S4());
}
And I want to make it utilize a php uuid library that I've found, the problem is I need it to run in javascript. I use the guid() function a lot and I've been trying to think of an elegant way of grabbing the uuid, that I request using the ajax object (commented out above). The uuid page that just prints random uuids each time is sitting locally next to this page. I would not like to make the request synchronous because, like I said, I use it quite a bit and would prefer to not have everything halt every time this thing makes a request. Or perhaps there's a method I could use of jQuery that be as fast and not hinder performance?
I'm not adverse to changing things up a bit, like would the best practice here to acquire a uuid on load? But the number of UUIDs I generate is completely dynamic, and dependent upon the user.
Thank you!
Check the uniqid() function from phpjs.org.
How about adding a callback argument to the guid() function, wherein you can assign a value to something:
function guid(callback) {
$.ajax({
type: "GET",
url: "uuid.php",
cache: false,
success: function(html){
callback(html);
}
});
}
var value;
guid(function (result) {
value = result;
});
Related
I have a page that has to run an ajax command a few times. It has to use the results of the previous ajax call in for the current one.
in laymen's terms:
call ajax, build entity on remote server, return result (i get a proprietary id as result)
...
call ajax, use result to post additional data to remote server, get id of this post
...
call ajax, post ids..etc
my first idea was async:false, but i see this is widely unacceptable and it ruins code execution order. My goal too, is to have a dialog window that prints the results of the ajax calls as they happen. Currently, the dialog window appears once all ajax calls are done. I don't get the pretty little: Build....done then additional Options.....done and so on...
if i make asynch:true, i wont have the id's need to process the next ajax..
what other options do i have have?
//form var is set earlier, standard serialized form.
var functions = ['build','additionalOptions','completion'];
$('#submitButton').click(function(){
$('#createGroupDialog').dialog({
autoOpen:false,
width: 1200,
height:800,
modal: true,
position: {my: "top", at: "top"},
resizable: false,
closeOnEscape: true
});
$("#createGroupDialog").dialog('open').html("<p>Please Wait...</p>");
function fireAjax(form,func)
{
$.ajax({
type: "POST",
url: "createGroup/createGroupDo.php",
data: form+"&func="+func,
asynch: false,
success: function (result) {
$('#createGroupDialog').append(result);
}
});
}
jQuery.each(functions , function(i,func){
fireAjax(form,func);
});
});
asynch:false is indeed a terrible way to deal with asynchronous data. It doesn't mess with the execution order but it blocks until the request finishes meaning no other JavaScript can run in the mean time, this includes things like onclick handlers and animations.
Since your requests rely on a previous request you have to write them like that:
$.ajax({
url: "request1.php",
data: data,
success: function (result_1) {
$.ajax({
url: "request2.php",
data: result_1,
success: function (result_2) {
$.ajax({
url: "request3.php",
data: result_2,
success: function () {}
});
});
});
}
});
But as you can see this gets tedious. You can use callbacks, but it's better use the Promise API.
Use like:
$.ajax({
url: "request1.php",
data: data
}).then(function (result_1) {
alert(result_1);
return $.ajax({
url: "request2.php",
data: result_1,
});
}).then(function (result_2) {
alert(result_2);
return $.ajax({
url: "request3.php",
data: result_2
});
}).then(function (result_3) {
alert(result_3);
});
It's worth noting that jQuery does a lot of work under the hood to make this API possible. $.ajax is a very flexible function. This means you can use it in many ways. It's best to chose one way and to stick with it. The current state of art really leans towards Promises.
Im trying to save this string:
~`##$%^&*()_+}{":?><,./;'[]=-|\
using a AJAX call in php. But in the database it saves as this:
~`##$%^????
this is my AJAX call
function saveComment(timesheetId,activityId,date,comment,employeeId) {
var r = $.ajax({
type: 'POST',
url: commentlink,
data: "timesheetId="+timesheetId+"&activityId="+activityId+"&date="+date+"&comment="+comment+"&employeeId="+employeeId,
async: false
}).responseText;
return r;
}
Edit: Fixed display of strings and code.
You need to in javascript call encodeURIComponent on the string with the weird characters before you send it to the server.
EDIT: Tomalak pointed out a better method.
If you want to put a variable 'text' in the data, you should run it through $.URLEncode(text) before doing so; as it is, the '&' character in the text introduces a new parameter.
jQuery supports an object as the data parameter in Ajax requests. This also does the URL encoding for you automatically:
$.ajax({
type: 'POST',
url: commentlink,
data: {
timesheetId: timesheetId,
activityId: activityId,
date: date,
comment: comment,
employeeId: employeeId
},
success: function (data) {
alert(data);
}
});
Also - you should never use synchronous Ajax requests. Always work with callback functions.
My ajax function has stopped working all of a sudden.
function get_file_info()
{
$.ajax({
type: "GET",
url: "http://localhost/includes/get_file_info.php",
dataType: "json",
jsonp: false,
jsonpCallback: "callbackName",
success: function(data) {
return data;
}
});
}
I did some debugging and found that the ajax request is going to
http://localhost/includes/get_file_info.php?_=1297356964250
I am just would like to know what it is and can be used for, also how to remove so the ajax request is like below so it works again.
http://localhost/includes/get_file_info.php
Many Thanks
If you add:
cache: true,
to your call it will remove the timestamp which is there to always call a different URL's so the browser doesn't cache the result. This is standard for calls except for datatypes script and jsonp.
As others have stated though, it would be good to change the server side to stop turning away anything with GET's, maybe check if the get is a _ and only numeric, if not then turn it away...
The "_=1297356964250" query string is jQuery's method of preventing the URL being cached and returning an old result. Adding this ensures that you're retrieving a new response every time.
This is not the cause of your request breaking down. It must be from another issue. Have you tried logging your response and seeing what it returns?
success: function(data) {
console.log(data);
}
I have a single page that I need to on occasion asynchronously check the server to see if the status of the page is current (basically, Live or Offline). You will see I have a function with a var live that is set when the page initially loads. I then do an ajax request to the server to retrieve whether the status of live is true or false. I compare the initial live variable with the newly returned data json object. If they're the same I do nothing, but if there different I apply some css classes. I recursively run it with setTimeout (Is there a better way to recursively do this?).
My Problem:
data.live doesn't change from it's initial time it runs even when it has changed in the db. I know my mysql is working because it returs the right value on the initial load. It seems like a caching issue.
Any help is greatly appreciated.
function checkLive() {
var live = <?=$result["live"]?>;
$.ajax({
type: 'get',
url: '/live/live.php',
dataType: 'json',
success: function(data) {
console.log('checking for updates... current:' + data.live);
if (data.live == live) {
return;
} else {
var elems = $('div.player_meta, object, h3.offline_message');
if (data.live == '1') {
elems.removeClass('offline').addClass('live');
} else {
elems.addClass('live').addClass('offline');
}
}
}
});
setTimeout(function() { checkLive() } ,15000);
}
checkLive();
Use the cache option of $.ajax() to append a cache breaker to the URL, like this:
$.ajax({
type: 'get',
url: '/live/live.php',
dataType: 'json',
cache: false,
//success, etc.
});
If that doesn't resolve it...look at firebug, see if a request is being made (it should be after this for sure), if it's still getting an old value, the issue is in PHP, not JavaScript.
Unrelated to the issue, just a side tip: If you need no parameters, you can skip the anonymous function call, this:
setTimeout(function() { checkLive() } ,15000);
can just be:
setTimeout(checkLive, 15000);
You can check if it's a caching issue by adding unique ID to the url:
change url: '/live/live.php', to url: '/live/live.php?'+new Date().getTime(),
Cheers
G.
I think Nick Craver has the right response.
For the other point of the question which is you SetTimeout , you could use SetInterval() and avoid the recursive call. But in fact I would stay with a setTimeout() and add a factor on the 15000 time. set that factor as a parameter of checklive. Then you will have a check which will be delayed progressively in time. This will avoid a LOT of HTTp requests from the guy which his still on your page since 48 hours.
Chances are that most of the time users will check for new pages in a regular manner, but someone staying for a very long time on a page is maybe not really there. Here's a piece of code I had doing that stuff.
function checkLive(settings) {
(...) //HERE ajax STUFF
setTimeout(function() {
if ( (settings.reload <2000000000) && (settings.growingfactor > 1) ) {
checkLive(settings);
settings = jQuery.extend(settings,{reload:parseInt(settings.reload*settings.growingfactor,10)});
}
},settings.reload);
}
So I can call a php page using jquery
$.ajax({ type: "GET",
url: "refresh_news_image.php",
data: "name=" + name,
success: function(html) {
alert(html)
$('div.imageHolder').html(html);
}
});
However this getting a bit messy, I have a few .php files that only really preform very simple tasks. If I want to call a method
$images->refresh_image();
is this possible. Failing that I could just create a big file with lots of functions in it?
Thanks,
Ross
Well, depends on what the intention is, of course, but if you really only want to run the refresh_image function, you don't need to pass any data, you don't have to handle success etc, then this isn't messy:
$.ajax({
url: "refresh_news_image.php",
});
You could also create a general function, such as:
function php_func(name){
$.ajax({
data: { name: name }
url: "background_functions.php",
});
}
And then background_functions.php:
switch($_GET['name']){
case 'refresh_image':
$images->refresh_image();
break;
case 'something else':
something_else();
break;
}
In javascript, whenever you need it (perhaps on an onclick) then you'd simply invoke:
php_func('refresh_images');
Be careful not to use the GET-parameter to run whatever function is passed, as that's obviously a huge security risk. :-)
You cannot call php functions directly from jQuery because jQuery knows nothing about php. You could create a file that based on a given request parameter calls the respective function and returns the result.