How to get jQuery to submit a form to a post - javascript

I have a form that I am validating with jQuery.
<form id="target" class="center-block" action="/" method="POST">
<textarea class="form-control" id="name" rows="3" name="name" placeholder="Enter a burger you would like to devour!"></textarea>
<button type="button" id="submit" class="center-block btn btn-default top">Submit</button>
</form>
After validation I am also trying to submit the form via jQuery.
if (validateForm() == true) {
$("#target").submit();
}
The validation is working however, it doesn't seem like the form is submitting to the post route. I was able to get the form to post using ajax, but the post wouldn't redirect after finishing. Was hoping this method would give the desired effect.
The app is running on Express and using MySQL.

I don't think your jquery submit will work ,because an element id or name submit will replace the form.submit method, you should simply change id (name also shouldn't give that).
<button type="button" id="changeThisId" class="center-block btn btn-default top">Submit</button>

Use Ajax and if you want to redirect to the current page, on success reload the current page
$.ajax({
url: yourUrl,
type: "post",
data: $("#target").serialize(),
success: function(r){
//form posted successfully
window.location.reload();
},
error: function(error){
alert(error);
}
});

I might have a typo in there, but the idea is:
$('#target').submit(function(event){
event.preventDefault();
}).validate({
rules: { ... },
submitHandler: function(form){
$.ajax{
type: 'POST',
data: $(form).serialize(),
url: '/',
success: function(result){
console.log(result);
}
error: function(err){
console.log(err.message);
}
}
});
});

Related

i want to send file to api url and get the response without redirecting to it using ajax

the code below is form with action api link
and thats my ajax request
$('#form1').submit(function(e) {
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: formdata,
success: function(data) {
alert(data);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://www.example.com/uploader" id="myForm" method="post" name="myForm">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
when i send a file to that api it respond with data i want to get this data without redirecting to it this code in wordpress site
You need to add enctype in form tag and use preventDefault to prevent the refresh of page.
You need to serialize the data and send in data.
On the success area you need to deal with response.
HTML
<form action="http://www.example.com/uploader" id="form1" method="post" name="myForm" enctype="multipart/form-data">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
JS
$('#form1').submit(function(e){
e.preventDefault();
let data = $( this ).serialize()
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: data,
success: function(response){
// success action here
},
error: function(response) {
// error action here
}
});
});
You just need to add the following code to your function in your submit event.
e.preventDefault();
because, normally it would submit the form.

I want to get my textbox values from HTML document and post those when submit button is pressed using Json file in node JS

This is my JS file:-
$(document).ready(function(){
$('form').on('submit', function(){
var email = $("form input[type=text][name=emails]").val();
var todo = {email: email.val(),
pass:dat.val()};
$.ajax({
type: 'POST',
url: '/project',
data: todo,
success: function(data){
//do something with the data via front-end framework
location.reload();
}
});
return false;
});
});
This is my html document:-
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="/assests/todo-list.js"></script>
<body>
<form>
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="emails" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</head>
</html>
I want that when i click submit button value from both text boxes gets saved in my database(using Mlab),for that i am using a json file to fire post request to the server.
My main post request handler:-
app.post('/project',parser,function(req,res)
{
var register=Todo(req.body).save(function(err,data)
{
if(err) throw err
res.json(data);
});
});
EDIT:-
I removed my Javascript file and now i am directly posting the form using and i am able to save my email address but not the password.
This is my main code now :-
app.post('/views/register',parser,function(req,res)
{
var data={
email:req.body.emails,
password:req.body.passcode
};
var send=Todo(data).save(function(err)
{
if(err) throw err
res.render('login')
})
});
If I understand your question right, you're missing the contentType param.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
...
then try again.
I was not following the correct schema for the database when creating the object
var data={
email:req.body.emails,
password:req.body.passcode
};
The property name was pass and i was using password that's why it was not inserting the password.
var data={
email:req.body.emails,
pass:req.body.passcode
};

Redirection after successful form submit

I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.
What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.
By now I have the following code:
Submit button:
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
</div>
</div>
Also I have the following js function to submit the form and to redirect me to another page:
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.
How can I solve this problem? I only want to be redirected when all required fields are not empty.
You should bind to the submit event, not click event:
UPDATED TO MATCH THE COMMENTS
$(function () {
var submityesClicked;
//catch the click to buttons
$('#submityes').click(function () {
submityesClicked = true;
});
$('#submitno').click(function () {
submityesClicked = false;
});
$('#webform').submit(function (e) {
e.preventDefault();//prevent the default action
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
},
error: function () {
alert("error");
}
});
});
});
The submit event is triggered only if the form is valid.
Note that the submit event is triggered by the form but the click event is triggered by the input element.
Do redirection on complete. Not on success
$('document').ready(function () {
"use strict";
$(function () {
$('#submityes').click(function () {
$.ajax({
type: "POST",
/* url: "process.php", //process to mail
data: $('form.contact').serialize(), */
success: function (msg) {
//window.location.replace("/submit_resolved.php");
},
complete: function () {
window.location.replace("/submit_resolved.php");
},
error: function () {
alert("error");
}
});
});
});
});
I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
check this link: Return errors from PHP run via. AJAX?
Hope this may be helpful to you.
The simplest thing you can do is to add "required" attribute to you input elements.Example:
<form action="/action_page.php">
Username: <input type="text" name="usrname" required>
<input type="submit">
</form>
It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:
http://caniuse.com/#search=required
Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<form action="">
Username: <input type="text" id="usrname" required>
<button type="button" name="submityes"
id="submityes" class="btn btn-danger">Submit</button>
</form>
</div>
function isValid(){
var usrname = $("#usrname").val();
if(usrname == ""){
return false;
}
return true;
}
$(function () {
$('#submityes').submit(function () {
if(isValid() == true){
$.ajax({
type: "POST",
/*url: "process.php", //process to mail
data: $('form.contact').serialize(),*/
success: function (msg) {
alert("success");
window.location.replace("/submit_resolved.php");
},
});
}else{
alert("error");
}
});
});

Submit form using JS and AJAX

I have little problem with JS and AJAX, i dont know this languages. I know php and i have applied for position php developer, now i have some tasks to do and i stucked at one. It is simple task, form, submit, process information, store in DB, and send. Only problem is i have to use AJAX to submit form, i done little research and somehow i made wrote this code but it doesnt work.
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="submit" value="Submit" id="submit">
</form>
Send messages from database
</div>
<script>
$(document).ready(function() {
// When click on button store values from form fields into variables
$("form").submit(function(event) {
event.preventDefault();
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: ("#form").attr('action');
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
return false;
});
});
</script>
</body>
IN form can i use input type button instead of submit (so no need for preventDefault in JS) and in JS i do it
$("#submit").click(function.....
I think i have tried all combinations and when form is submited it goes with default, no JS activated...
SOLVED: problem was in IF statment, content="" instead of content=="", OMG how i overlooked that...
To answer your questions, yes you are right, you can use an input of type button and you don't necessary need to depend on submitting the form. Here is how you'd write it without form submission:
<div>
<form method="POST" action="add.php" id="form">
<input type="email" name="email" id="email" value="Email">
<textarea name="content" id ="content">Message</textarea>
<input type="button" value="Submit" id="submit" onclick="SendAjax();">
</form>
Send messages from database
</div>
<script>
// When click on button store values from form fields into variables
function SendAjax() {
var email = $("#email").val();
var content = $("#content").val();
// Check if fields are empty
if (email=="" || content=="") {
alert("Please fill all fields");
}
// AJAX code to submit form
else {
$.ajax ({
type: "POST",
url: "type your URL here",
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
}
}
</script>
As you can see, I prefer to specify the URL in AJAX instead of taking it from the form's action which I sometimes have it set to a different URL from the AJAX. However, if you want to take the URL from the form's action, then fix that line in your code to be:
url: $("#form").attr('action'),
Use the serialize() method (described bellow) instead of manually getting the value of each field of your form in order to build the JSON object.
$('#form').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function() {
alert("Data successfully forwarded to add.php");
}
});
return false;
});
You have a syntax error in your ajax call.
$.ajax ({
type: "POST",
url: ("#form").attr('action'); // This is bad JSON
data: { "email": email, "content": content},
cache: false,
success: function() {
alert("Data successfully forwarded to add.php");
}
});
Replace that line with:
url: $("#form").attr('action'),

Subscribe Form using Ajax

I'm really clueless as to how to get this done.
I need to make a subscribe with email button and it needs to be validated and show a little message for success, Loading ands Error.
I have never worked with Ajax before and this is what I have to do, I have To complete the newsletter subscribe ajax-functionality using a pre-defined controller in a php file on the server called newsletter.php and the I should use the controller function named subscribe in there to generate the response for the ajax request.
If that makes any sense please help me out.
This is my form for the email address
<div id="subscribeText">
<form action="" method="post" name="ContactForm" id="ContactForm" >
<input type="submit" name="subscribeButton" id="subscribeButton" value="Submit" />
<input type="text" name="subscribeBox" id="subscribeBox" value="Enter your email address..." size="28" maxlength="28" onFocus="this.value=''" />
</form>
</div>
http://jsfiddle.net/vaaljan/R694T/
This is what the success should look like and error and loading pretty much the same.
What the success message looks like
Hope this isn't too far fetched, I have not worked with java script that much yet but I understand more or less.
Thanks
I have made a small example on jsfiddle.
$('#send').click(function (e) {
e.preventDefault();
var emailval = $('input#email').val();
console.log(emailval);
if (emailval !== "") {
$.ajax({
cache: false, // no cache
url: '/echo/json/', // your url; on jsfiddle /echo/json/
type: 'POST', // request method
dataType: 'json', // the data type, here json. it's simple to use with php -> json_decode
data: {
email: emailval // here the email
},
success: function (data) {
console.log(data);
$('<strong />', {
text: 'Successfull subscribed!'
}).prependTo('#state');
},
error: function (e) {
$('<strong />', {
text: 'A error occured.'
}).prependTo('#state');
},
fail: function () {
$('<strong />', {
text: 'The request failed!'
}).prependTo('#state');
}
});
} else {
alert("Insert a email!");
}
});
Here it is.
It uses jQuery for the ajax request.
The example shows how ajax works.

Categories

Resources