Submit form using JS and AJAX - javascript

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'),

Related

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
};

How to get jQuery to submit a form to a post

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);
}
}
});
});

How to wisely redirect after successful ajax login?

I have a method calling ajax and after success I need to redirect to another page.
I think when ajax call ends my URL is by default changed, ending with my username and password which I have posted in the ajax call.
How to wisely handle this? I am not in a situation to remove async false and I know I can send password and username using ajax given keys.
function Login() {
var model = { user_Name: $("#username").val(), Password: $("#password").val() };
$.ajax({
async: false,
url: 'http://localhost:51525/api/HomeApi/',
type: 'POST',
data: JSON.stringify(model),
dataType: "json",
success: function (data) {
alert("Function is successfully returned now redirect");
//how to redirect??
//window.location.href = 'http://localhost:51525/user/';
//window.location.href = '#Url.Action("Index","User")';
}
});
}
The reason that your url shows the username and password is because you are triggering the form submit with the default method="GET".
There are lots of alternatives. E.G.:
Return false from your Login. This will disable the form submit.
function Login() {
//Your code...
return false;
}
Or
Don't use ajax at all, and use a normal form post:
<form method="POST" action="/api/HomeApi/">
Additionally, there are other ways a user might submit the form so <form onsubmit="Login()"> is probably better than <input onclick="Login()">

Send form data with jquery ajax json

I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.

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