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!
Related
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
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.
I do not want to change pages, I want to keep it, why redirect this ajax?:
$('#add-user').click(function() {
$.ajax({
type: "GET",
url: "/evaluacion/usuariosSeleccionados",
data: {
fact: JSON.stringify(localStorage.getItem("evaluacion")),
seleccionados: JSON.stringify(yourArray)
},
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function(data) {
document.open("text/html", "replace");
document.write(data);
document.close();
window.location.href="/evaluacion/agregarUsuarios"// esto hago para que se quede en la misma pagina
},
error: function(err) {
var msg = 'Status: ' + err.status + ': ' + err.responseText;
}
});
my link on html is
a(href="" id='add-user' class='btn btn-primary') agregar usuarios
Why are you using document.write() and document.close()? Inside of jQuery especially? Do you intend to replace the entire content of the page once the .ajax query is complete? That's probably why your page is reloading.
You should add some kind of <div> for the .ajax function success, and then put the output passed through with data inside the div.
Anchor tag has a property which will makes page to redirect every time you click it. In your case, because href is blank so it is reloading the page. Prevent the execution process in your event handler using event.preventDefault and it will not reload.
Also, in your success callback, you are trying to redirect the page explicitly window.location.href="/evaluacion/agregarUsuarios" to a new URL.
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
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,