That’s my JQuery code which is currently working ->
$("#newsLetter-form").on('submit',function(event){
event.preventDefault();
email = $('#emailId').val();
console.log(email);
$.ajax({
url: '/subscribes/emailSubscribe',
type:'POST',
data:{
"_token": "{{ csrf_token() }}",
email:email,
},
success:function(response){
console.log(response);
$('#responseFromSub').text("Registred!");
$('#responseFromSub').css('background','lightgreen')
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
error:function(response){
console.log(response);
var val = 'asdasd:111122:123123123';
var response1 = response.responseJSON.message.substring(response.responseJSON.message.indexOf(""title":"));
response1 = response1.split(":").pop();
response1 = response1.split(',')[0];
response1 = response1.replace(""", "");
response1 = response1.replace(""", "");
console.log(response1);
$('#responseFromSub').text(response1);
$('#responseFromSub').css('background','red');
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
});
});
And this is my converted code which isn’t working, it says 400 bad request wrong data. I’m using laravel and mailchimp for newsletter with jquery everything is working but with this pure js code, no ->
function myFunc123() {
var email1 = document.getElementById("emailId").value;
alert(email1);
var data = {
"_token": '{{ csrf_token() }}',
email: email1
};
var boundary = String(Math.random()).slice(2);
var boundaryMiddle = '--' + boundary + 'rn';
var boundaryLast = '--' + boundary + '--rn'
var body = ['rn'];
for (var key in data) {
body.push('Content-Disposition: form-data; name="' + key + '"rnrn' + data[key] + 'rn');
}
body = body.join(boundaryMiddle) + boundaryLast;
var xhr = new XMLHttpRequest();
xhr.open('POST', '/subscribes/emailSubscribe', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.onreadystatechange = function () {
if (this.readyState != 4) return;
alert(this.responseText);
}
xhr.send(body);
}
I fixed it the problem was here ->
var email1 = document.getElementById("emailId").value;
alert(email1);
var data = {
"_token": '{{ csrf_token() }}',
email: email1
Now it’s working..
BUT the page is refreshing after request how can I disable refreshing ?
2
Answers
Okay, final converted version looks like that.
You forgot
event.preventDefault()
, which was in the jQuery code. The default behaviour is to refresh the page on submit (which is a very dumb default), you want to prevent this.