ajax call executing twice - ajax

Hello Everyone i have modal dialog that trigger database insertion when it has been closed. However when i check my table in DB i often duplicate insertion.
The insertion is done thru ajax call. Here is my source code
$(`#closingModal-${alertId}`).on('hidden.bs.modal', function (e)
{
//..Load la map pour la localisation du badge d'alerte
loadMapByMacAddress(macAddress)
//..Inserer dans la BD le nom de l'utilisateur qui a ferme le modal
const alarmId = parseInt(alertId.replace('alerte', ''));
$.ajax({
url: "/Observer/SetStopDynamicAlarm",
type: "POST",
data: {
LastUpdate: dateFermeture.toJSON(),
AlarmId: alarmId
}
});
$(this).remove();
});
I don't really any error in the above source code. Any help woud be appreciated.
Thanks

Related

get input value with ajax

I'm trying to get the value of an input with ajax, but i only manage to get the full input, not its value.
Here is my code:
$("#formulaire1").submit(function(e){ // On sélectionne le formulaire par son identifiant
e.preventDefault(); // Le navigateur ne peut pas envoyer le formulaire
var donnees = $(this).serialize(); // On créer une variable content le formulaire sérialisé
$.ajax({
url : 'index.php',
type : 'POST',
data : donnees,
success : function(data, statut){
if (text1 !== '') { $("#resultat").text(text1[0]);}
I think I should use .val() but I can't make it work while putting this result in #resultat.
Could you please help me?
thanks you very much!

Google Analytics Goal for ajax form submissions not scoring the goals

I have tried this answer but it is not working properly:
https://stackoverflow.com/a/33207127/9124081
This answer possibly needs to be updated for more recent versions of GA. I did the following to set up goals when the page is submitted via ajax.
$.ajax({
type: "POST",
url: "/some/page/that/does/not/have/ga/on/it.php",
data: { formData:formData },
success: function() {
// Some success message to user.
// Create a virtual page view that you can track in GA.
ga('send', {
'hitType' : 'pageview',
'page' : '/contact-us-success' // Virtual page (aka, does not actually exist) that you can now track in GA Goals as a destination page.
});
}
});
Then in GA -> Admin -> Goals -> New Goal
(1) Goal setup - Custom
(2) Goal description -> choose 'Destination'.
(3) Goal details -> Destination Equals to /contact-us-success
Hope this helps someone else.
And this is my current code:
$(document).ready(function() {
// Antes de enviar
$('#formdata').submit(function() {
$('#botonenviar').hide();
$('#loader').show();
// Enviamos el formulario usando AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
// Mostramos un mensaje segun respuesta de PHP
success: function(rsp) {
if(rsp=='error')
$('#fracaso').show(),
$('#loader').hide()
;
else
$('#exito').show(),
$('#loader').hide(),
ga('send', {
'hitType' : 'pageview',
'page' : '/contact-us-success' // Virtual page (aka, does not actually exist) that you can now track in GA Goals as a destination page.
});
}
})
return false;
});
})
No console errors, I have disable adblockers even.
Since you are mentioning the ga object:
ga('send','event', <Category>, <Action>, <Label>);
EDIT: You use tag manager, therefore you have to use the dataLayer object.
This is the correct syntax to track a contact form, then you create a Goal in Analytics
$(document).ready(function() {
// Antes de enviar
$('#formdata').submit(function() {
$('#botonenviar').hide();
$('#loader').show();
// Enviamos el formulario usando AJAX
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
// Mostramos un mensaje segun respuesta de PHP
success: function(rsp) {
if(rsp=='error')
$('#fracaso').show(),
$('#loader').hide();
else
//ga('send','event','form','submitted');
dataLayer = dataLayer || []; // Safe init
dataLayer.push({'event' : 'form_submitted'});
$('#exito').show(),
$('#loader').hide(),
}
})
Go into Tag Manager, create a new tag with the following:
Tag configuration - Universal Analytics - Event.
Event Category and Event Action you can put what you prefer as long as it's the same as what you put in the Goal information. Remember to also set the Google Analytics property ID into a Google Analytics variable.
Trigger configuration - Custom event, all custom events and you put form_submitted inside the textbox.
And then, if needed you create an Event Goal . You test them from Real time > Events and analyze them through Behaviour > Events.

What´s the difference between traditional:true option and false in Ajax call?

All of this is for discard a problem with a MVC controller.
This is the code of the ajax:
$.ajax({
//tipo de transferencia
type: "POST",
//dato a enviar
dataType: 'Json',
traditional:true,
//enviar variable previamente formada contiene la estructura del modelo
data:data,
//liga previamente asignada esta liga contiene la ruta controlador-metodo
url: url,
Notice the traditional:true.
jQuery API documentation
http://api.jquery.com/jQuery.Ajax/#jQuery-ajax-settings
traditional
Type: Boolean
Set this to true if you wish to use the
traditional style of param serialization.
The traditional property changes the way how parameters are sent to the server. As of jQuery 1.8, it is defaulted to false.
For ASP.NET MVC developer
$.ajax(url, {
data : { a : [1,2,3] },
traditional : true
}));
// `data` are sent as "a=1&a=2&a=3"
If traditional was set to false the data would be sent as a%5B%5D=1&a%5B%5D=2&a%5B%5D=3
Answer adapted from neverever from this thread

CasperJS test does not run

I have got a problem with my test in CasperJS.
This is my code:
var casper = require('casper').create({
viewportSize:{
width:1920,
height: 1080
}
});
casper.start('http://myweb.es/', function() {
})
//COMPROBACION DE POPUP LOGIN
casper.then(function(){
this.click('.btn-attendee');
this.waitForSelector(
'#form_signup2',
function(){
//El parametro 'INFO' es para que el echo aparezca en color VERDE
this.echo('Existe el popup SIGNUP', 'INFO');
this.capture('signup.jpg', undefined, {
format: 'jpg',
quality: 75,
});
this.echo('pantallazo signup', 'INFO');
this.wait(4000, function() {
this.fill('form#form_signup2', {
'first_name': 'Perico',
'last_name': 'Palotes',
'email': new Date().getTime()+'#testing.es',
'password': '123456'
//Ponemos false porque sino nos haria el SUBMIT del formulario y no queremos eso.
//En el email la pasamos un numero aleatorio para que no de fallo al ejecutar el script varias veces
}, true);
//PROBLEM HERE! No run this CLICK
this.click('.checkbox');
this.capture('form.jpg', undefined, {
format: 'jpg',
quality: 75,
});
this.echo('pantallazo form', 'INFO');
});
},
function(){
//El parametro 'ERROR' es para que el echo aparezca en color ROJO
this.echo('error login', 'ERROR')
},
10000
);
});
casper.run();
My problem is that in the comment //PROBLEM this.capture runs but the this.click does not run and this class is good and works in the console of firebug with Mozilla.
this.click does not run in this part of code.
What's my problem?
you need to learn how casperjs uses jquery. it has to be passed to the evaluate function inside of your casper function.
If you don't wish to click by jquery, you could just say casper.click(x('yourXpath'));
Otherwise you need to make sure your jQuery attempts to click are using the right context.
high level example to use jquery...
casper.then(function () {
// this is your casper function
this.evaluate(function () {
// this is the function that can now manipulate the page using jQuery
$('.yourClass').click();
});
});

ajax formdata : Illegal invocation

I try to make ajax script for upload for Symfony 2. Chrome returns this error:
Uncaught TypeError: Illegal invocation jquery.min.js:4
I think it's due to the FormData object not correctly constructed (I try the script with .serialized():
$(document).ready(function() {
$('#formImage').submit(function(event) {
event.preventDefault();
// appel Ajax
alert("ajax");
var input = document.getElementById("rasta_blogbundle_imagetype_file");
console.log(input);
var formdata = false;
if (window.FormData) {
formdata = new FormData();
console.log('formdata initialized ...');
}
else{
console.log('formdata not supported');
}
formdata.append('name',$('#rasta_blogbundle_imagetype_name').val());
console.log(formdata);
formdata.append('file',input);
formdata.append('_token',$('#rasta_blogbundle_imagetype__token').val());
console.log(formdata);
//alert(DATA);
if (formdata){
$.ajax({
url: $(this).attr('action'), // le nom du fichier indiqué dans le formulaire
type: $(this).attr('method'), // la méthode indiquée dans le formulaire (get ou post)
cache: false,
//data : $(this).serialize(),
data: formdata ,
success: function(data) { // je récupère la réponse du fichier PHP
$('#myModal').html(data);
console.log('ok');
}
//return false; //
});
}
});
});
jQuery tries to transform your FormData object to a string, add this to your $.ajax call:
processData: false,
contentType: false
it occurs sometime when jquery internally not serialize data correctly data to fix it add this.
cache : false,
dataType : 'json',
processData : false,
I have solved the issue just by adding following these:
contentType: false,
processData: false,
cache: false,

Resources