How to post mutliple forms from a webpage - javascript

I want to post 2 forms using javscript, but I can't seem to figure it out. Can someone help me?
It seems like I need to submit the first form Async according to this but I don't follow their code: Submit two forms with one button
HTML
<form name="form1" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" target = "me1">
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<form name="form2" action="https://test.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST" >
<input type="hidden" name="oid" value="00Df00000000001" />
</form>
<input name="submit" value="Submit Form" onclick="submitForms ()" type="button">
JS
function submitForms(){
document.forms["form1"].submit(); /* should be Async?*/
document.forms["form2"].submit();
}

var str1 = $( "form1" ).serialize();
var str2 = $( "form2" ).serialize();
ajaxReq(url,str1);
ajaxReq(url,str2);
function ajaxReq(url,data){
var request = $.ajax({
url: url,
type: "POST",
data: data,
dataType: "html"
});
request.done(function(html) {
console.log('SUCCESS')
});
request.fail(function( jqXHR, textStatus ) {
console.log("AJAX REQUEST FAILED" + textStatus);
});
}

Related

How to check if submitting form with jQuery if successful?

I have following codes as form, and I wanted to check if the form is been successfully submitted.
I was wondering how I can check on the console. I want to check if the form is been successfully submitted so I can display another form.
<form id="signup" data-magellan-target="signup" action="http://app-service-staging.com" class="epic_app-signup" method="POST">
<div class="grid__column " style="width: 100%;">
<input type="text" name="first_name" placeholder="Name" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="password" placeholder="Password" required/>
</div>
<div class="grid__column " style="width: 100%;">
<input type="text" name="confimred-password" placeholder="Confirmed password" />
</div>
<div class="grid__column " style="width: 100%;">
<input type="date" name="startdate" id="startdate" min="2019-12-16">
</div>
</div>
<button type="submit" class="grid__column" style="width: 50%;"></button>
</div>
</div>
</div>
</form>
and the script,
$('.epic_app-signup').on('submit', function(e) {
e.preventDefault();
var formData = $('.epic_app-signup').serializeArray();
var jsonData = {};
formData.forEach(function(item, index) {
jsonData[item.name] = item.value;
});
console.log('data\n', jsonData);
$.ajax({
url: 'http://app-service-staging.com/api/auth/register',
type:'POST',
data: jsonData,
contentType: 'application/json'
}).done(function(data, textStatus, jqXHR) {
if (textStatus === 'success') {
}
});
});
});
you can do this by various ways currently you are not using ajax request if you want to achieve this without ajax let follow these steps
when user click on submit button your form is submitted received form information(you define the path in action attribute where form submitted) after processing successfully redirect toward a new form
second solution use jquery ajax request
//first form
<form action='test.php' id='form_1' method='post'>
<label>Full Name</label>
<input type='text' name='full_name'>
<input type='submit'>
</form>
//second form
<form action='test.php' id='form_2' method='post' style='display:none'>
<label>Father Name</label>
<input type='text' name='father_name'>
<input type='submit'>
</form>
use jquery cdn
<script src='https://code.jquery.com/jquery-git.js'></script>
<script>
$("#form_1").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert("form submitted successfully");
$('#form_1').hide();
$('#form_2').show();
},
error:function(data){
alert("there is an error kindly check it now");
}
});
return false;
});
</script>

How do I make a success alert appear after correct submission in javascript

I want to show the user a form sent correctly alert message with javascript using bootstraps built in alerts.
When I run the code I get the object array of the values (inspecting the page at console log). what I want to do is after it is sent, to display a success alert (if it is a success).
there is test4.sj which contains the javascript code and then there is main.php which is the code for the form.
The code that I have so far is in the snippet.
$('form.ajax').on('submit', function() {
var that = $(this),
type = that.attr('action'),
data = {};
that.find('[name]').each(function(index, value) {
//console.log(value);
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data);
/* $.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
})*/
return false;
})
<body>
<form method="post" class="ajax">
<div>
<input name="name" type="text" placeholder="Your name" required>
</div>
<div>
<input name="lName" type="text" placeholder="Your Last Name">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
</div>
<input type="submit" value="Send">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
Just add hidden alert panel and show it on AJAX success.
HTML:
<form method="post" class="ajax">
<div class="alert alert-success js-alert hidden" role="alert">
Form was successfully sent!
</div>
...
<div>
<input name="name" type="text" placeholder="Your name">
</div>
...
<button type="submit" class="btn js-btn">Send</button>
</form>
JS:
$('form').on('submit', function( event ) {
var $form = $( this );
event.preventDefault();
$('.js-alert').addClass('hidden');
$('.js-btn').button('loading');
$.ajax({
url: '/someurl',
type: 'POST',
data: $form.serialize(),
success: function(response){
$('.js-alert').removeClass('hidden');
$('.js-btn').button('reset');
}
});
});
Check the fiddle:
https://jsfiddle.net/xw63db57/1/
you can use ajax jqXHR status and statusCode and based up on that you can write the alert code
success(data, textStatus, jqXHR){
var statusCode = jqXHR.status;
var statusText = jqXHR.statusText;
}

jQuery validation not work in Ajax Form Submit

I submit my form using jQuery $.post method and need to validation form using jQuery validation plugin like this :
HTML :
<form name="myform" id="myform" action="send.php">User:
<input type="text" value="" name="user" />
<br/>Password:
<input type="password" name="password" value="" />
<input type="hidden" name="xyz" value="123" />
<input type="hidden" name="submit" value="true" />
<?php $token=N oCSRF::generate( 'csrf_token' );?>
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
</form>
<button class="btn btn-info" id="ajax-form-1">Run Code</button>
<div id="ajax-form-msg1"></div>
JS:
$('#myform').validate({
rules: {
user: {
required: true
},
password: {
required: true
}
},
submitHandler: function (form) {
$("#ajax-form-1").click(function () {
$("#ajax-form-msg1").html("<img src='loading.gif'/>");
// var formData = $("#myform").serialize(); //or
var formData = $("#myform").serializeArray();
var URL = $("#myform").attr('action');
$.post(URL,
formData,
function (data, textStatus, jqXHR) {
$("#ajax-form-msg1").html('<pre><code class="prettyprint">' + data + '</code></pre>');
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
});
});
}
});
In action, jQuery validation not work with my form. how do fix this ?
DEMO : http://jsfiddle.net/fcuswvf1/2/
You are binding the click handler on the button inside the submitHandler. This way, when a user clicks the button, the click event doesn't fire. You can simply remove the click handling lines from the 'submitHandler, so that the code inside is called directly wheneversubmitHandler` is triggered.

jQuery AJAX submitting not working

I'm having trouble with a jquery ajax submit form. Here's the jquery code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString,
});
return false;
});
});
</script>
and here is the form code:
<form name="form" method="post" action="">
<input type="hidden" id="machine_id" name="machine_id" value="5">
<input type="text" id="number" name="number"></input>
<input class="btn btn-small btn-success" type="submit" class="submit" id="submit" name="submit" value="submit">Submit</input>
</form>
And the code of updatetextdatabase.php:
<?php
date_default_timezone_set('America/New_York');//set time zone
$con=mysqli_connect('saslaundry.db.10410357.hostedresource.com', 'saslaundry', 'password', 'saslaundry');//establish connection
// Check connection
if (mysqli_connect_errno())//ping database to check connection
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();//error message
}
mysqli_query($con,"INSERT INTO textrequests VALUES('$_GET[number]', '$_GET[machine_id]') ");
return;
?>
But not only is it not submitting the form, the page also reloads, which is sort of what I was trying to avoid by using AJAX. I feel like the problem is that the function is not being called by the submit button, but I can't figure out why.
Thanks!
try this one use e.preventDefault(); prevent your form to submit and then perform your ajax call
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
e.preventDefault();
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString,
success: function (data) {
//do something here when you got the response
}
});
});
});
</script>
event.preventDefault
I made this working fiddle:
HTML:
<form name="form" method="post" action="">
<input type="hidden" id="machine_id" name="machine_id" value="5" />
<input type="text" id="number" name="number" />
<input class="btn btn-small btn-success" type="button" class="submit" id="submit" name="submit" value="submit" />
</form>
Jquery:
$(document).ready(function(){
$("#submit").click(function() {
var number = $("#number").val();
var machine_id = $("#machine_id").val();
var dataString = 'number='+ number + '&machine_id=' + machine_id;
$.ajax({
type: "POST",
url: "http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php",
data: dataString
});
});
});
Network Console:
Request URL:http://www.onmsgmedia.com/hurryitUP/updatetextdatabase.php
Request Headersview source
Accept:*/*
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Origin:http://fiddle.jshell.net
Referer:http://fiddle.jshell.net/WJGhr/show/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36
Form Dataview sourceview URL encoded
number:25
machine_id:5
Here is the fiddle: http://jsfiddle.net/WJGhr/

Ajax is giving me an error when I send data

I am trying to submit a form by Ajax but I am unable to . I have multiple forms and I am using (this) to submit the data. I am getting the error From error:0 error.The alert messages are showing me that I have the value.
<script type="text/javascript">
$(document).ready(function() {
$(".submitform").click(function (){
alert ($(this).parent().serialize());
$.ajax({
type: "POST",
url: "reply_business.php",
timeout:5000,
data: $(this).parent().serialize(),
beforeSend: function(xhr){
$('#load').show();
},
success: function(response){
$(this).parent().find('.sentreply').append(response);
$('.sentreply div:last').fadeOut(10).fadeIn(2000);
//uncomment for debugging purposes
//alert(response);
},
error: function(jqXHR) {
alert ('From error:' + jqXHR.status + ' ' +jqXHR.statusText);
},
complete: function(jqXHR, textStatus){
//uncomment for debugging purposes
//alert ('From complete:' + jqXHR.status + ' ' +jqXHR.statusText + ' ' + textStatus);
$('#load').hide();
}
});
});
});
</script>
I am creating the form below by the PHP code
foreach ($array['business_ids'] as $business)
{
?>
<form >
<input type="hidden" name="b_id" value="<?php echo $business ; ?>" />
<input type="hidden" name="c_id" value="<?php echo $sqlr['conversation_id']; ?>" />
<input type="hidden" name="q_id" value="<?php echo $sqlr['query_id']; ?>" />
<input type="hidden" name="u_id" value="<?php echo $sqlr['u_id']; ?>" />
<textarea name="reply">Type the reply here.</textarea>
<input type="submit" class="submitform" value="Submit">
</form>
<?php
}
I do not understand why Ajax isn't able to send the data.
Without seeing the markup or the network traffic, we can only guess. Perhaps $(this).parent() isn't the form?
It's typically safer to attach $(form).submit() than $(button).click() for this reason and because $(button).click() doesn't capture form submit by hitting the enter key.
Edit Here's an example:
<form id="theform">
<input type="text" id="thetext" name="thetext" />
<input type="submit" value="send" />
</form>
<form id="anotherform">
<input type="text" id="anothertext" name="anothertext" />
<input type="submit" value="save 2" />
</form>
<script>
$(document).ready(function () {
$("#theform").submit(function (e) {
var data = {
thetext: $("#thetext").val()
};
$.ajax("/the/server/url", {
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function (r) {
alert("done");
}
});
// Technically you need only one or the other
e.preventDefault();
return false;
});
});
</script>
You seem to have submitted the form after starting the Ajax request - and when the page is unloaded, the request is cancelled. Since your form has no action, the submit will just reload the current page so you might not notice it.
To prevent this, you will need to preventDefault() the catched event. Also, you should not handle just click events on submit-buttons, but rather the submit-event of the <form> itself.

Categories

Resources