Run a ajax function to check a json response every 3 seconds - javascript

I want to check if my user is updated from another system using javascript.
I need help writing a function which checks a json response. If it is true or false.
The url /user/updatecheck/ has a json response like this: {"updated": "true"} or {"updated": "false"}
<script type="text/javascript">
$(document).ready(function() {
var updated='2013-01-02T10:30:00.000123+02:00'; //user variable from the system, will be empty if the user is not updated
if (!updated){
$('#not-updated').modal('show');
var updatedCheck = window.setInterval(
$.ajax({
url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"}
data: dataString,
dataType: "json",
success: function(data){
if (json.updated == 'true') { //not sure if this is the correct method
window.clearInterval(updatedCheck);
//The user is updated - the page needs a reload
}
} //success
})
, 3000); //Hoping this is the function to check the url every 3 seconds until it returns true
}
});
$(document).ajaxStop(function(){
window.location.reload();
});
</script>
It does not seem to work. Not sure if my ajax function is correct, I only get the modal window if the user is not updated at first, and the page does not reload if the url /user/updatecheck/ returns true.

The way you call jQuery ajax function as part of the setInterval is not proper. Please try placing it within a function,
var updatedCheck = window.setInterval(
function(){$.ajax({
url: "/user/updatecheck/", //Returns {"updated": "true"} or {"updated": "false"}
data: dataString,
dataType: "json",
success: function(data){
if (json.updated == 'true') { //not sure if this is the correct method
window.clearInterval(updatedCheck);
//The user is updated - the page needs a reload
}
} //success
})}
, 3000);
The data that you will receive from the ajax request is returned via the data parameter of you success callback function, so you can use that. Try to print the data result to the console (i.e. console.log(data);)or alert it (i.e. alert(data);). For instance you may need to call data.updated. I'm not sure if the json variable you are using in the if condition is initialised.

Related

javascript not show results on success

I have this JavaScript code:
<script type="text/javascript">
$(document).ready(function() {
$(".deleteImage").on('click', function() {
var idmess = $(this).data("id");
var token = $(this).data("token");
$.ajax({
url: '{{ url('admin/deletemulti') }}/'+encodeURI(idmess),
type: 'DELETE',
dataType: "JSON",
data: {
"id": idmess,
"_method": 'DELETE',
"_token": token,
},
success:function() {
alert("it Work");
}
});
});
});
</script>
is working just fine (data is removing from my DB and I get 200 in network), except I cannot get my alert any idea why is that?
UPDATE
my network
my network response
Delete Function
function destroy(Request $request) {
$image = Image::find($request->id);
Storage::delete($image->name);
$image->delete();
}
try passing an argument in your success function.
success:function(data) {
alert("it Work");
}
You have used ajax with dataType : json
So you need to respond with a valid JSON as HttpResponse else it gets into a error event.
The response of your api call:
{{ url('admin/deletemulti') }}/'+encodeURI(idmess)
should be a valid JSON. Please check api response value and fix it, or share it so that we can help you update that.
In case the response is not a valid JSON, success function will never get triggered and hence alert is not getting executed.
More info :
Ajax request returns 200 OK, but an error event is fired instead of success
When I'm making backend for myown use, and when I'm writing json, I usually put my json on success like session = true, or something like that, so later you can check like :
success: function(json) {
if(json.session == true) {
alert('something')
}
}
Maybe it's not the best solution, but it's working perfectly for me.

Reload variables every 10 seconds

Okay here's the problem.
I want to have 6 realtime variables in php (now they are like Divs). The method I use works fine but it's awful (I know). I need better solution.
Now I load 6 diffrent files like this:
<script>
function loadText() {
$.ajax({
url: ("variable1.php"),
cache: false,
success: function(data) {
$("#variable1").html(data);
}
});
} setInterval(loadText, 60000);
</script>
<div id="variable1"></div>
What should I do? Thanks.
Are you going to want to do a setInterval()?
setInterval(function(){loadText();}, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:
function loadText(){
var text = $.ajax({
type: "POST",
url: "variable1.php",
async: false
}).success(function(){
setTimeout(function(){loadText();}, 10000);
}).responseText;
$('#variable1').html(text);
}
Or use .ajax().complete() if you want it to run regardless of result:
function loadText(){
var text = $.ajax({
type: "POST",
url: "variable1.php",
async: false
}).complete(function(){
setTimeout(function(){loadText();}, 10000);
}).responseText;
$('#variable1').html(text);
}
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
http://jsfiddle.net/YXMPn/
You can always have a function you set to run however often you want that has this... It's a much shorter way... If this is what you mean...
$("#variable1").load("variable1.php");

pass paremeter through .load from previous ajax call

Tearing my hair out on this one.... sure it just the structure of my function.
Basically I make a Ajax call within an Ajax loaded tab. The call made within writes a record to the Database and returns a value. I can alert the value fine but when I try to use it as a data parameter in my .load() call it doesn't get passed?
As they are in the same success function I just thought (Stupidly?) that I could easily reference it!
$('#convert-2-booking').click(function(e) {
var quoteid = $(this).attr("title");
$.ajax({
type: "POST",
url: 'tabs/convert-2-booking.asp?Planner_ID='+$('#convert-2-booking').attr("title")+'',
data: quoteid,
cache: false,
dataType: "html",
success: function(responseText){
var ajax_load = "<img class='loading' src='images/load.gif' alt='loading...' />";
var loadUrl = "tabs/booking.asp";
bookingid = responseText;
//above gets correct returned id.
$("#bookingtab").html(ajax_load).load(loadUrl, { 'bookingid': bookingid } ); // not here though :(
alert(bookingid) // alerts the correct id here too!
setTimeout(function() {
     
// move to bookings tab after 3 seconds
$("#tabs").tabs( "option", "active", 3 );
// load correct record into tab
}, 3000);
},
error: function(responseText){
alert("NOT:"+responseText);
//alert(responseText);
$("#tabs").tabs( "option", "active", 2 ); //load previous tab itself if returns error..
},
});
});
Try passing it via "booking.asp?bookingid=..."
Like this:
.load(loadUrl+"?bookingid="+bookingid)
It's a workaround tho; I'm not sure why load() doesn't do the same thing thru your array... Maybe it's because you only check GET variables on server side and load() gives you POST...?
ended up deciding to store the id in a session for the few seconds i need it. Not ideal, but a workaround for now, and enough to allow me to demo to my client.

Browser cache issue in IE

I have this JavaScript code:
$('#selectionoptions').change(function() {
var courseId = $(this).val();
$.get('../php/lecturer_getcourse_info.php',
{ course_id: $(this).val() },
function(courseData) {
var description = courseData.description;
$("#coursecontent").html(description);
...
Assume I can also modify 'description' and save it back to the db. Now, on Firefox every time I refresh the page I see the correct description; but on IE I have to clear the cache before I see the correct description....
How can I fix this?
The reason being in IE you have to false the Ajax Calls not to cache.
Use this:
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
or use a completely different ajax call rather than $.get such as:
$.ajax({
url: "test.html",
success: function(data){
alert('data returned!');
},
cache: false
});

How to bring ajax search onkeyup with jquery

My Script to call ajax
<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>
HTML
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.
For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.
When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.
Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.
I believe I had explained up to reader knowledge.
You should check if the value has changed over time:
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
EDIT:
The searchRequest variable was added to prevent multiple unnecessary requests to the server.
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort(). That should kill the previous ajax request and let you do the new one.
var req = null;
function search_func(value)
{
if (req != null) req.abort();
req = $.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
Try using the jQuery UI autocomplete. Saves you from many low-level coding.
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .
Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?
$(function(){
// Document is ready
$("#sample_search").keyup(function()
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg)
{
//Receiving the result of search here
}
});
});
});
I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.

Categories