ajax inside addEventListener not working - javascript

This is very simple but I am missing something here and could not figure out. I have a submit button with an addEventListener so when you click, it will call to php file. However, this is what i get
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
but it works if i place ajax outside of addEventListener. I am so confused
index.html
<input type="submit" value="Submit" id="submit"/>
index.js
$(document).ready(function() {
document.getElementById('submit').addEventListener('click', function () {
$.ajax({
type: 'GET',
url: 'index.php',
data: {'user_id': '123213'},
complete: function (response) {
alert(JSON.stringify(response));
}
})
})
});
index.php
echo json_encode("got to php file!!!");

Try this instead:
$('#submit').click(function(){ // Click handler
$.get('index.php',
{'user_id': '123213'}, // Data payload
function(resp) { // Response callback
alert(JSON.stringify(resp));
});
return false; // Prevent default action
});

$(document).ready(function() {
$('#submit').on('click', function () {
$.ajax({
type: 'GET',
url: 'index.php',
data: {'user_id': '123213'},
})
.done(function(data) {
console.log("success");
})
.fail(function(msg){
console.log("error");
});
})
});
Try this it will work

Related

Action returns Status Code 204 but, AJAX success function doesn't execute

My controller is correctly returning new HttpStatusCodeResult(204)(checked using debugging), but the success function is not triggered. I just want to reset a text field after I've submitted something.
Ajax:
$(document).ready(function () {
$("#offersubmit").click(function (e) {
$.validator.unobtrusive.parse($('offerForm'));
if ($(this).valid()) {
var valdata = $("#offerForm").serialize();
$.ajax({
url: "/Product/MakeOffer",
type: "POST",
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: valdata,
success: $(document).ready(function () {
alert("AAA");
$('#offerText').val('');
})
})
}
});
});
Also tried with alert() and it didn't show anything. Any help would be appreciated
You need to remove the $(document).ready(.. code
success: $(document).ready(function () {
alert("AAA");
$('#offerText').val('');
})
should be
success: function(data) {
alert("AAA");
$('#offerText').val('');
}

Why is my response data empty in the complete function of a jquery ajax call?

I have a function that fires two ajax calls when toggling a radio button. Both calls return a price and put it inside an element. The problem is when I spamclick the radiobutton, sometimes the prices differ from eachother while they should be the same, this means the ajax calls are out of synch with eachother.
I tried removing the part that appends the price from the success function to the complete function, so it only adds the result of the PHP scripts when the entire call is finished. But for some reason it won't append the price when I put it inside the complete function, why is that?
My function:
$('.checkoutwrap input[name=ontwerpcontrole]').on("change", function(e) {
e.preventDefault();
var productid = $(this).closest('.prodinfoleft').siblings('.prodinforight').find('.productid').val();
var $pricediv = $(this).closest('.prodinfoleft').siblings('.prodinforight').find('.prodinfoprice');
$.ajax({
type:'post',
url:"checkout/ontwerpcontrole.php",
data:({ontwerp: ontwerp, productid: productid}),
success:function(data){
},
complete: function(data) {
refreshcoupon(true);
}
});
$.ajax({
type:'post',
url:"checkout/prices.php",
data:({productid: productid}),
success:function(data){
},
complete: function(data) {
$($pricediv).empty().append( data );
}
});
});
Above puts no price in $pricediv, but when I put that part in the success function like this:
$('.checkoutwrap input[name=ontwerpcontrole]').on("change", function(e) {
e.preventDefault();
var productid = $(this).closest('.prodinfoleft').siblings('.prodinforight').find('.productid').val();
var $pricediv = $(this).closest('.prodinfoleft').siblings('.prodinforight').find('.prodinfoprice');
$.ajax({
type:'post',
url:"checkout/ontwerpcontrole.php",
data:({ontwerp: ontwerp, productid: productid}),
success:function(data){
},
complete: function(data) {
refreshcoupon(true);
}
});
$.ajax({
type:'post',
url:"checkout/prices.php",
data:({productid: productid}),
success:function(data){
$($pricediv).empty().append( data );
},
complete: function(data) {
}
});
});
The function used inside the first ajax call:
function refreshcoupon(force){
$.ajax({
type:'post',
url:"checkout/refreshcoupon.php",
data:({}),
success:function(data){
$( "body #coupon" ).empty().append( data );
}
});
}
It works fine (except like mentioned if you click to fast the prices are not the same).
Why is this?
You have couple of synced and couple of sequential ajax calls. Therefor it may happen that first request is done after last one. You probably have more solutions, but simply one would be to check if your variable productid is still same in ajax success function:
$('.checkoutwrap input[name=ontwerpcontrole]').on("change", function(e) {
e.preventDefault();
var $ontwerp = $(this).closest('.prodinfoleft').siblings('.prodinforight').find('.productid');
var productid = $ontwerp.val();
var $pricediv = $(this).closest('.prodinfoleft').siblings('.prodinforight').find('.prodinfoprice');
$.ajax({
type: 'post',
url: "checkout/ontwerpcontrole.php",
data: ({
ontwerp: ontwerp,
productid: productid
}),
success: function(data) {
if ($ontwerp.val() == productid) {
refreshcoupon($ontwerp, productid);
};
}
});
$.ajax({
type: 'post',
url: "checkout/prices.php",
data: ({
productid: productid
}),
success: function(data) {
if ($ontwerp.val() == productid) {
$($pricediv).empty().append(data);
};
}
});
});
function refreshcoupon($ontwerp, productid) {
$.ajax({
type: 'post',
url: "checkout/refreshcoupon.php",
data: ({}),
success: function(data) {
if ($ontwerp.val() == productid) {
$("body #coupon").empty().append(data);
};
}
});
}
Anyhow... looking at this code it does not look fine. Maybe try to do it with only one ajax call, save resources, reduce errors and debugging etc.

Form submit on button click in a multistep form

I have a form which has a save and continue button. So I want the third click to submit the data. I have written the following code for it. But the submit portion doesn't work.
$(document).ready(function(){
var datastring="";
var d1= $( "#Submit3" ).mousedown(function() {
alert("Event occurred");
datastring = $("#reg_form").serialize();
console.log(datastring);
});
function submit()
{
$('form').submit(function(){
$.ajax({
type: "POST",
url: "reg.php",
data: datastring,
success: function(data) {
console.log('Data sent');
}
});
});
}
$.when(d1).done(submit());
});
Try the following code
$(document).ready(function(){
$( "#Submit3" ).on("click", function() {
alert("Event occurred");
dataString = $("#reg_form").serialize();
console.log(dataString);
submit(dataString);
});
function submit(dataString)
{
$.ajax({
type: "POST",
url: "reg.php",
data: dataString,
success: function(data) {
console.log('Data send');
}
});
}
});
You need to make the button type of the third button to "submit" and the type of other two buttons should be "button" just like this.
<button type="button">Save</button>
<button type="button">Continue</button>
<button type="submit">Submit</button>
So that when you click on the other two buttons form will not be submitted. Only on the click of third button, your form will be submitted. Here is the script to submit the form
$("form").submit(function(e){
e.preventDefault();
var formData=$("form").serialize();
console.log(formData);
$.ajax({
type: "POST",
url: "register.php",
data: formData,
success: function(response) {
console.log('Data send');
}
});
});

Reusable Ajax call in X times with same logic

This is very bad code
I need to do similar logic but without setInterval.
There is foundation 5 modal dialog
<span class="spanButton registration" data-reveal-id="addExternalRegistration">Add external registration</span>
This button that reveal empty modal
<div id="addExternalRegistration" class="reveal-modal" data-reveal aria-hidden="true">
and with jQuery I am fill dialog with form.
In Ajax success I change content in dialog if form has errors.
And story ends here. But I need to cover x submits before form is valid.
setInterval kills memory I know that, this is just example to show what I want.
response is new form with errors and should not be sumbited, it is need to send ajax request and all that in x circles.
$('.registration').click(function () {
$('#addExternalRegistration').load("/dashboard/add-external-registration/{{ confName }}");
setInterval(function () {
$('form[name="dashboard_conference_registration_form"]').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '/dashboard/add-external-registration/{{ confName }}',
method: 'POST',
data: $(this).serialize(),
success: function(response) {
$('#addExternalRegistration').html(response);
}
});
});
}, 3000);
});
I do some old tricks.
recursive calls
This is function that sends ajax request unlimited number of time
(in theory because of leak of memory, unfortunately).
var ajax = function () {
$('form[name="dashboard_conference_registration_form"]').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '/dashboard/add-external-registration/{{ confName }}',
method: 'POST',
data: $(this).serialize(),
success: function(response) {
$('#addExternalRegistration').html(function () {
return response;
});
setTimeout(ajax(), 2000);
}
});
});
};
Then I call recursive function that fires recursion on submit.
$('.registration').click(function () {
$('#addExternalRegistration').load("/dashboard/add-external-registration/{{ confName }}",
// Wait until form is loaded at modal window
// And then do the logic
function () {
$('form[name="dashboard_conference_registration_form"]').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: '/dashboard/add-external-registration/{{ confName }}',
method: 'POST',
data: $(this).serialize(),
success: function(response) {
$('#addExternalRegistration').html(function () {
return response;
});
setTimeout(ajax(), 2000);
}
});
});
}
);
});

jQuery and Bootstrap don't let me use AJAX

I have form that is posted through AJAX. If I don't use any other JavaScript libraries it works like a charm.
Now I'm using Bootstrap and jQuery and it won't fire.
The code:
$(function() {
$('form').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'ajax-post.php',
data: $(this).serialize(),
alert($(this).serialize());
success: function() {
$(".alert").show(0).delay(2000).hide(0);
}
});
e.preventDefault();
});
});
You can not put alert between two properties data and success, remove alert():
$('form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'ajax-post.php',
data: $(this).serialize(),
success: function () {
$(".alert").show(0).delay(2000).hide(0);
}
});
e.preventDefault();
});

Categories