php jquery ajax work with multiple forms and files - javascript

I'm not sure about the right title for this question.
I have two inputs with two buttons for them in index.php
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<input type="text" class="form-control" id="input1" name="input1" value="">
<button type="submit" id="button1" name="button1" class="btn">Get Data</button>
</form>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<input type="text" class="form-control" id="input2" name="input2" value="">
<button type="submit" id="button2" name="button2" class="btn">Get Data</button>
</form>
// display and insert them into database with third button
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
// the results goes inside these input
<input type="text" class="form-control" class="results-container" name="input3" value="">
<input type="text" class="form-control" class="results-container" name="input3" value="">
<input type="text" class="form-control" class="results-container" name="input3" value="">
<input type="text" class="form-control" class="results-container" name="input3" value="">
...
<button type="submit" id="button3" name="button3" class="btn">Sace The Data</button>
</form>
I want to get the input data separately and pass the values(ajax or $_POST) into two other files and do something with them in those two other files namely( doing_somthing1.php , doing_somthing2.php ) and get the results of these files and show them in index.php inside inputs(results-container).
here is a preview:
index.php / AJAX Script
<script>
$(document).ready(function() {
$('#button1').click(function() {
$input = $('#input1').val();
$.ajax({
type: 'POST',
url: '.php',
data: {
'doing_somthing1.php': $input
},
dataType: 'json',
success: function(result) {
$('.results-container').html(result[0]);
},
});
});
});
</script>
doing_somthing1.php
if (isset($_POST['button1'])) {
$input_data = $_POST['input1'];
// do other stuffs like foreach, if and etc..
// and return new data in array
$results = array();
echo json_encode($results);
}
I'm new to ajax and I don't know if I did this right, but if you understand what I mean and what I'm trying to do, please can you help me out here.

I'm not sure that I've understood everything. But you do not need to use two files to handle the form. You can do something like this:
if (isset($_POST['button1'])) {
$input_data = $_POST['input1'];
// do other stuffs like foreach, if and etc..
// and return new data in array
$results = array();
echo json_encode($results);
} else if (isset($_POST['button2'])) {
$input_data = $_POST['input2'];
// do other stuffs like foreach, if and etc..
// and return new data in array
$results = array();
echo json_encode($results);
}
How many inputs you want to submit to the form at the bottom ? You might need again a little bit of jquery 'on click' to handle the third form, because the inputs "results-container" are outside of it. By the way, you do not need the property name any more.

Related

It is not able to post with JS form submit function

In this webpage , I have a visible form with a submit button ,called form A.It has a post action.
<form name="payFormCcard" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
I want to do an invisible form that extract some of the data from form A , with the method of hidden input button .It auto-executes the form and post to the another place with the JS.
However, it works and posts to appropriate place if I add the real button .
<input type="submit" name="submission_button" value="Click here if the site is taking too long to redirect!">
Here is my code (without the real button):
<form name="A" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <== first visable form
.....
//invisible table
<form name="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" name="merchantId" value="sth">
<input type="hidden" name="amount" value="</?php echo $input_amount; ?>" >
<input type="hidden" name="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" name="currCode" value="sth" >
<input type="hidden" name="mpsMode" value="sth" >
<input type="hidden" name="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" name="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" name="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
...
<!-- <input type="submit" name="submission_button" value="Click here if the site is taking too long to redirect!">-->
</form>
<script type="text/javascript">
//Our form submission function.
function submitForm() {
document.getElementById('payForm').submit();
}
//Call the function submitForm() as soon as the page has loaded.
window.onload = submitForm;
</script>
You should use DOMContentLoaded instead of load to ensure that the DOM elements are loaded successfully.
Try to do something like below:
<script type="text/javascript">
//Our form submission function.
function submitForm() {
document.getElementById('payForm').submit();
}
//Call the function submitForm() as soon as the document has loaded.
document.addEventListener("DOMContentLoaded", function(event) {
submitForm();
});
</script>

Multiple Forms on Same page AJAX

I'm having troubles on making this work.
I need to have multiple forms on the same page... I've tried countless things, but nothing seem to work.
What I'm trying to do here is identify every form (in some way) in order to submit that one instead of the FIRST form on the page. Code below, works but submits always the same form, the first one!
Here's my current code
JS:
$(document).ready(function(){
$('.submit').on("click", function() {
var artworkId = $("#inquirebox").data("artworkid");
$.post("send.php";, $("#artinquire"+artworkId).serialize(), function(response) {
$('#success').html(response);
});
return false;
});
});
HTML:
<div id="inquirebox" data-artworkid="<?php echo 456;?>">
<form action="" method="post" id="artinquire<?php echo 456;?>" data-artworkid="<?php echo 456;?>">
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="message">Message:</label><br />
<textarea name="message" id="message"></textarea><br />
<input type="hidden" name="id" value="<?php echo 456;?>">
<input type="hidden" name="artist" value="<?php echo $title1; ?>">
<input type="hidden" name="url" value="<?php echo $uri1; ?>">
<input type="hidden" name="artwork" value="<?php echo $artwork1; ?>">
<input type="button" value="send" class="submit" id="submit" data-artworkid="<?php echo 456;?>">
<div id="success"></div>
</form>
</div>
You're using the same ID on all the DIV wrappers around the forms.
ID's must be unique, so you could use a class instead, but you really don't need any identifiers at all, nor do you need data attributes, the .submit button is inside the form, so all you need is this.form, or more jQuery'ish $(this).closest('form') to get the parent form
$(document).ready(function(){
$('.submit').on("click", function() {
var form = $(this).closest('form');
$.post("send.php", form.serialize(), function(response) {
form.find('.success').html(response);
});
return false;
});
});
You should however use a class on the #success element to find it based on the form.

send data to php JSON way from html form

I'm trying to send POST data using JavaScript. I have data in HTML form :
<form name="messageact" action="">
<input name="name" type="text" id="username" size="15" />
<input name="massage" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
after press submit key i want to send name and massage to my PHP file ! a wrote this for my JavaScript in html : post.php , with post method
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
and for my php i wrote this :
if(isset($_SESSION['name'])){
$text = $_POST['text'];
....
....
but in PHP i couldn't receive anything ! please help me to solve this problem ! and how can i change it to JSON way ?
You don't need javascript for send data to server just submit the form and add the destination php in action
<form name="messageact" action="post.php">
<input name="name" type="text" id="username" size="15" />
<input name="massage" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
for testing post.php you could use this code
<?php
if(isset($_POST['name'])){
echo $_POST['name'] . <br />;
echo $_POST['massage'] . <br />;
echo $_POST['submitmsg'] . <br />;
?>
if you want ajax behavior try this
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {submitmsg: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
Why do you need to store name in the $_SESSION?
If you have used $_SESSION by mistake change this
if(isset($_SESSION['name'])){
$text = $_POST['text'];
....
....
to this and it should work
if(isset($_POST['text'])){
$text = $_POST['text'];
....
....
The $_POST and $_SESSION are 2 different variables. You might wanna take a look at this and this
Try this:
<form name="messageact" method="post" action="post.php">
<input name="name" type="text" id="username" size="15" />
<input name="message" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
$("#submitmsg").click(function(e){
var name = $("#username").val();
var usermsg = $("#usermsg").val();
$.post("post.php", {'name': name,'usermsg':usermsg});
return false;
});
i do it for java :
//If user submits the form
$('#edit').submit(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'post.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
console.log("success");
$('#feedback').html(data).fadeIn().delay(3000).fadeOut();
},
error: function( jqXHR,textStatus,errorThrown ){
console.log(textStatus);
}
});
});
and for form :
<form id="edit" action="" method="POST">
<input type="text" name="name" >
<input type="text" name="phone" >
<input type="text" name="address" >
<input type="submit" name="submit" value="Send">

Submit multiple form with one button

I know this question has been asked a lot, but there doesn't seem to be an answer for me. I'm sorry if I'm just really dumb, but I've been stuck for a day now..
I want to select a table row(see below), and then delete that user. Since I want to have multiple form's to interact with the table I can't place them in one form.
$("#clickMe").click(function () {
$(".myForms").trigger('submit');
});
$('.myForms').submit(function () {
console.log("SWAGGG");
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="listForm" action="index.php?p=admin" method="POST">
<?php
$userQuery = "SELECT * FROM usr2";
$row_userQuery = $dbportal->query($userQuery);
if(isset($row_userQuery) && !empty($row_userQuery))
{
//row[0] = ID
//row[1] = username(abbrevation)
//row[2] = admin? 0=normale user 1=admin
echo'
<table id="myTable" class="table table-striped">
<tr><td></td><td>User ID</td><td>username</td><td>Role</td></tr>';
foreach ($row_userQuery as $row)
{
echo'
<tr>
<td id="tdSelect"> <input type="checkbox" name="selectedUser[]" value="'. $row[0] .'" />
<td>'. $row[0] .'</td>
<td>'. $row[1] .'</td>
<td>'. $row[2] .'</td>
</tr>';
}
echo'</table>';
}
?>
<input type="hidden" name="action" value="listForm">
</form>
<form id="deleteForm" class="myForms" action="index.php?p=admin" method="POST">
<div class="leftTextBox">
<p>user ID:</p>
<p class="margin">gebruikersnaam:</p>
</div>
<div class="rightTextBox">
<input class="form-control" type="text" name="userID" placeholder="user ID">
<input class="form-control" type="text" name="login" placeholder="gebruikersnaam" style="margin-top: 8px;">
</div>
<input type="hidden" name="action" value="deleteForm">
</form>
<button id="clickMe" class="btn btn-default" style="margin-top:5px;float:right;">Delete user</button>
I'm sure that its just me overseeing something, but help would greatly be appriciated.
Also, I have ajaxForm plugin installed.
A 'submit' is by definition a jump to a new URL. You know this can only be done for one form at a time.
However, we talking normal 'submits' here, and you don't have to use normal submits to get information from a form and act on it.
Since you're using JQuery, you could use that. Have a look at ajax calls. For instance here:
http://api.jquery.com/jquery.post
Look for the example called: Post a form using ajax and put results in a div, you will find useful code there. It shows you how to get the values of the fields in the form.
Let's imagine you have 3 forms like this:
<form id="form1" action="api/url1">
<input name="field1" type="text" />
</form>
<form id="form2" action="api/url2">
<input name="field2" type="text" />
</form>
<form id="form3" action="api/url3">
<input name="field3" type="text" />
</form>
<button>Submit</button>
Then you can fire the submit of each form like this:
$('button').on("click", function () {
$('form').each(function (index, form) {
$(form).submit();
});
});
Then to prevent form full post back just prevent the default of the submit event and then post the serialized form with ajax:
$('form').on("submit", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
alert(data);
},
error: function (error) {
console.error({ status: error.status, statusText: error.statusText })
}
});
});
JSFIDDLE
If you want to use ajax
you can group a data of all input and post using new FormData()
function fnSubmintAll(){
var formData = new FormData();
$("#form1,#form2,#form3").each(function(idx,item){
var frmValue = $(item).serializeArray();
$.each(frmValue, function (key, input) {
formData.append(input.name,input.value);
});
})
$.ajax({
url: "/PostUrl",
type: "POST",
data: formData,
contentType:false,
processData: false,
success: function (result) {
alert("Success")
},
error: function () {
alert("Error")
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset>
<legend>From 1</legend>
<form id="form1">
<input name="field1" type="text" />
</form>
</fieldset>
<fieldset>
<legend>From 2</legend>
<form id="form2">
<input name="field2" type="text" />
</form>
</fieldset>
<fieldset>
<legend>From 3</legend>
<form id="form3">
<input name="field3" type="text" />
</form>
</fieldset>
<br />
<br />
<br />
<button type="button" onclick="fnSubmintAll">Submit All</button>

Jquery form data not sending through ajax POST method

I have a form which sends data to php via ajax , very simple. But when I submit the form the data is not being sent across.
Javascript:
$(document).ready(function(e) {
$('#update').submit(function(event) {
event.preventDefault();
var fd = new FormData($('#update')[0]);
alert(fd);
$.ajax({
url:'func/update.php?id=<?php echo md5($result['id']);?>',
processData: false,
contentType: false,
data: fd,
type:'POST',
dataType:"JSON",
success:function(json){
}
});
});
});
PHP:
if(empty($_POST)){
echo 'No post data';
}else{
echo 'data sent';
}
print_r($_POST);
The php is left very basic to see what is going on. I would normally attach my data fom the individual field.
data:{a:a,b:b,c:c}... and so on.
HTML:
<form id="updateStaff">
Profile Picture<br /><img id="pp_img_display" src="../images/<?php echo $result['pp'];?>" width="100px" /><br /><small>Upload a new image</small><br/><input onchange="uploadImage()" type="file" id="file" /><input type="hidden" id="pp_img" value="<?php echo $result['pp']; ?>" /><br/><small>upload .jpg .png .jpeg only</small><br /><div class="form_err" id="image_err"></div>
Name: <select id="prefix" required="required">
<option><?php echo $result['prefix']; ?></option>
<?php $pre = array('Mr','Mrs','Miss','Ms');
for($x = 0; $x < count($pre); $x++){
if($pre[$x] != $result['prefix']){
echo '<option>'.$pre[$x].'</option>';
}
}?>
</select>
<input type="text" id="f_name" placeholder="First Name" value="<?php echo $result['f_name'];?>" required="required" />
<input type="text" id="l_name" placeholder="Last Name" value="<?php echo $result['l_name'];?>" required="required" /><br/>
Job Title: <input type="text" id="job" required="required" placeholder="Job Tilte" value="<?php echo $result['job_title']; ?>" />
<br/>
Years of Experience: <input type="number" id="xp" required="required" placeholder="1" value="<?php echo (int)$result['xp'];?>" />
<p><input type="submit" value="Update" /> <input type="button" value="Cancel" onclick="history.go(-1);"/></p>
</form>
I would have thought that formData would be a shorter way of doing this.
To be send, element requires name attribute:
<input name="myInputSend" type="text" id="f_name" placeholder="First Name" value="<?php echo $result['f_name'];?>" required="required" />
Once you have added something like this first answer into your project to apply name prefixes to your partial views, you can post them back as is.
On a side note
If you get into variable length lists within those partial views, its no longer that easy.
You would want to send prefix to the controller to properly add new htmlNamePrefixes to the new partial view.
To make posting easy in those situations I've created this helper $.fn()
The helper function will re-base missing / added name indexes back in order for each of the partial views within a parenting form (even if the partial views , had partial views) for the post back to go through as it should. (apologize for the early stage and messed up commenting).

Categories

Resources