AJAX form - post result data to correct DIV - javascript

Can someone help a JS newbie?
Almost everything is working, results are returned, nothing opens new tabs, forms submit to MC database....however I cannot get the result html to post to the correct DIV. All results are being posted to the footer div.
I am guessing my selectors are not specific enough? But I do not have the knowledge on how to structure correctly.
2 forms on page using AJAX submit.
1 pop up form and 1 form in footer..... but all the result html is posting the the div in the footer.
I have adjusted the function register names as suggested (and updated the code below), but form result data is still going to the footer div
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};
<!--HTML POP UP FORM-->
<form
action="mailchimp url"
method="post"
name="pop-form"
id="pop-mc-embedded-subscribe-form"
class=""
target="_blank"
novalidate
>
<div class="form-group">
<input
type="email"
name="EMAIL"
class="form-control required"
placeholder="Enter your e-mail"
id="pop-mce-EMAIL"
/>
<input
type="submit"
value="SUBSCRIBE HERE"
name="pop-subscribe"
id="pop-mc-embedded-subscribe"
class="button"
/>
</div>
<div id="pop-subscribe-result"></div>
</form>
<!--FOOTER FORM HTML-->
<form
action="mailchimp url"
method="post"
id="footer-mc-embedded-subscribe-form"
name="footer-form"
class=""
target="_blank"
novalidate
>
<div class="mc-field-group">
<label for="mce-EMAIL"
>Email Address <span class="asterisk">*</span>
</label>
<input
type="email"
value=""
name="EMAIL"
class="form-control required email"
id="footer-mce-EMAIL"
placeholder="Email Address *"
/>
</div>
<div class="mc-field-group">
<label for="mce-FNAME">First Name </label>
<input
type="text"
value=""
name="FNAME"
class="form-control"
id="mce-FNAME"
placeholder="First Name"
/>
</div>
<div class="mc-field-group">
<label for="mce-LNAME">Last Name </label>
<input
type="text"
value=""
name="LNAME"
class="form-control"
id="mce-LNAME"
placeholder="Last Name"
/>
</div>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;" aria-hidden="true">
<input
type="text"
name="b_dc51fb25cd808abedc98e3ff2_ea4d259202"
tabindex="-1"
value=""
/>
</div>
<div class="footer-btn">
<input
type="submit"
value="Subscribe"
name="footer-subscribe"
id="mc-embedded-subscribe"
class="button"
/>
</div>
<div id="footer-subscribe-result"></div>
</form>

You have two functions with the same name "register" so when you press the submit button in either forms it runs in the register function in the footer since it has the same name as the one dedicated to the popup form
Use this code and your form will work as expected:
//JAVASCRIPT
// FOOTER FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#footer-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerFooterFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register1($registerFooterFormbutton);
} catch(error){}
});
// POP UP FORM. waits for form to appear rather than appending straight to the form. Also helps if you have more than one type of form that you want to use this action on.
$(document).on('submit', '#pop-mc-embedded-subscribe-form', function(event) {
try {
//define argument as the current form especially if you have more than one
var $registerPopUpFormbutton= jQuery(this);
// stop open of new tab
event.preventDefault();
// submit form via ajax
register($registerPopUpFormbutton);
} catch(error){}
});
// POP UP FORM. post result to div
function register($registerPopUpForm) {
$('#pop-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerPopUpForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#pop-mc-embedded-subscribe-form').val('pop-subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ffffff')
$('#pop-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#pop-subscribe-result").html(data['msg']);
$('#pop-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#pop-mce-EMAIL').css('borderColor', '#ff8282')
$('#pop-subscribe-result').css('color', '#ff8282')
$("#pop-subscribe-result").html(data['msg']);
}
}
})
};
// FOOTER FORM. post result to div
function register1($registerFooterForm) {
$('#footer-mc-embedded-subscribe-form').val('Sending...');
$.ajax({
type: 'GET',
url: 'https://websitename.us16.list-manage.com/subscribe/post-json?u=.....&c=?',
data: $registerFooterForm.serialize(),
cache: false,
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
error: function (err) { alert('Could not connect to the registration server. Please try again later.') },
success: function (data) {
$('#footer-mc-embedded-subscribe-form').val('footer.subscribe')
if (data.result === 'success') {
// Yeahhhh Success
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ffffff')
$('#footer-subscribe-result').css('color', 'rgb(53, 114, 210)')
$("#footer-subscribe-result").html(data['msg']);
$('#footer-mce-EMAIL').val('')
} else {
// Something went wrong, do something to notify the user.
console.log(data.msg)
$('#footer-mce-EMAIL').css('borderColor', '#ff8282')
$('#footer-subscribe-result').css('color', '#ff8282')
$("#footer-subscribe-result").html(data['msg']);
}
}
})
};

You are defining the register() function two times with the same name. The second one overwrites the first and everytime you call the function with that name you call the second function. An easy solution is to change the name of the functions (i.e registerPopUpForm() , registerFooterForm() ) and use them accordingly.

Related

how to send form data in ajax with multiple files without refreshing?

in my form code there is text input, checkbox input, file input type...etc,
everything working fine except the file input it's only taking one value ( multiple files upload isn't sending through ajax call ) how can i send arrays inside the serialize() function ?
Code :
<form action="#" id="postAdd" enctype="multipart/form-data">
<input accept=".png,.jpg,.jpeg" type="file" class="form-control-file d-none" id="file-upload" name="file[]" multiple required>
<input autocomplete="off" type="text" class="form-control bg-white" name="discName[]">
<button id="postAdbtn" class="btn btn-primary d-block mt-2">Submit</button>
</form> $(document).ready(function() {
$('#postAdbtn').click(function() {
var form = $('#postAdd').serialize();
$.ajax({
url: 'add-product-done.php',
method: "POST",
data: {
form: form
},
success: function(data) {
$('.fetchData').html(data);
}
})
});
});
one more thing, how can i get the files in PHP ?
and thanks
Can you try something like this?
var form = new FormData($("postAdd"));
$.ajax({
url: 'add-product-done.php',
data: form,
contentType: "multipart/form-data",
type: 'POST',
success: function(data){
console.log(data);
},
error: function(err){
console.error(err);
}
});

Why Ajax is sending object in Response?

I have a very simple script in php that is supose to send a request to ajax and return the string im putting in the .php file but when the request respond, it sends an object instead of the string. I dont know why this is hapening because i already have done this the same way previusly and works fine.
this is the form that send the request
<form method="POST" id="personForm">
<div class="form-group col-md-6">
<label for="NameInput">Name</label>
<input type="text" name="name" class="form-control" id="NameInput">
</div>
<div class="form-group col-md-6">
<label for="lNameInput">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lNameInput">
</div>
<input type="button" name="Send" class="btn btn-info" onclick="ajaxRequest($('#NameInput').val(), $('#lNameInput').val())" value="Send">
</form>
<hr>
<div id="result">
</div>
This is the script that send the ajax request
function ajaxRequest(name, lastn) {
var params = {
"name" : name,
"lastn" : lastn
};
$.ajax({
url: './process/resquestAjax.php',
method: 'POST',
data: params,
beforeSend: function() {
$('#result').html('<p>Procesando Peticion...</p>');
},
complete: function(completeResult) {
$('#result').html(completeResult);
},
sucess: function(successResult) {
},
error: function(jqXHR,estado,error){
alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
alert("Please contact support ias soon as posible...!");
}
}); // End Ajax Call
}
and the php file is just this
$nombre = $_POST['name'];
$apellido = $_POST['lastname'];
echo "¡Hello! your name is : ". $nombre ." and your last name: ". $apellido;
I dont know why im not getting the string of that echo in the response of the ajax. it sends an object instead. I'm trying to make other project with database with this but i have the same issue.
See the documentation. You're using the complete callback, which receives the jqXHR object as its first argument.
Instead, you want to use the success (two cs, note), not complete, if you want to use the returned data. success receives the data as its first argument. (You can also use complete to remove the in-progress message, etc.)
So for instance:
function ajaxRequest(name, lastn) {
var params = {
"name" : name,
"lastn" : lastn
};
$.ajax({
url: './process/resquestAjax.php',
method: 'POST',
data: params,
beforeSend: function() {
$('#result').html('<p>Procesando Peticion...</p>');
},
complete: function(completeResult) {
// If you wanted to do something whether the request
// succeeded or failed, you'd do it here. Otherwise,
// remove this handler.
},
success: function(successResult) {
$('#result').html(successResult);
},
error: function(jqXHR,estado,error){
alert('There was an error!: '+estado+' name-> '+error+' otro-> '+jqXHR);
alert("Please contact support ias soon as posible...!");
}
}); // End Ajax Call
}

Laravel csrf token mismatch on ajax post a second time

im trying to submit an ajax post in laravel but im having some problem regarding the form's csrf token. In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted. However if i submit the form and purposely failed the conditions i set in my ajax post url in the first try, If i submit the form again i get a token mismatch exception in my ajax error log. Do i need to refresh the csrf_token every ajax post?
Below is my code
JS
$(document).on('submit','.registration-form',function(e){
e.preventDefault();
var form = $(this);
var form_url = $(this).attr("action");
var form_values = $(this).serialize();
$.ajax({
url:form_url,
type:'POST',
data:form_values,
dataType: 'json',
async:false,
success: function(result){
console.log(result);
if(result['status']==true){
location.href = result['redirect'];
}
else{
form.find(".form-details").show().html(result['message']);
}
},
error: function(ts) {
console.log(ts.responseText)
}
});
});
HTML
<form action="{{ url('login') }}" method="POST" class="registration-form">
{{ csrf_field() }}
<input type="text" name="username" class="input" placeholder="Email">
<input type="password" name="password" class="input" placeholder="Password">
<button class="button is-redbox is-flat is-fullwidth">Login</button>
</form>
Are u sure that each time that is send in ajax?
data: {
"_token": "{{ csrf_token() }}",
}
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
public function regenerateToken(){
session()->regenerate();
return response()->json([
'msg'=>'success',
'token'=>csrf_token()
]);
}
$('#form').submit(funtion(event) {
event.preventDefault(event);
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
if (response.msg === 'success') {
$('#token').val(response.token);
console.log($('#token').val());
}
}
$('input[type="text"],input[type="email"] ,textarea, select').val(''); $(this).trigger('reset');
});

Parse json data with JS being received from php

My form:
<form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
</div>
</form>
the end of my php script
$response = array(
"status" => $status,
"message" => $message
);
echo json_encode($response);
My page is receiving data like:
{"status":0,"message":"This email is already on list!"}
using JS I need to parse that data and then update text within an element.
<span id="notice">Get notified!</span>
here's my script which doesn't work, after senging form data to my php script I get a white screen that shows the json strong
$(document).ready(function() {
$.ajax({
dataType: 'json',
$('#notice').text(data.message);
});
});
You have to handle the response in a callback.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize(),
url: $(this).attr('action'), // Or the path of the PHP file
dataType: 'json',
}).done(function(response) {
$('#notice').text(response.message);
});
});
});
See the related docs here
That ajax call is not well formed, missing success callback and url e.g:
$(document).ready(function () {
$.ajax({
url: '/the/url/where/your/data/comes/from/',
dataType: 'json',
success: function (data) {
$('#notice').text(data.message);
}
});
});
Your code as is, is just executing at page load and not on submission of a form. You need to attach an onsubmit event, prevent the default action of doing the form submit and do your ajax call in there. Also your ajax call itself was malformed
$("#yourFormID").submit(function(e){
e.preventDefault();
$.ajax({
url:"/urlToServerScript",
data:{} //any form data the script needs you should be put here,
dataType:"json" //type of response the server will output
}).then(function(data){
$('#notice').text(data.message);
});
});

JQuery ajax call fails when last input is filled

JQuery noob here,
I'm working on a simple web-app which needs to send registration info to a server.
For some reason this code works fine when only two of the form inputs are filled in, but fails when there's information in the last one, even though I'm not using it in the code. The error callback gets called, but errorThrown is empty. My server receives no data.
Is there anything obviously wrong with this?
Note: the call fails when the last input is filled, no matter how many inputs are in the form.
JQuery:
$(document).ready(function() {
$("#registrationForm button.register").on("click", function(event) {
var params = {
email: $("#registrationForm input.email").val(),
password: $("#registrationForm input.password").val()
};
$.ajax({
url: "/register",
type: "POST",
contentType: "application/json",
data: JSON.stringify(params),
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
if(data.user_exists==true)
{
alert("Stop trying to register twice!");
}else{
window.location.href = "/registered";
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.error("Error:", errorThrown);
}
});
});
});
And the HTML:
<form id="registrationForm">
<label>Email:</label>
<input name="user[email]" type="text" required="required" class="email">
<br>
<label>Password:</label>
<input name="user[password]" type="password" required="required" class="password">
<br>
<label>Verify Password:</label>
<input name="nothing" type="text" required="required">
<br>
<button onclick="" class="btn btn-default register">Register</button>
</form>
Unless you specify otherwise, the button inside your form will submit the form when clicked. In the click function, put event.preventDefault() to stop this default action from taking place. For more details, see the jQuery docs here.

Categories