Ajax to send form to server, fails at serialize? - javascript

It seems like i cant get to serialize my form. I do get the first alert with lol, but not the second alert with pdata. Does anyone see whats wrong? Im trying to use ajax to send the data in the form. Down below is the script and the html code.
<html>
<head>
<script>
function dologin(event) {
event.preventDefault();
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
};
</script>
</head>
<body>
<h1>Logg inn</h1>
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="login" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-default">Logg inn</button>
</form>
<div class="login-help">
<p>Glemt passordet? Trykk her for å endre det.</p>
</div>
</body>
</html>

The problem with your code is, you are accessing event argument wheres there is no parameter passed to the function, so its triggering an error and submitting the form as normal form submission.
If you like to keep your implementation u can modify your code like bellow:
function dologin() {
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
return false;
};
and modify this line
<form id="form" onsubmit="dologin()">
to
<form id="form" onsubmit="return dologin()">
or can use the following way
$(document).ready(function() {
$('#form').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
});
});
And form tag should be then:
<form id="form">

Related

How to submit form using AJAX without having to leave the page HTML Formsubmit

I'm using Formsubmit to send contact us form to my email and so far it's working.
But I would like when user send the form it does not redirect it to the source thank you page instead I'd like to display just thank you text on the same page. I'd like to use my own.
So I followed the documentation and I came up with the following :
Unfortunately when I try validate the form button it does not work
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->
<script type="text/javascript">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
method: "POST",
url: "https://formsubmit.co/el/vupawa",
dataType: 'html',
accepts: 'application/json',
data: frm.serialize(),
success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},
error: function (response) {
console.log('An error occurred.');
console.log(response);
}
complete: function(response){
setTimeout(ajax,1000);
}
});
});
});
</script>
Note : that uncommenting this line <input type="hidden" name="_next" value="thanks.html"> will take validate the form and go through another page which is not what I want here.
Any ideas ?
To Prevent Submission You should return false in
frm.submit(function (e) {
return false;
})
Or in form tag
<form onSubmit="return false">
var frm = $('#contactForm');
var msg_res ='';
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
method: "POST",
url: "https://formsubmit.co/el/vupawa",
dataType: 'html',
accepts: 'application/json',
data: frm.serialize(),
success: function (response) {
$("#message").html(response);
if(response != msg_res){
msg_res = response; //store new response
alert('New message received');
}
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
}
});
return false; // here a change
});
<form id="contactForm" action="https://formsubmit.co/el/myemail" method="POST">
<input type="text" name="name">
<input type="phone" name="phone" inputmode="tel">
<input type="hidden" name="_subject" value="Partenaires">
<input type="email" name="email" >
<input type="text" name="message" >
<button class="btn btn-primary border rounded-0 shadow-lg d-lg-flex justify-content-lg-center"
type="submit" name="sendData">Send</button>
<!-- <input type="hidden" name="_next" value="thanks.html">-->

Web Api 2 Login and Register Actions, JavaScript problems

Today I'm trying Web Api 2 Login and Register Actions. I'm using Standard Template from Visual Studio 2015. I created JavaScript Client on web side, but I do not see alerts and registration is not working.
Here is my code:
<div class="form-group">
<div class="input-group">
<input type="email" class="form-control" placeholder="Email" id="email">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" class="form-control" placeholder="password" id="password">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="password" class="form-control" placeholder="Password again" id="confirmpassword">
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="submit" id="submit" value="Register" class="btn btn-info">
</div>
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
<script>
$(function () {
$('#submit').click(function (e) {
e.preventDefault();
var data = {
Email: $('#email').val(),
Password: $('#password').val(),
ConfirmPassword: $('#confirmpassword').val()
};
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).success(function (data) {
alert("Registration success");
}).fail(function (data) {
alert("Error message");
});
});
})
</script>
}
Update:
Here is code for login process:
div class="userInfo" style="display:none;">
<p>You are loged in as: <span class="userName"></span></p>
<input type="button" value="Log out" id="logOut" />
</div>
<div class="loginForm">
<h3>Log in</h3>
<label>Enter email</label><br />
<input type="email" id="emailLogin" /> <br /><br />
<label>Password</label><br />
<input type="password" id="passwordLogin" /><br /><br />
<input type="submit" id="submitLogin" value="Log in" />
</div>
#section scripts{
<script type="text/javascript">
$(function () {
//...........................
var tokenKey = "tokenInfo";
$('#submitLogin').click(function (e) {
e.preventDefault();
var loginData = {
grant_type: 'password',
username: $('#emailLogin').val(),
password: $('#passwordLogin').val()
};
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
}).success(function (data) {
$('.userName').text(data.userName);
$('.userInfo').css('display', 'block');
$('.loginForm').css('display', 'none');
// store sessionStorage auth token
sessionStorage.setItem(tokenKey, data.access_token);
console.log(data.access_token);
}).fail(function (data) {
alert('Error on login');
});
});
$('#logOut').click(function (e) {
e.preventDefault();
sessionStorage.removeItem(tokenKey);
});
})
</script>
}
Update 2
On registration here is F12 console code:
(index):88 Uncaught TypeError: $.ajax(...).success is not a function
at HTMLInputElement.<anonymous> ((index):88)
at HTMLInputElement.dispatch (jquery-3.1.1.js:5201)
at HTMLInputElement.elemData.handle (jquery-3.1.1.js:5009)
(anonymous) # (index):88
dispatch # jquery-3.1.1.js:5201
elemData.handle # jquery-3.1.1.js:5009
But registration passes and I have new record in database. Can anyone explain me what does it mean?
do it like this :
$.ajax({
type: 'POST',
url: '/api/Account/Register',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
success: function(html){
alert("Registration success");
}
});
Well, I found that I've used submit type button, it's first misstake - if I want operate request using jquery I've use type="button" instead submit.
Another moment is that json properties is not difined in right case:
var data = {
email: $('#email').val(),
password: $('#password').val(),
confirmPassword: $('#confirmpassword').val()
};
this will be correct
Now about error in console: correct is like #Mustapha answered
for example:
$.ajax({
type: "GET",
url: "/api/rooms",
success: function (rooms) {
}
});
Here is fixed ajax code:
$.ajax({
type: 'POST',
url: '/Token',
data: loginData
success: function(data) {
$('.userName').text(data.userName);
$('.userInfo').css('display', 'block');
$('.loginForm').css('display', 'none');
// store sessionStorage auth token
sessionStorage.setItem(tokenKey, data.access_token);
console.log(data.access_token);
},
error: function (data) {
alert('Error on login');
});
});
Here is, but I've done it using angular :)
Thanks.

HTML Form Submit does not reach my javascript

I am trying to reach my javascript code when I press the submit button within my form and it is not triggering my javascript code at all.
So I got this form within my Bootstrap Modal using the following code:
<form id="updateUserForm">
<div class="form-group">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstnameModalInput" />
</div>
<div class="form-group">
<label for="middleName">Middle name:</label>
<input type="text" class="form-control" id="middlenameModalInput" />
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastnameModalInput" />
</div>
<div class="form-group">
<label for="mobileNumber">Mobile number:</label>
<input type="text" class="form-control" id="mobilenumberModalInput" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="emailModalInput" />
</div>
<div class="form-group">
<label for="Enabled">Enabled:</label>
<input type="checkbox" class="form-control" id="enabledModalInput" style="width:34px" />
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" id="submit" value="Apply" />
</div>
</form>
And the javascript code I have:
$('document').ready(function(){
$("#updateUserForm").submit(function (event) {
console.log("Method entered");
event.preventDefault();
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
})
})
I have another function in that javascript that is used to populate the input fields and that works fine, so I guess the HTML can reach the javascript file. But it does not reach the javascript submit function (it doesn't do the console.log for example) . Does anyone have an idea what I am doing wrong?
EDIT:
I have been playing around a bit more, and it seems that I can acces the javascript method when I try to reach it from outside of the bootstrap modal, it goes wrong somewhere within the modal.
Use return false instead of prevent default end of the function and change the submit function with on function.
$('document').ready(function(){
$("#updateUserForm").on("submit", function () {
console.log("Method entered");
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
return false;
})
})
try this
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Can you please try below code. and please check post URL"/Dashboard/UpdateUser" is right?
$("#UpdateUserForm").submit(function (e)
{
var isValid = $("#UpdateUserForm").valid();
if (!isValid)
return;
//This is important as it prevents the form being submitted twice
e.preventDefault();
$.ajax({
type: "POST",
url: "/Dashboard/UpdateUser",
data: $("#UpdateUserForm").serialize(),
success: function (response)
{
var status = '';
status = response.Status;
console.log("succes!");
console.log(data);
}
})
.error(function () {
console.log("error");
console.log(data);
});
});
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Or use action properties in form.

Submit multiple forms same jquery script

I have multiple forms and I want all of them to be processed by a single jquery script, of course I have php functions that work correctly, I tried them separately.
This is my script:
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
My form looks like this
<form id="contacto" name="contacto" method="post" onsubmit="proceso_form('contacto', 'cargando')">
<input type="text" name="name"class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
I think my problem is that I can't put my script in the onsubmit, but honestly I have no idea.
Your html must look like
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form(this, 'cargando')">
...
</form>
And inside the function:
function proceso_form(form, id_div_error){
var $form = $(form);
var url = "my_url.php?form="+$form.attr('id'); //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
By passing this to the function you passing the whole form reference.
Hope it will help.
First, it should be:
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
The return keyword there is important.
Next, data: $(this).serialize(), //ID form should be:
data: $('#'+type_form).serialize(), //ID form
So, your script should look like this:
<script type="text/javascript" src="/path/to/jquery.min.js"></script>
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
<input type="text" name="name" class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
<div id="cargando"></div>
<script>
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
</script>

Form serialize issue

Here is my form's markup
<form name="contactForm" id="contactForm" role="form">
<div style="width: 190px">
<div class="form-group">
<input type="text" placeholder="fullname" name="fullname" id="formFullname" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="email" name="email" id="fromEmail" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="company" name="company" id="fromCompany" class="form-control">
</div>
</div>
<div class="clear"></div>
<div class="form-group">
<textarea placeholder="message" name="message" id="formMessage" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-success" type="submit" name="submit" id="formSubmit">send</button>
</form>
Using jquery 1.10.2
And here is JS
var form = $('#contactForm');
form.submit(function () {
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
I know that function fires, tested with alert. But console.log doesnt return anything, and during ajax call I don't see anything in POST (Watching with firebug's XHR).
BTW: role="form" is because i'm using Twitter Bootstrap framework
What am I doing wrong?
UPDATE
data: $(form).serialize() didn't help also
If you try this :
form.submit(function () {
console.log("form ", $(this).serialize());
return false;
});
it works just fine. So I think the problem
form.on('submit',function () {
event.preventDefault();
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $("form").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
Because $(this) in your code doesn't refer to the form but instead refers to jQuery on which the ajax method is called
Try the following code, but first modify your form HTML so that is has an "action" attribute. The nice thing about this code is that it can be used on any form which has a submit button and an action attribute. (i.e. it is not coupled to any specific IDs)
$(function() {
$('input[type="submit"]').click(function(event) {
event.preventDefault();
var form = $(this).closest('form');
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function() {
alert('Yay! your form was submitted');
})
.fail(function() {
alert('Uh oh, something went wrong. Please try again');
});
});
Cheers.

Categories