JQuery ajax call fails when last input is filled - javascript

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.

Related

AJAX form - post result data to correct DIV

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.

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
}

How to post form data as JSON?

I'm trying to build a registration site for a group project we are working on but can't figure out how to send the form data as json. I've tried googling a lot and changing the code but nothing seems to work. The problem I have is that when i press on the submit button I get an error like this from the API:
{"":["The input was not valid."]}
I think the reason is that my form does not send the data as JSON and it's they format they require according to their API documentation. My form code looks like this:
<form id="register_form" action="https://https://url.com/users/register" method="post">
<input type="text" pattern="[A-Za-z]{1,20}" placeholder="Name" name="name" title="Up to 20 alphabetical characters" required>
<input type="email" placeholder="Email" name="email" title="Must be a valid email address" required>
<input type="password" pattern="[a-zA-Z0-9-]+{8,20}" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
<input type="text" pattern="[a-zA-Z0-9-]+" placeholder="Homeadress" name="homeadress">
<input type="text" placeholder="Postnumber" name="postnumber">
<input type="text" placeholder="City" name="city">
<br>
<button value="Submit" type="submit">Register</button>
</form>
And the script i've been trying to get to work looks like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
<script type="text/javascript">
$('register_form').on('submit', function(event){
var obj = $('register_form').serializeJSON();
$.ajax({
type: 'POST',
url: 'https://url.com/users/register',
dataType: 'json',
data: JSON.stringify(obj),
contentType : 'application/json',
success: function(data) {
alert(data)
}
});
return false;
});
</script>
Any help would be greatly appreciated since I'm not very familiar with coding stuff like this.
Edit:
I also tried it with a script like this but still getting the same response:
<script>
$(document).ready(function(){
$("#submit").on('click', function(){
var formData = {
"name": $('input[name=name]').val(),
"email": $('input[name=email]').val(),
"password": $('input[name=password]').val(),
"homeadress": $('input[name=homeadress]').val(),
"postnumber": $('input[name=postnumber]').val(),
"city": $('input[name=city]').val()
};
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: 'https://url.com/users/register',
type : "POST",
dataType : 'json',
data : JSON.stringify(formData),
success : function(result) {
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
I tested it with our teachers test api also and the response is this:
{"message":"Bad Request","reason":"val: nil fails spec: :user-system.spec/login-request predicate: map?\n"}
There's a couple problems here.
Invalid start tag for script element. This was probably a copy and paste error, but worth mentioning:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"</script>
missing greater than symbol ^
Selecting register_form instead of #register_form in two places, the second was unnecessary regardless because you could reference this instead. This also resulted in the form submission not being cancelled.
You didn't include a $.serializeJSON plugin, again I'm assuming this is a copy and paste error.
$.serializeJSON (whichever you choose) should return a JSON string, but you run JSON.stringify on the result, which will be a string inside a string.
https://https:// This isn't a huge issue because it is in the action attribute of a form that should never submit, but worth mentioning.
In the example below I've provided a simple replacement for $.serializeJSON, and corrected the rest of the issues listed above. serialize_form in the code below can be replaced with whatever $.serializeJSON plugin you choose to use.
I have commented out the ajax request as what is really of concern here is getting the JSON from the form data, so I just log it to the console instead so that you can see it is a JSON string. I also removed the pattern attributes and required flags from the input for ease of testing.
const serialize_form = form => JSON.stringify(
Array.from(new FormData(form).entries())
.reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
);
$('#register_form').on('submit', function(event) {
event.preventDefault();
const json = serialize_form(this);
console.log(json);
/*$.ajax({
type: 'POST',
url: 'https://url.com/users/register',
dataType: 'json',
data: json,
contentType: 'application/json',
success: function(data) {
alert(data)
}
});*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="register_form" action="https://url.com/users/register" method="post">
<input type="text" placeholder="Name" name="name" title="Up to 20 alphabetical characters">
<input type="email" placeholder="Email" name="email" title="Must be a valid email address">
<input type="password" placeholder="Password" name="password" title="Must be 8 or more characters long and contain at least one number and one uppercase letter">
<input type="text" placeholder="Homeadress" name="homeadress">
<input type="text" placeholder="Postnumber" name="postnumber">
<input type="text" placeholder="City" name="city">
<br>
<button value="Submit" type="submit">Register</button>
</form>

How can I create some kind of alert for the user in node?

I have a form:
<form class="form-inline" action="/" method="post">
<div class="form-group">
<label class="sr-only">Username</label>
<input name="username" type="text" class="form-control" placeholder="Desired Username">
</div>
<br>
<br>
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Email address</label>
<input name="email" type="email" class="form-control" id="exampleInputEmail3" placeholder="Email">
</div>
<br>
<br>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Password</label>
<input name="password" type="password" class="form-control" id="exampleInputPassword3" placeholder="Password">
</div>
<br>
<br>
<button type="submit" class="btn btn-default">Register</button>
</form>
Here is my app.js:
app.post('/', function(req, res) {
var user = new Parse.User();
user.set("username", req.body.username);
user.set("password", req.body.password);
user.set("email", req.body.email);
user.signUp(null, {
success: function(user) {
// Hooray! Let them use the app now.
console.log(user);
res.redirect('/#register');
},
error: function(user, error) {
// Show the error message somewhere and let the user try again.
console.log(error.message);
res.redirect('/#register');
}
});
});
Everything functionally works, I just want to know how I can show a message if the user has been successfully signed up or not. I would also like to know if this is a correct way of handling a form.
Handle the success status after signUp.
success: function(user) {
// Hooray! Let them use the app now.
res.redirect('/#register');
}
On successful signup you are redirecting to /#register page. You can show an alert when this page is loaded.
Front-end JS:
Instead of submitting the form the usual way, we will use jQuery-AJAX for this purpose:
Attach jQuery to your web page using the below <script> tag in your web page's <head> tag:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
Follow it up in the same <head> with the following:
<script type="text/javascript">
$('.form-inline').submit(function(event) {
$.ajax({
type: "POST", // the request type
url: "/", // the URL where your form data will be sent
data: $(this).serialize(), // the form data to be sent
success: function(data) { // this function will be called when you do a res.send from the back-end
alert(data); // although I would suggest you use a modal or some other solution to display your success message
window.location.href = your_redirect_url; // this will redirect the user to your /#register url
}
});
event.preventDefault(); // to prevent the form from being submitted the usual way
});
</script>
NOTE: This is just an example to help you get started.
Back-end JS:
app.post('/', function(req, res) {
...
user.signUp(null, {
success: function(user) {
res.send(your_success_message); // send your success message or status or result object using this method, it will call the success function of your ajax object on the front-end
},
error: function(user, error) {
res.send(your_error_message); // similarly send the error message, or status, or object.
}
});
});

Send Ajax Variables with POST to PHP

I am trying to find the best way to send variables from Javascript to PHP without GET method. I found a way to send through POST method with AJAX:
<form method="POST" id="post" enctype="multipart/form-data">
<input type="file" name="image_upload[]" id="img1" />
<input type="file" name="image_upload[]" id="img2" />
<input type="file" name="image_upload[]" id="img3" />
<input type="text" name="description" id="description" />
<textarea class="intext" name="editor" id="editor"></textarea>
<input type="text" name="state" id="state" disabled="true" />
<input type="text" name="city" id="city" disabled="true" />
<input type="submit" id="submit" />
</form>
And I am trying to submit the form with jQuery:
$('#post').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "cpage.php",
data: {
'variable1': 'content var1',
'variable2': 'content var2'
},
success: function () {
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
NOTE: the variable "position" has been declared before and works fine.
Result: I get "Internal Server Error" in the alert. Any ideas?
First of All - show us what is going on the server side.
And now about the files being sent:
You should use FormData element for file submit threw Ajax, its not supported by old browser, the browsers that would support this are : ie>9, chrome > 7, opera > 12 safari >5, android > 3 gecko mobile > 2, opera mobile >12.
Use something like this:
$('#post').submit(function (event) {
event.preventDefault();
if( window.FormData !== undefined ) //make sure that we can use FormData
{
var formData = new FormData($('form#post'));
$.ajax({
type: "POST",
url: "cpage.php",
data: formData ,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data); // <- for debugging
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
} else {
//fallback
}
});
As you can see I added console.log(data), try looking at the returned data to identify any other problems.

Categories