JavaScript: Fetch URL from JSON File and execute it in background - javascript

I want to fetch JSON from URL using jQuery:
$.getJSON('http://example.com/file.php', function(data) {
//data
});
Example JSON: { "url":"http://example.com/execute.php" }
Then I want to execute the URL in background (client side and without telling to user) which we have got from JSON file.
And Repeat the whole process every second! Getting the JSON every second and executing in background and so on..

function callPhpFile() {
$.ajax({
file: "http://yoururl.com/executethis/script.php"
method: 'POST',
success: function(data) {
setTimeout(function() { callPhpFile() }, 1000);
}});
}
setTimeout(function() { callPhpFile() }, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Then I want to execute the URL in background (client side and without telling to user) which we have got from JSON file.
You don't need AJAX for a response, you can use it as a request as well. This will just run the PHP page every * times you call it. In the success listener you can do nothing, or implement a setInterval() to repeat the process
DOCS: http://api.jquery.com/jquery.ajax/

This is what i made for this solution, getting URL every second and executing it!
function getURL() {
var url = 'http://example.com/pending.php';
$.getJSON(url, function(result){
var executeL = result.url;
$.get(executeL);
});
}
$(document).ready(function(){
setInterval(getURL, 1000);
getURL();
});

Related

Problem using multiple jquery ajax request in a single page

Hello i am working on a PHP Project where i need to load some request using ajax request. Below are my request function.
Function One: When showNotify event is click i call the ajax request to get content and use ajaxStart to show spinner untill the content is fully ready!
//* First click load nofication
$(document).on('click', '#showNotify', function() {
let check = $(this).data('check');
if(check === 0) {
//* Process notification
$(this).attr('data-check', 1);
//* Load ajax request
$(document).ajaxStart(function() {
$('#notify-wait').show();
});
$(document).ajaxComplete(function() {
$('#notify-wait').hide();
$('#list-noti').show();
});
$.ajax({
url: '/list-dd-notifications',
method: 'GET',
success: function() {
$('#notif-unread').hide();
}
});
}
});
Function Two: i need to check from the server side to see if user has a new unready notify and show up the new notification sign.
function checkNewFotify() {
$.ajax({
url: '/check-notifications',
method: 'GET',
success: function(data) {
if(data) {
if($('#notif-unread').is(":hidden"))
{
$('#notif-unread').show();
}
}
else
{
if($('#notif-unread').is(":visible"))
{
$('#notif-unread').hide();
}
}
}
});
}
//* check for new notification
setInterval(() => {
checkNewFotify();
}, 5000);
Problem: Any time the showNotify is dropdown at first it show the spinner the loader until the request is fully loaded also if the function checkNewFotify is doing is job by refreshing every 5 secs to check the server for new notification the ajaxStart in showNotify will be affected by showing the spinner loader every time the checkNewFotify is refreshing in background.
Please how can i stop it from showing the spinner loader whil it refreshing every 5 seconds.
Set the global option to false on the ajax on checkNewFotify() this will prevent handlers like ajaxStart from firing.
$.ajax({
url: '/check-notifications',
method: 'GET',
global: false,
});

convert normal submit form to ajax real time

im new here so forgive me if my question seems to be stupid
i have the following code to search youtube video with submit button (normal form)
i want to turned to real time input once the user write any word will fetch result depend on what wrot by hime
so i add
$(".search_input").keyup(function(e) {
instead of
$("form").on("submit", function(e) {
full code is here https://jsfiddle.net/5ymndbax/
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
$(function() {
$(".search_input").keyup(function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: $("#search").val(),
order: "viewCount",
publishedAfter: "2000-01-01T00:00:00Z"
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("tpl/item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
});
});
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
});
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
function init() {
gapi.client.setApiKey("key");
gapi.client.load("youtube", "v3", function() {
// yt api is ready
});
}
i hope can i got some help from you ❤
full of love to each of you.
Currently you are using keyup, and that will check entry by letter.
So you need to check did key up ended with " ",",","." etc. for that will mostly mean the end of the word.
Now when we have the word, we want to add that to
previously entered words so you need to
concatenate or append new_word to previous_words.
And only then you should call AJAX call to URL or script that is using YouTube API for search...
It should go something like this:
**
event.preventDefault();
$.ajax({
type:"GET",
url: "youtube url or some script preforming to yt api call",
data:{"search": previous_words,},
success:function(data){
//display data somewhere
console.log(data);
}
});

Refreshing Captcha on Ajax call

I have the following code with which I used to refresh a captcha image via JavaScript. Is there anyway I can also achieve that using an AJAX request?
<script>
function refreshCaptcha() {
$("#captcha_code").attr('src','captcha_code.php');
}
</script>
<button name="submit" onClick="refreshCaptcha();">Refresh Captcha</button>
Yes it's possible, but then you need to handle session manually!
<script>
$(".RefreshCaptcha").click(function () {
$.post('captcha_code.php', function(data, status){
$("#captcha_code").attr('src', data);
console.log("ajax log: " + status);
});
});
</script>
<button class="RefreshCaptcha">Refresh Captcha</button>
w3shcools ajax.post
You can use the following code.
<script>
$(document).ready(function() {
setInterval(function() {
$.post('captcha_code.php', function(data) {
$('#captcha_code').html(data);
});
}, 1000);
});
</script>
Yes AJAX can be used to update the update the image via Javascript. Because the code already uses jQuery, a simple way would be to use $.post() to post to the PHP script. Presuming that captach_code.php merely returns the image source (e.g. base-64 encoded string), you can set the src attribute to the response value (e.g. in the function updateImage() below).
function refreshCaptcha() {
$.post('captcha_code.php', updateImage);
}
function updateImage(response) {
$("#captcha_code").attr('src',response);
}
See it in action in this phpfiddle. Note - there is no control of the filenames so PHP_SELF is used instead of captcha_code.php.
$.post() returns a jqXHR object, which implements the Promise interface. Because of this, .done() and other similar functions can be used instead of specifying the success callback:
function refreshCaptcha() {
$.post('captcha_code.php')
.done(function(response) {
$("#captcha_code").attr('src',response);
})
.fail(function() {
//fail handler...
})
.always(function() {
//handler for all cases
});
}
See it in action in this phpfiddle.

How to add preloader to website without manually show/hide it

On my website (MVC and web API) I have added a preloader for a better user experience purpose.
I have added the preloader at two points:
After Login, between the user is authenticated and the redirection to the homepage.
In every page that loads data from the server.
I did it with an image that I show when the page/data loads and I hide when the data is fully loaded.
<div id="dvReqSpinner" style="display: none;">
<br />
<center><img src="~/images/loading_spinner.gif" /></center>
<br />
</div>
And with jquery I show and hide it:
$("#dvReqSpinner").show();
$("#dvReqSpinner").hide();
It's a little bit anoying to keep showing and hiding an image every time I need to load data (using an AJAX call to web API, authenticating the user etc.. - Every action that takes time and I want to show the user that something is "happening"), isn't there any "automatic" option to have a preloader on a website?
I don't know if its the case, but if you use jquery ajax to handle your requests, you can do something like this:
$(document).ajaxStart(function() {
// every time a request starts
$("#dvReqSpinner").show();
}).ajaxStop(function() {
// every time a request ends
$("#dvReqSpinner").hide();
});
EDIT:
If you want to avoid showing the spinner for fast requests, i think this can make it work:
var delayms = 3000; // 3 seconds
var spinnerTimeOut = null;
$(document).ajaxStart(function() {
// for every request, wait for {delayms}, then show spinner
if(spinnerTimeOut!=null){
clearTimeout(spinnerTimeOut);
}
spinnerTimeOut = setTimeout(function(){
$("#dvReqSpinner").show();
}, delayms);
}).ajaxStop(function() {
// every time a request ends
clearTimeout(spinnerTimeOut); // cancel timeout execution
$("#dvReqSpinner").hide();
});
Give it a try. i couldn't test it -.-'
To show or hide a loading indicator in a single page app, I would add and remove a CSS class from the body:
#dvReqSpinner {
display: none;
}
body.loading #dvReqSpinner {
display: block;
}
and
$("body").addClass("loading");
$("body").removeClass("loading");
Primarily this would make the JS code independent on the actual page layout, so it's "nicer" but not really "less work".
To do it "automatically", I recommend abstracting your Ajax layer into a helper object:
var API = {
runningCalls: 0,
// basic function that is responsible for all Ajax calls and housekeeping
ajax: function (options) {
var self = this;
self.runningCalls++;
$("body").addClass("loading");
return $.ajax(options).always(function () {
self.runningCalls--;
if (self.runningCalls === 0) $("body").removeClass("loading");
}).fail(function (jqXhr, status, error) {
console.log(error);
});
},
// generic GET to be used by more specialized functions
get: function (url, params) {
return this.ajax({
method: 'GET',
url: url,
data: params
});
},
// generic POST to be used by more specialized functions
post: function (url, params) {
return this.ajax({
method: 'POST',
url: url,
data: params
});
},
// generic POST JSON to be used by more specialized functions
postJson: function (url, params) {
return this.ajax({
method: 'POST',
url: url,
data: JSON.stringify(params),
dataType: 'json'
});
},
// specialized function to return That Thing with a certain ID
getThatThing: function (id) {
return this.get("/api/thatThing", {id: id});
}
// and so on ...
};
so that later, in your application code, you can call it very simply like this:
API.getThatThing(5).done(function (result) {
// show result on your page
});
and be sure that the low-level stuff like showing the spinner has been taken care of.
You can use global ajax handlers for this.
This code will execute whenever you make an ajax request. all you have to do here is enable your spinner.
$( document ).ajaxSend(function() {
$("#dvReqSpinner").show();
});
This code will execute once your ajax request succeeded. all you have to do here is enable your spinner.
$( document ).ajaxSuccess(function( event, request, settings ) {
$("#dvReqSpinner").hide();
});
You can also use other global ajax function to handle things like showing a popup when a ajax request fails using ".ajaxError()"
Below link will have details of all the other functions
https://api.jquery.com/category/ajax/global-ajax-event-handlers/

Execute Javascript after ajax response has been rendered

I want to execute a piece of javascript after the ajax response has been rendered. The javascript function is being generated dynamically during the ajax request, and is in the ajax response. 'complete' and 'success' events to not do the job. I inspected the ajax request in Firebug console and response hasn't been rendered when the complete callback executes.
Does not work:
function reloadForm() {
jQuery.ajax({
url: "<generate_form_url>",
type: "GET",
complete: custom_function_with_js_in_response()
});
};
ajaxComplete does the job, but it executes for all the ajax calls on the page. I want to avoid that. Is there a possible solution?
$('#link_form').ajaxComplete(function() {
custom_function_with_js_in_response();
});
you can also use $.ajax(..).done( do_things_here() );
$(document).ready(function() {
$('#obj').click(function() {
$.ajax({
url: "<url>"
}).done(function() {
do_something_here();
});
});
});
or is there another way
$(document).ready(function() {
$('#obj').click(function() {
$.ajax({
url: "<url>",
success: function(data){
do_something_with(data);
}
})
});
});
Please, utilize this engine for share your problem and try solutions. Its very efficient.
http://jsfiddle.net/qTDAv/7/ (PS: this contains a sample to try)
Hope to help
Checking (and deferring call if needed) and executing the existence of the callback function might work:
// undefine the function before the AJAX call
// replace myFunc with the name of the function to be executed on complete()
myFunc = null;
$.ajax({
...
complete: function() {
runCompleteCallback(myFunc);
},
...
});
function runCompleteCallback(_func) {
if(typeof _func == 'function') {
return _func();
}
setTimeout(function() {
runCompleteCallback(_func);
}, 100);
}
Can't help a lot without code. As an general example from JQuery ajax complete page
$('.log').ajaxComplete(function(e, xhr, settings) {
if (settings.url == 'ajax/test.html') {
$(this).text('Triggered ajaxComplete handler. The result is ' +
xhr.responseHTML);
}
});
In ajaxComplete, you can put decisions to filter the URL for which you want to write code.
Try to specify function name without () in ajax options:
function reloadForm() {
jQuery.ajax({
url: "<generate_form_url>",
type: "GET",
complete: custom_function_with_js_in_response
});
};

Categories