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.
Related
I need to access a js variable declared in one block of a html page into another block of the same html page just so I can stop a ajax call that is being made, but I don't know how can I access a variable that was declared into another block. I can't merge the two blocks, everything else is on the table.
<script>
$(function() {
var term = new Terminal('#input-line .cmdline', '#container output');
term.init();
});
</script>
<script>
term.ajaxHandler.abort();//but how can I access the variable term from the block above,this will be inside a button later
</script>
Thanks in advance
The way your code example is described, it's not possible to reuse that variable. Because it is not bound to the window object, it's bound to the function that is self-executed. It's an example of a "safe" way of libraries not intervening with your own code.
You can however, since I guess by the syntax it's jQuery, hook into the jQuery ajax handling. Based on your requirements, to stop an ajax call, you need to listen to all ajax requests.
You could take a look at the jQuery ajax hooks, https://api.jquery.com/category/ajax/.
You could end up with something like:
$(document).ajaxSend(function(event, xhr, settings){
if (settings.url === "/your/url/to/abort") {
xhr.abort();
}
});
just declare var term above the function declaration
var term
function test1(){
term = 'hello there'
test2()
}
function test2(){
console.log(term)
}
test1()
ok, I managed to solve, basically I created a function only to abort the ajax request like this:
this.abortAjax = () => {
requestHandler.abort();
}
and then accessing it within terminal.js itself using the term object that was instantiated beforehand. After working around the code I was able to keep everything inside the terminal script and not splitted in the two parts, getting something like this:
function ShowLoadingScreen () {
var customElement = $("<div>", {
"class" : "btn btn-danger btn-lg",
"text" : "Abort",
"onclick": "term.abortAjax()"
});
$.LoadingOverlay("show", {
//image : "/static/loading.gif",
background : "rgba(204, 187, 0, 0.8)",
imageAnimation : "rotate_right",
//imageAutoResize : true,
text : "Loading...",
custom : customElement
});
}
function request (command) {
...
requestHandler = $.ajax({
url: _url,
beforeSend: function () { ShowLoadingScreen(); }, // <Show OverLay
type: 'GET',
dataType: 'json',
success: function (response) {
...
},
complete: function () { HideLoadingScreen(); } //<Hide Overlay
}).fail(function (jqXHR, textStatus, error) {
...
});
ShowLoadingScreen();
}
Thanks, everyone.
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();
});
As my title indicates, I need to run a function if any ajax get/post is fired.
I tried using
$(document).ajaxStart(function () {
console.log('a');
});
$(document).ajaxComplete(function () {
console.log('c');
});
but it runs only for the first time.
Later it does not log anything. What am I doing wrong?
I need to do this in chrome extension and on google image search page, so after 100 images it fire a ajax function to get more image data and show on page.
You probably want it to work even if AJAX requests are not made with jQuery with a technique like How to check if HTTP requests are open in browser?
(function() {
var oldOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
console.log('Request went out', arguments);
oldOpen.call(this, method, url, async, user, pass);
}
})();
You might be looking for something like this:
$.ajaxSetup({
success: function(){
callYourFunctionHere();
}
});
OR
$(document).bind("ajaxSend", function(){
alert('ajax fired');
callYourFunctionHere();
});
Hope it works for you.
The ajax method itself can accept functions in beforeSend and complete.
.ajax({
// the rest of your parameters
complete: function(data) {
// do something
}
});
If you do not want to specify these on a per-request basis, you can do so with the `.ajaxSetup' function which modifies the defaults.
.ajaxSetup({
beforeSend: function() {
// custom logic
},
complete: function() {
// custom logic
}
});
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
});
};
After getting a new page with $.get none of the javascript will run on the new page.
Is there a way to make javascript use the new page too?
Many thanks
Dorjan
Edit: Example:
$(function() {
$('.viewPage').click(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Now this works fine however, the new page's anchor tags won't trigger (lets say it has a .viewPage).
I hope that clarify's the issue.
You need to bind events to your anchors using live:
$('a.something').live("click",function() {
alert('this will still work after a.something has been replaced via ajax');
});
Another way using $.get's callback:
$.get( "page.html", function(data) {
$('#someDiv').html(data);
$('a.something').click(function() {
alert('this will still work after a.something has been replaced via ajax');
});
});
Now that I've seen your code:
$(function() {
$('.viewPage').live("click",(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Yep; there is another jquery ajax method that will take the returned script from your page and execute it. Check the jquery docs.