how to stop propagation after making an ajax request in angularJS - ajax

I have an ajax request to server side script in order to validate my captcha. I want my requested script to stopPropagation based on server response.
this is my script:
$scope.submit = function(e){
s_registration.captchaValidation($scope.txtCaptcha)
.then(function(r){
if(r == 'failed'){
e.stopPropagation();
}
});
}
I understand this not gonna work because the response will not arrive soon due to ajax call, but i cannot find another way that fix my scenario. Any advice guys?

you need to stop propagation synchronously, and you called it asynchronously
$scope.submit = function(e){
s_registration.captchaValidation($scope.txtCaptcha);
e.stopPropagation();
}

Related

Is it possible to fire multiple ajax requests asynchronously in Magento 2 backend?

What the title says.
Im trying to run an import script with AJAX "call 1" and I want to keep track of the import (for feedback purposes) with AJAX "call 2".
To give the end user live feedback these calls need to run simultaneously and "call 2" needs to call itself (recursive) to poll for changes.
I have the Controllers and the calls and everything works just fine, just not at the SAME time.
Is it a soft lock on the database or is it something else?
Btw I am aware of the "async: true" setting for the ajax call.
[edit]
It looks like Magento is preventing me from executing two controllers at the same time. Can anyone confirm this?
I think you cannot do two AJAX requests concurrently. This means you always needs to have a logical order, a.k. first 'call 1', then 'call 2'. If you want to make sure call 2 always fires after the call 1 just put it in the success method.
Like so:
$.ajax({
url: "test-to-call-1",
context: call-1-context
}).done(function() {
$.ajax({
url: "test-to-call-2",
context: call-2-context
}).done(function() {
Now both ajax requests are done.
And you could add the context of the first one to the second call.
});
});
If you want to enable polling, just place a setTimeOut loop in which you do the second AJAX call :)
Like this:
function start_polling(counter){
if(counter < 10){ // poll maximum of 10 times.
setTimeout(function(){
counter++;
$.ajax({
url: "test-to-call-2",
context: call-2-context
}).done(function() {
start_polling(counter);
Now both ajax requests are done.
And you could add the context of the first one to the second call.
}).error(function(){
start_polling(counter);
});
}, 1000);
}
}
$.ajax({
url: "test-to-call-1",
context: call-1-context
}).done(function() {
start_polling(0)
});
Well I figured it out.
All I had to do was set:
session_write_close();
In front of the method that started the import and I could start polling with a second AJAX call!
This is probably frowned upon, but it works

Cancel event in AJAX response fire from misc/AJAX.js

How can I override Drupal.ajax written in misc/ajax.js?
I need to check URL existence before firing an AJAX call.
Is there any other way/better way to achieve that without overriding this js?
Thanks
I don't know about Drupal.ajax but this Jquery Method is the way to go:
$(document).ajaxSend(function(event, jqxhr, settings){
if ( settings.url == "some urls" ) {//checks if related url should be checked or not.
//Do Something likeThis url checkingor what ever you want.
if(!UrlExists(settings.url)){
jqxhr.abort();
}
}
});
Be careful, This method is a global ajax event -- so this effectively can filter all ajax requests.

Global AJAX event listeners in Can.JS?

Is it possible to bind listeners to when an AJAX request is started in Can.JS? I want to integrate a little loading indicator in my Can.JS project so that users can see when data is being loaded from my server. Using the jQuery $.ajaxStart and $.ajaxSend events didn't work, however the $.ajaxComplete event did fire correctly.
In your example you are binding to the event on document.ready which is after you start the Ajax request. The complete log only shows because the document is ready and binds the event before the Ajax request returns. If you do everything in the correct order on document.ready like this:
$(document).ready(function(e){
$(document).ajaxStart(function(){
console.log('start');
}).ajaxComplete(function(){
console.log("Complete");
});
var TestModel = can.Model({
findAll: "GET http://jsfiddle.net/echo/json/"
});
TestModel.findAll({}, function(result){
alert(result);
});
});
It works as expected (see updated fiddle).

Detect AJAX Request

On my website I have mouse over and mouse out events set up on an HTML table. These events trigger ajax requests, and perform certain actions etc. However, i want to be able to not trigger a second request if one is already running. So, is there away to detect these requests, and therefore avoid a second. Incidentally Im using the jQuery $.ajax()
if it helps at all.
Thanks in advance
Chris
I'd try something simple like:
var requestMade = false;
function yourAjaxFunction(){
if(!requestMade)
{
requestmade = true;
$.ajax({
url: "page",
success: function(){
requestMade = false;
}
error: function(){
requestMade = false;
}
});
}
}
You can use the success: and error: settings to change the variable back to false.
I have never used the error so you may have to include some other things in it, but this is the general idea.
For this suppose I'd use ajaxStart() and ajaxStop() which would change specific variable ajaxRunning which could be checked before sending the request (maybe in ajaxStart() directly?)
Set global or local static variable to true when first ajax is about to trigger, than add if before triggering the second one ;) Than after one request is finished, set this variable to false

ajax - When to use $.ajax(), $('#myForm').ajaxForm, or $('#myForm').submit

Given so much different options to submit sth to the server, I feel a little confused.
Can someone help me to clear the idea when I should use which and why?
1> $.ajax()
2> $('#myForm').ajaxForm
3> ajaxSubmit
4> $('#myForm').submit
Thank you
I personally prefer creating a function such as submitForm(url,data) that way it can be reused.
Javascript:
function submitForm(t_url,t_data) {
$.ajax({
type: 'POST',
url: t_url,
data: t_data,
success: function(data) {
$('#responseArea').html(data);
}
});
}
HTML:
<form action='javascript: submitForm("whatever.php",$("#whatevervalue").val());' method='POST'> etc etc
edit try this then:
$('#yourForm').submit(function() {
var yourValues = {};
$.each($('#yourForm').serializeArray(), function(i, field) {
yourValues[field.name] = field.value;
});
submitForm('whatever.php',yourvalues);
});
Here is my understanding
$.ajax does the nice ajax way to send data to server without whole page reload and refresh. epically you want to refresh the segment on the page. But it has it's own limitation, it doesn't support file upload. so if you don't have any fileupload, this works OK.
$("#form").submit is the javascript way to submit the form and has same behaviour as the input with "submit" type, but you can do some nice js validation check before you submit, which means you can prevent the submit if client validation failed.
ajaxForm and ajaxSubmit basically are same and does the normal way form submit behaviour with some ajax response. The different between these two has been specified on their website, under FAQ section. I just quote it for some lazy people
What is the difference between ajaxForm and ajaxSubmit?
There are two main differences between these methods:
ajaxSubmit submits the form, ajaxForm does not. When you invoke ajaxSubmit it immediately serializes the form data and sends it to the server. When you invoke ajaxForm it adds the necessary event listeners to the form so that it can detect when the form is submitted by the user. When this occurs ajaxSubmit is called for you.
When using ajaxForm the submitted data will include the name and value of the submitting element (or its click coordinates if the submitting element is an image).
A bit late, but here's my contribution. In my experience, $.ajax is the preferred way to send an AJAX call, including forms, to the server. It has a plethora more options. In order to perform the validation which #vincent mentioned, I add a normal submit button to the form, then bind to $(document).on("submit", "#myForm", .... In that, I prevent the default submit action (e.preventDefault() assuming your event is e), do my validation, and then submit.
A simplified version of this would be as follows:
$(document).on("submit", "#login-form", function(e) {
e.preventDefault(); // don't actually submit
// show applicable progress indicators
$("#login-submit-wrapper").addClass("hide");
$("#login-progress-wrapper").removeClass("hide");
// simple validation of username to avoid extra server calls
if (!new RegExp(/^([A-Za-z0-9._-]){2,64}$/).test($("#login-username").val())) {
// if it is invalid, mark the input and revert submit progress bar
markInputInvalid($("#login-username"), "Invalid Username");
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
return false;
}
// additional check could go here
// i like FormData as I can submit files using it. However, a standard {} Object would work
var data = new FormData();
data.append("username", $("#login-username").val());
data.append("password", $("#login-password").val()); // just some examples
data.append("captcha", grecaptcha.getResponse());
$.ajax("handler.php", {
data: data,
processData: false, // prevent weird bugs when submitting files with FormData, optional for normal forms
contentType: false,
method: "POST"
}).done(function(response) {
// do something like redirect, display success, etc
}).fail(function(response) {
var data = JSON.parse(response.responseText); // parse server error
switch (data.error_code) { // do something based on that
case 1:
markInputInvalid($("#login-username"), data.message);
return;
break;
case 2:
markInputInvalid($("#login-password"), data.message);
return;
break;
default:
alert(data.message);
return;
break;
}
}).always(function() { // ALWAYS revert the form to old state, fail or success. .always has the benefit of running, even if .fail throws an error itself (bad JSON parse?)
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
});
});

Resources