How do I automatically submit two forms without the page refreshing? - javascript

<form id="addToCart" action="http://my-website/cart/action.php">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
document.forms[1].submit();
</script>
This only submits the first form but not the second. How can I get it to submit both?
Before anyone asks, I also tried this below and it still didn't work.
document.getElementById("addToCart").submit();
document.getElementById("buy").submit();

In order of preference
Submit all data to action and have that add AND buy
Use ajax, submit the second form in the success of the first submit
const url = "https://my-website/cart/action.php";
document.getElementById("container").addEventListener("click", e => {
const itemNum = e.target.dataset.itemnum;
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
action: "add",
itemNum: itemNum
})
})
.then(() => {
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
action: "buy",
itemNum: itemNum
})
})
})
});
<div id="container">
<input type="button" data-itemnum="201" value="Buy 201 with one click " />
<input type="button" data-itemnum="202" value="Buy 202 with one click " />
<input type="button" data-itemnum="203" value="Buy 203 with one click " />
</div>
Two iframes (don't change the fields or methods, only the value of action):
<form id="addToCart" method="post" action="http://my-website/cart/action.php" target="iframe1">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php" method="POST" target="iframe2">>
<input type="hidden" name="action" value="buy" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<iframe name="iframe1"></iframe>
<iframe name="iframe2"></iframe>
<script>
document.forms[0].submit();
setTimeout(() => document.forms[1].submit(),2000);
</script>

This would be my approach. Use jquery ajax to define a .submit() function for each form (the procedure to follow when submitted). Use .click() to "click" both submit buttons programmatically. Then use return false to prevent page refresh. This should submit both forms simultaneously. I was unable to test this without the php actions.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addToCart" action="http://my-website/cart/action.php" method="get">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="post">
<input type="submit" value="Submit request" />
</form>
<script>
$(document).ready(function() {
const $addToCartForm = $("#addToCart");
const $buyForm = $("#buy");
const addToCartUrl = $("#addToCart").attr("action");
const buyUrl = $("#buy").attr("action");
$buyForm.submit(function() {
$.ajax({
url: buyUrl,
type: $buyForm.attr("method"),
data: $buyForm.serialize()
});
return false;
});
$addToCartForm.submit(function() {
$.ajax({
url: buyUrl,
type: $addToCartForm.attr("method"),
data: $addToCartForm.serialize()
});
return false;
});
$addToCartForm.find("[type='submit']").click();
$buyForm.find("[type='submit']").click();
});
</script>

you can use AJAX with JQuery $.post() method for submitting both forms simultaneously.
$(document).ready(main);
function main(){
submitFormUsingAjax('#addToCart');
submitFormUsingAjax('#buy');
}
function extractInputDataOfFromRef(formSelector){
var $inputRefs = $(formSelector +' input:not([type=submit])');
var data = {};
$inputRefs.each(function($index){
var name = $(this).attr("name");
var value = $(this).attr("value");
data[name] = value;
})
return data;
}
function submitFormUsingAjax(formSelector){
var $formRef = $(formSelector);
var url = $formRef.attr('action');
var data = extractInputDataOfFromRef(formSelector);
var method = $formRef.attr('method');
method = method && method.toUpperCase();
var posting;
if(method == 'GET'){
posting = $.get(url,data);
}else{
posting = $.post(url,data)
}
posting.done(function(response) {
console.log("form submitted: ",response);
});
posting.fail(function(error) {
console.log("form submittion failed:",error.statusText);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addToCart" action="http://my-website/cart/action.php" method="get">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
<input type="submit" value="Submit request" />
</form>

document.forms[0].onsubmit = (e) => {
e.preventDefault();
}

Related

Laravel dynamic form input text and upload file

I have a problem when I add input type="file" to the dynamic form insert
all works before I tried to add input type="file"
also, I got no error message on the browser
addMore.blade.php
<form name="add_name" id="add_name" enctype="multipart/form-data">
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button> //add dynamically input
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
here the ajax
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
});
//note the dynamic add input filed button already works #add
//already tried remove serialize() still not work
//also i got no error message on the browser
here the HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal')->store('proposals'); //already change to ->file(proposal[]) not work
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}
you are using serialize while sending data via ajax, you need to pass FormData with ajax.
Below is a complete code for sending file with ajax, and also you can trigger event when form is submitted so you can get entire formdata:
<form name="add_name" id="add_name" enctype="multipart/form-data" action="home" method="post">
#csrf
<input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" />
<input type="file" name="proposal[]" id="proposal" class="form-control name_list" />
<button type="button" name="add" id="add" class="btn btn-success">Add More</button>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$('#add_name').submit(function(e) {
e.preventDefault();
var form = $(this);
var formData = new FormData(this);
$.ajax({
url: form.attr('action'),
method: "POST",
data: formData,
type: 'json',
processData: false,
contentType: false,
success: function(data) {
if (data.error) {
printErrorMsg(data.error);
} else {
i = 1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display', 'block');
$(".print-error-msg").css('display', 'none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
// location.href = "http://www.example.com/ThankYou.html"
}
}
});
return false;
});
</script>
HomeController.php
public function addMorePost(Request $request){
$name = $request->name;
$proposal = $request->file('proposal');
foreach ($proposal as $file) {
$file->store('proposals');
}
for ($count = 0; $count < count($name); $count++) {
$data = array(
'name' => $name[$count],
'proposal' => $proposal[$count] //already change 'proposal[]' but not work
);
TagList::create($data);
}
return response()->json(['success' => 'done']);
}

Angular Form Trouble Binding to Scope

I have a simple Angular form with a textbox and some hidden fields. This form is recycled many times on my page.
<form accept-charset="UTF-8" name="form.jobAppForm" class="pitch-form" novalidate>
<div style="display:none;">
<input name="authenticity_token" type="hidden" ng-value="window._token">
<input name="user_id" type="hidden" ng-value="<%= current_user.id %>">
<input name="job_description_id" type="hidden" ng-value="j.id">
<input name="company_id" type="hidden" ng-value="j.company_id">
</div>
<div class="form-group">
<textarea class="apply-textbox" id="pitch" name="pitch" ng-model="jobApp.pitch"></textarea>
</div>
<input class="apply-submit-btn" name="commit" type="submit" value="Submit Application" ng-click="createApplication(jobApp)" onClick="this.disabled=true;this.value='Sending…';">
</form>
In my controller I have a newApplication method that initializes $scope.jobApp and then a createApplication method that sends a post request to the server. If I log the value of $scope.jobApp when createApplication is called, all the attributes are still set to null. Only the pitch attribute seems to be bound. If I enter a pitch, that is bound to the scope, but nothing else is. I'm not sure what I'm missing. Why is pitch bound but none of the other attributes? Here are my controller methods.
$scope.newApplication = function() {
console.log('new app')
$scope.form = {}
$scope.jobApp = {
token: null,
user_id: null,
job_description_id: null,
company_id: null,
pitch: null
};
};
$scope.createApplication = function() {
var jobAttributes = $scope.jobApp;
console.log(jobAttributes)
if ($scope.form.jobForm.$valid) {
$http({
method: 'POST',
url: '/applications',
data: jobAttributes,
headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}
}).success(function(data, status){
console.log('success');
}, function(err){
alert("Failed to save job! Server responded with: " + err)
});
};
}
Note: I've tried setting ng-model="jobApp.attribute" for the other attributes as well as using value= rather than ng-value= to no effect.
like #HaukurHaf, you need to use ng-model on the form field.
<form accept-charset="UTF-8" name="form.jobAppForm" class="pitch-form" novalidate>
<div style="display:none;">
<input name="authenticity_token" type="hidden" ng-model="jobApp.token">
<input name="user_id" type="hidden" ng-model="jobApp.user_id">
<input name="job_description_id" type="hidden" ng-model="jobApp.job_description_id">
<input name="company_id" type="hidden" ng-model="jobApp.company_id">
</div>
<div class="form-group">
<textarea class="apply-textbox" id="pitch" name="pitch" ng-model="jobApp.pitch"></textarea>
</div>
<input class="apply-submit-btn" name="commit" type="submit" value="Submit Application" ng-click="createApplication(jobApp)" onClick="this.disabled=true;this.value='Sending…';">

Sending values to the action script continuously. How to do that?

I want to repeatedly send values of username and password to the php script. How do I do this ? Like to send the values to the action script, we use submit button but how can I send the values automatically to the script and that too continuously ?
<form method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
Using the jQuery form plugin you can do the following:
setInterval(function() {
$('form').ajaxSubmit();
}, 1000);
Another solution is to target the form to an iframe so if you submit the form, it doesn't reload the page:
HTML:
<form id="myform" method="post" action="processor.php" target="frm">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<iframe name="frm" id="frm"></iframe>
JS:
var form = document.getElementById('myform');
setInterval(function() {
form.submit();
}, 1000);
try something like this
JAVASCRIPT
<script language=javascript>
var int=self.setInterval(function(){send_data()},1000);
function send_data()
{
document.getElementById('my_form').submit()
}
</script>
HTML
<form method="post" id="my_form" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
</form>
<form id="myform" method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<script type="text/javascript">
var count=100,i=0;
for(i=0;i<count;i++) {
document.getElementById('myform').submit();
}
</script>
This will submit the form 100 times
Use Ajax, it's really easy with jQuery. To send the form data to the processor.php script:
var sendForm = function () {
$.ajax({
type: 'post',
url: 'processor.php',
dataType: 'JSON',
data: {
username: $('#username').val(),
password: $('#password').val()
},
success: function (data) {
// do something with the answer from server?
},
error: function (data) {
// handle error
}
});
}
So, sendForm is a function that sends the form data to the server. Now, wee need to set a timer that will invoke it repeatedly:
window.setInterval(sendForm, 1000); // sends form data every 1000 ms
You may you $.post or $.get or $.ajax request repeatedly to send continuous request.
$(document).ready(function(){
setInterval(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
//your code what you want to do of response
alert(response);
});
}, 1000);
});
and html code is like following
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>
This is a full HTML file doing what you want, read the comments.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post" action="processor.php">
<input type="username" id="username" value="suhail" />
<input type="password" id="password" value="secret_code" />
<input type="submit" />
</form>
<script>
function send_request(username, password) {
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
// You can check if the login is success/fail here
console.log(response);
// Send the request again, this will create an infinity loop
send_request(username, password);
});
}
// Start sending request
send_request($('#username').val(), $('#password').val());
</script>
Try this,
JS:
$(document).ready(function(){
var int=self.setInterval(function(){statuscheck()},1000);
function statuscheck()
{
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type:"post",
url:"processor.php",
dataType: "html",
cache:false,
data:"&username="+username+"&password="+password,
success:function(response){
alert(response);
}
});
}
});
HTML:
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>

Hide and Show in angularjs

I am new in angularJs .
This is my bit level view
<input type="text" ng-model="todoName" size="30"
placeholder="Add Your Name">
<input type="text" ng-model="todoAge" size="30"
placeholder="Add Your Age">
<input type="hidden" ng-model="todoId" />
<form style="display:'?????????'" ng-submit="addTodo()">
<input class="btn-primary" type="submit" value="add">
</form>
<form style="display:'?????????'" ng-submit="addTodo()">
<input class="btn-primary" type="submit" value="update">
</form>
and this is my angularjs bit level coding
$scope.DisplayUpdate = "none";
I have one screan for manage student details, i want to show add button when first time at this time hide update button , and when update time to show update button and at this time add button was need to hide .
see this line for set to hide and show details in script side using angular js : $scope.DisplayUpdate = "none";
How to i set this value in my button style ?
<form style="display:'?????????'" ng-submit="addTodo()">
<input class="btn-primary" style="display:'?????????'" type="submit" value="add">
</form>
You can use ng-show to hide it
<form ng-show="DisplayUpdate === 'none'" ng-submit="addTodo()">
<input class="btn-primary" type="submit" value="add">
</form>
If you want to remove it from DOM tree, use ng-if
<form ng-if="DisplayUpdate === 'none'" ng-submit="addTodo()">
<input class="btn-primary" type="submit" value="add">
</form>
Don't set the style directly, use the ng-show directive and let Angular handle it for you.
API Docs
Finally i got it .
Below is my code :
JS file :
function TodoCtrl($scope) {
var value = BindStudentList();
function BindStudentList() {
$.ajax({
url: '/Home/Contact1',
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
value = data.data;
}
});
$scope.DisplaySave = true;
$scope.DisplayUpdate = false;
return value;
}
$scope.addTodo = function () {
$.ajax({
url: '/Home/Index1',
type: 'GET',
data: { todoName: $scope.todoName, todoAge: $scope.todoAge },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
value = data.data;
}
});
};
$scope.Sample = value;
$scope.remaining = function () {
var count = 0;
angular.forEach($scope.Sample, function (todo) {
count += todo.done ? 0 : 1;
});
return count;
};
$scope.editTodo = function (Student) {
$.ajax({
url: '/Home/Edit1',
type: 'GET',
data: { Id: Student.todo.StudentId },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$scope.todoName = data.data.StudentName;
$scope.todoAge = data.data.StudentAge;
$scope.todoId = data.data.StudentId;
$scope.DisplayUpdate = true;
$scope.DisplaySave = false;
}
});
};
}
and this is my view code
<!doctype html>
<html ng-app>
<body>
<script src="~/Scripts/angular.js"></script>
<h2>Student Details</h2>
<div ng-controller="TodoCtrl">
<span>{{remaining()}} of {{Sample.length}} remaining</span>
[ archive ]
<input type="text" ng-model="todoName" size="30"
placeholder="Add Your Name">
<input type="text" ng-model="todoAge" size="30"
placeholder="Add Your Age">
<input type="hidden" ng-model="todoId" />
<form ng-show="DisplaySave" ng-submit="addTodo()">
<input class="btn-primary" type="submit" value="Save">
</form>
<form ng-show="DisplayUpdate" ng-submit="addTodo()">
<input class="btn-primary" type="submit" value="Update">
</form>
<br />
<br />
<table>
<tr>
<td><b>Student Name</b></td>
<td><b>Student Age</b></td>
</tr>
<tr ng-repeat="todo in Sample">
<td><span>{{todo.StudentName}}</span></td>
<td><span>{{todo.StudentAge}}</span></td>
<td>
<button value="{{todo.StudentId}}" ng-click="editTodo(this)">Edit</button>
</td>
</tr>
</table>
</div>
<script src="~/Scripts/Todo.js"></script>
</body>
</html>
I added the ng-show="DisplaySave" and ng-show="DisplayUpdate" in my buttons , and i will pass the values like true or false in javascript using angularjs when edit and load time .
Now it's working. I know my code will helps to other person . cheers

Form is not checked by if statement

I have two forms with id formA and comments and I want to submit them via AJAX. But the if and else here doesn't check the form. I always get alert hello3.
JS:
function submitformbyajax() {
var currentForm = $(this);
if (currentForm.attr("id") == 'formA') {
$.ajax({
type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function() {
$("#refresh").load("commentform.php #refresh");
}
});
} else if (currentForm.attr("id") == 'comments') {}
alert("hello3");
return false;
}
the function is called by
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
here is the full demo page ....
<?php
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script>
function submitformbyajax (){
var currentForm = $(this);
if (currentForm.attr("id") == 'formA' ) {
$.ajax({type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function(){
$("#refresh").load("commentform.php #refresh");
alert ("hello1");
}
} );
}
else if (currentForm.attr("id") == 'comments') {
alert("hello2");
}
alert ("hello3");
return false;
}
</script>
<title>
comment forms..
</title>
</head>
<body>
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
<div id="refresh">
<?php
include_once('databaseconnection.php');
$selectdata=mysql_query("select * from `fetwork_view` ");
while($selectedinarray=mysql_fetch_array($selectdata)){ ?>
<table>
<tr>
<td>
<?=$selectedinarray['view']?>
</td>
</tr>
<tr>
<td>
<form name="comment" id="comments" action="" method="">
<textarea name="comment" id="commentform" style="width:70%; height:25px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</td>
</tr>
</table>
<?php } ?>
</div>
</body>
</html>
Your alert(...) statement is executed regardless of condition tested by if. It is executed right after that if.
Note that ajax will not redirect the "flow" of the code. Browser will just "launch" the AJAX request and continue. Then, after a response from server is received - AJAX callback function will be executed.
Update:
To "pass" your form to submitformbyajax function add this as an argument:
<form name="formA" id="formA" onsubmit="submitformbyajax(this);">
JS:
function submitformbyajax(your_form) {
var currentForm = $(your_form);
I think you should use
$("form#formA").submit(function(){
alert(1);
});

Categories

Resources