How to submit form using Ajax in MVC - javascript

I am getting problem to save my form data in the database. I am done small code on that which is shown below, when i enter data in form and click on my submit button it not work.
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form role="form" id="frm">
<div class="form-group">
<div class="col-sm-6 col-lg-12 col-md-12">
<div class="form-group">
<label for="name" style="color:black;">Product Name</label>
<input type="text" class="form-control" id="name"
placeholder="Product Name" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Date</label>
<input type="text" class="form-control" id="Text1"
placeholder="Date" style="color:black;">
</div>
<div class="form-group">
<label for="name" style="color:black;">Product Price</label>
<input type="text" class="form-control" id="Text2"
placeholder="Date" style="color:black;">
</div>
</div>
</div>
<button type="submit" class="btn btn-default" id="ok" >Submit</button>
</form>
Above is my code please give me solution on that

As I've checked you code, client side code is working fine, The only problem I can imagine in this case is you url path.
make sure you are providing correct url path.
You should check if its hitting the that page or not.

Which Framework you are using. Different framework has different syntax to pass the value in URL. Check the path you are getting in the page source page view in URL parameter or you can check the error in console log after the submit. It may be not getting the correct path of your action.

Make sure ajax library loaded successfully, and try to have alert messages to have forward step where you reached, have this test:
$(".btn").click(function(e) {
e.preventDefault();
var form = $("#frm");
$.ajax({
url: '/Form/Index',
data: form.serialize(),
type: 'POST',
success: function(data) {
},
beforeSend: function() {
alert('before send alert')
},
error: function (request, status, error) {
alert(error);
},
});
});
if beforeSend not executed so your issue is related to ajax library.

use this :
$("#ok").click(function(e) {
// your code
}
Refer to id in javascript rather than class attribute.
If you refer class attribute than once it has click javascript perform preventDefault on that class so that if not refresh your page, The button is not working.
Put preventDefault function at last of your function.

Remove the type="submit" from button
You have to get the form submit with id and serialize the form data
`
$("#formid").submit(function(e) {
var url = "urlpathtohandlerequest";
$.ajax({
type: "POST",
url: url,
data: $("#formid").serialize(),
success: function(response)
{
alert(response);
}
});
e.preventDefault(); // stops default submit.
});
`

Related

Submitting Form using jquery AJAX [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed last year.
I am trying to submit my form using jQuery ajax, but my data isn't posting to PHP it returns empty array nothing in $_POST array.
This is my code - here is my form:
<form action = "/webdevelopmentpakistan/send_mail.php" method = "post" class = "myForm" >
<div class="row">
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" id="fname" type="text" required name= "full_name" placeholder="Full Name"
/>
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" type="tel" required name = "phone" placeholder="+92" id="phone" onkeypress="return isNumberKey(event)" />
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" type="email" required name = "email" id="email" placeholder="Email"/>
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="btn popup" type="submit" name = "submit" value="CONTACT OUR CONSULTANT"/>
</div>
</div>
</div>
</form>
its an ajax part:
$('form').on('submit', function (e) {
e.preventDefault();
var url = $(this).attr("action");
var form_data = $(this).serialize();
$.ajax({
type: 'POST',
url: url,
data: $('.myForm').serialize() ,
dataType : 'JSON',
//contentType: "application/x-www-form-urlencoded",
success: function (data) { // here I'm adding data as a parameter which stores the response
console.log(data); // instead of alert I'm changing this to console.log which logs all the response in console.
},
error:function(xhr, textStatus, thrownError, data)
{
console.log("Error: " + thrownError);
console.log("Error: " + textStatus);
}
});
// var popup = document.getElementById("myPopup");
// popup.classList.toggle("show");
console.log(form_data);
});
PHP CODE using at other page:
if(isset($_POST)) {
echo json_encode($_POST);
}
and this is my serialize array which I am getting on submission of form but it isn't getting passed to php
full_name=talha&phone=012345678&email=admin%40gmail.com
welcome to stackoverflow, here are the changes, hope it will works
$.ajax({
type: 'POST',
url: url,
data: $('.myForm').serialize() ,
dataType : 'json', // changing data type to json
success: function (data) { // here I'm adding data as a parameter which stores the response
console.log(data); // instead of alert I'm changing this to console.log which logs all the response in console.
}
});
in php
if(isset($_POST)) {
echo json_encode($_POST);
}
this should print array of post parameters in your console, however you will get an array in php.
The form action needs to be either absolute url i.e. https://somewebsite.com or a relative url on you site so ideally it should be /some-url.php. Read about form action here
So your form opening tag should be,
<form action = "/web-development-in-pakistan.php" method = "post" class = "myForm" target="_self">
So in your javascript code when you do
var url = $(this).attr("action");
I also believe that in your ajax call, the type needs to be method, so,
$.ajax({
method: "POST",
.....
})

AJAX form only allows one submission?

I am creating a form which will be submitted through the use of jQuery AJAX, but I am for some reason only able to submit the form once. To submit again I have to refresh page?
How do i accomplish the form and script so I do not have to refresh?
Here is the form:
<form role="form" class="form-horizontal validate" name="create_form" id="create_form">
<div class="form-group">
<label class="col-sm-2 control-label" for="name">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="name" name="name" data-validate="required" data-message-required="Remeber to fill name" placeholder="">
</div>
</div>
<div class="form-group-separator"></div>
<div class="form-group">
<button id="submit_btn" class="btn btn-success">Create</button>
<button type="reset" class="btn btn-white">Reset</button>
</div>
</form>
And here is the AJAX part:
$(document).ready(function(){
$("#submit_btn").on("click", function () {
$.ajax({
type: 'POST',
url: 'data/create.php',
cache: false,
data: $('#create_form').serialize()
})
.done(function(data){
$("#name").val("");
})
.fail(function() {
console.log("ERROR");
});
// Prevent refreshing the whole page page
return false;
});
});
Hoping for help and thanks in advance :-)
use submit instead of click.
$('#submit_btn').on('submit', function(e) {
e.preventDefault();
... //rest of the code
});
I don't really see why you are wanting to run your script on document load. I would suggest you to include the script's source in the html and include an onClick attribute to the button element and then assign the event handler function call to it to be fired every time you click the Submit button.
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>

AJAX HTTP post request is triggered 3 times

In my webapp, the Ajax request is executed 3 times, and I have no idea why this is happening.
Can someone please help here?
My Javascript:
$(document).ready(function() {
console.log("ready!");
$('form').on('submit', function(e) { //
e.preventDefault();
// on form submission ...
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="perfid"]').val();
valueTwo = $('input[name="hostname"]').val();
valueThree = $('input[name="iteration"]').val();
console.log(valueOne)
console.log(valueTwo)
console.log(valueThree)
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'first': valueOne,'second': valueTwo,'third': valueThree},
success: function(data) {
var res = data.AVG;
var p = '<p><pre>'+res+'</pre></p>';
$('#result').append(p);
},
error: function(error) {
console.log(error)
}
});
}); });
And my HTML is:
<form role="form" method="post" onsubmit="return false;">
<div class="form-group">
<input type="text" class="input-medium" id="perfid" name="perfid" placeholder="Enter a Perf ID" required style="height:30px;">
<input type="text" class="input-medium" id="hostname" name="hostname" placeholder="Enter a HostName" style="height:30px;">
<input type="text" class="input-medium" id="iteration" name="iteration" placeholder="Enter a Iteration" required style="height:30px;">
<button type="submit" class="btn btn-default" style="height:30px;">Get Data</button>
</div>
</form>
I have written the code for only one AJAX POST request,
EDIT:
This is the console output:
Please make sure you have included the js file only once,
and add a return false at the end of the submit event callback
look at the selector
$('form').on('submit', function(e) {
if the page has 3 forms, the above selector will execute 3 times
Try to add id to the form like this. sorry about my bad english

Contact form using e.preventDefault(); not working live

UPDATE - the contact form is found at this URL.
I am trying to get the following contact form to function, using this tutorial.
I manage to get everything to work as expected on my computer using apache webserver.
After uploading the files to an online website, the ajax function does not kick in.
I seems like the e.preventDefault(); stops working after the upload, and the form is redirected to a new site,and not just being processed on the site without the reload.
I have also been trying to use the return false; instead of e.preventDefault(); without any success.
Her is my code:
.html
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
.js
$(function(){
$('form').submit(function(e){
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function(){
//Display the "loading" message
$("#loading").fadeIn(function(){
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data){
//Hide the "loading" message
$("#loading").fadeOut(function(){
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
})
Please help!
That's because your JS is missing a closing });. Please check this demo to confirm that the default action is indeed prevented and the ajax does kick in. However, I was expecting a POST but instead I am seeing an OPTIONS request.
NOTE: Giving an element a name or id attribute value of submit is bad practice. You cannot for example use JavaScript to submit the form via default form submission -- this.submit() or $('form')[0].submit() without getting the error ...submit() is not a function .....
$(function() {
$('form').submit(function(e) {
var thisForm = $(this);
//Prevent the default form action
//return false;
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$("#loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$("#loading").fadeOut(function() {
//Display the "success" message
$("#success").text(data).fadeIn();
});
}
});
});
});
});
}); // <==== MISSING THIS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method="post" action='mail/mail.php'>
<label>Name</label>
<input name="name" id="name" placeholder="Name.." required="true" class="input-field">
<label>Mail</label>
<input type="email" name="email" placeholder="Mail.." required="true" class="input-field">
<label>Msg</label>
<textarea name="message" id="message" class="textarea-field" required="true"></textarea>
<input type="submit" id="submit" name="submit" value="Send">
</form>
<div id="loading">
Sender melding...
</div>
<div id="success">
</div>
Since you are submitting via AJAX anyway, you may find it easier to change your input type to button, and bind to click instead of form submit, to avoid the default submit behaviour you are trying to circumvent.

Single click event acts as double click event

I'm using Ajax to submit the login form without refreshing the page. I've added a function to see whether the data returns 'error' (which comes up when the user enters an incorrect email/password). If it does not return 'error', the user has been logged in and will be transferred to the page within 2 seconds.
The problem is that my button acts like a double-click button and I cannot see why. This is my JS file:
$(function() {
$("#goLogin").click(function() {
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
});
function finishLogin( data , textStatus ,jqXHR ) {
if ( data == "error" ) {
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
} else {
$('.succesMsg').fadeIn(500).show();
$('.errorMsg').fadeOut(300).hide();
setTimeout("location.href = 'protected.php';",2000);
}
}
I've tried placing it between the document_ready tags, but that isn't working either.
Part of the HTML code:
<div class="login form">
<div class="login-header">Please Login</div>
<form method="post" id="loginForm" name="form">
<label for="email" class="short">Email*</label>
<input type="text" name="email" id="email" class="required" placeholder="" />
<label for="password" class="short">Password *</label>
<input type="password" name="password" id="password" class="required" placeholder="" maxlength="15" />
</form>
<div id="login-functions">
<div class="loginbtn-container">
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Login" />
</div>
<div class="login form actions">
<p class="register account">Register an account</p>
<p class="request password">Lost your password?</p>
</div>
</div>
</div>
<div class="errorMsg">Incorrect. Please recheck your details</div>
<div class="succesMsg"><b>You've been logged in!</b> Please wait while we transfer you</div>
$('.errorMsg').fadeIn(500).hide();
$('.succesMsg').fadeOut(300).hide();
did you mean tto hide both? I see the click is working fine, though you should ideally do submit
Take your submit inside the form, and prevent normal form submit using preventDefault()
$("#goLogin").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});
Please move your submit button inside the form closing tag first
<input type="submit" id="goLogin" name="goLogin" class="button green" value="Inloggen" />
The above button is placed after the </form> tag.
Because you click on input type submit and progress Ajax on it; it cause submit 2 times.
To avoid it, you can use as Zach Leighton said above ; or use as below
$("#goLogin").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "db-requests/db-login.php",
data: $("#loginForm").serialize(),
success: function(data,textStatus,jqXHR){ finishLogin(data,textStatus,jqXHR); }
});
});

Categories