I have a form that "sits" inside a table
<form id="form">
<input type="submit" value="send" class="btn btn-w-m btn-primary" style="float: left;">Add transaction</input>
<table class="table table-striped table-bordered table-hover " id="editable" >
<thead>
<tr>
<th>Date</th>
<th>Name<br>(Last name, Firstname,<br>
or Business name)
</th>
<th>Address</th>
<th>Phone</th>
<th>Price with VAT</th>
<th>VAT</th>
<th>Transaction type</th>
<th>Currency</th>
<th>Installments</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" name="date"/></td>
<td><input type="text" name="name"/></td>
<td><input type="text" name="address"/></td>
<td><input type="text" name="phone"/></td>
<td><input type="text" name="price_with_vat"/></td>
<td>25%(from database)</td>
<td class="exclude"><select name="transaction_type">
<option>value1</option>
<option>value2</option>
<option>value3</option>
</select></td>
<td class="exclude"><select name="currency">
<option>Euro</option>
<option>USD</option>
<option>Pound</option>
</select></td>
<td class="exclude"><select name="installments">
<option>Yes</option>
<option>No</option>
</select></td>
</tr>
</tbody>
What I want is to select all input values and send an Ajax request to a php end. The problem is that in my jquery function (code following) i cannot gather all the inputs. Also altough i have a preventDefault page still get refreshed.
var request;
$('#form').submit(function(event){
if (request){
request.abort();
}
var form = $(this)
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
console.log(serializedData);
event.preventDefault();
});
Try this code
For a form element's value to be included in the serialized string,
the element must have a name attribute.
$(document).ready(function() {
//Form submit event
$('#form').on('submit', function(e){
// validation code here
if(!valid) {
e.preventDefault();
}
//Serialized data
var datastring = $("#form").serialize();
//Ajax request to send data to server
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
success: function(data) {
alert('Data send');
}
});
});
});
Try using this code:
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'yourpage.php',
data: $('#form').serialize(),
success: function(){
alert('success');
},
});
});
});
});
Just change url: 'yourpage.php' with your php page where you want to send form values
Related
Below is the html code
<select name="userSelected" id="ddl">
<option value="-1">---Select---</option>
<c:forEach items="${users}" var="user" varStatus="status">
<option value="${user.userId}">${user.userName}</option>
</c:forEach>
</select>
<button type="button" onclick="showForm(this)">view</button>
<div id="test">
<form:form id="expenseView"
action="${pageContext.request.contextPath}/deleteExpense"
method="POST" modelAttribute="users">
<table>
<thead>
<tr>
<td align="justify"></td>
<td align="justify"><b>Item</b></td>
<td align="justify"><b>Amount</b></td>
<td align="justify"><b>ExpenseDate</b></td>
</tr>
</thead>
<c:forEach items="${expenseList}" var="list" varStatus="status">
<tr>
<td><input type="checkbox" name="check"
value="${list.expenseId}"></td>
<td>${list.itemDescription}</td>
<td>${list.amount}</td>
<td>${list.expenseDate}</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="Delete">
</form:form>
</div>
And this is the jquery, ajax am using
var hideResult = function() {
$('#test').hide();
};
var showResult = function() {
$('#test').show();
};
function showForm(myFormType) {
var selectedValue = $('#ddl option:selected').val();
var url = "${pageContext.request.contextPath}/viewExpense" + "?Id="
+ selectedValue;
$.ajax({
url : url,
}).success(function(data) {
$('#test').html(data);
});
showResult();
}
what I want to achieve is when a user hits a view button the only the div section should be refreshed so for that I am using ajax, but as my controller is sending a view name so what its doing is that it is refreshing that part only but with that one more of same kind of dropdown gets added.
Maybe, because my controller is sending the whole view. So how to achieve partial rendering of view. Please help
There are 2 approaches you can use.
You could adjust what is sent based on a parameter in the request or parse the response for the html that you want once it is received.
Here's how to do second approach
$.ajax({
url : url,
}).success(function(data) {
var $form = $(data).find('#expenseView');
$('#test').html($form);
});
You can also use replace the above with load() shorthand method of $.ajax to do this:
$('#test').load(url +' #expenseView');// note that space before selector is important
I found a tutorial that auto submits the form data but all I want to do is add a submit button to pass the data to ajax.
My goal is to have a form with multiple inputs and when the user clicks the submit button it sends it through ajax and updates the page without reloading the page. Also, another key piece is the way it post all the inputs into an array so that when the update script is ran the name attributes from the input fields match the columns in the database.
I think I'm close. I've searched and haven't found my exact solution. Thanks in advance.
<script type="text/javascript" src="/js/update.js"></script>
<form method="POST" action="#" id="myform">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
<div id="alert">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event) {
updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
$('#alert').text('Updated');
$('#alert').fadeOut().fadeIn();
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
// FORM: Variables were posted
if (count($_POST))
{
$data=unserialize($_POST['data']);
// Prepare form variables for database
foreach($data as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$column."='".$value."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
Ended up figuring it out. Thanks for everyones help.
<p id="alert"></p>
<form id="form" method="post" action="/ajax/update_company_info.php">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<input type="submit" value="Save" id="submit">
</td>
<td></td>
</tr>
</table>
<!-- end id-form -->
</form>
update.js
$(document).ready(function() {
$('form').submit(function(evt) {
evt.preventDefault();
$.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var value = input.val();
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
//var method = form.attr('method');
//var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
$.ajax({
url: "/ajax/update_company_info.php",
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
type: "POST",
success: function(data) {
$('#alert').html("<p>Sent Successfully!</p>");
}
}); // end post
});// end each input value
}); // end submit
}); // end ready
update_customer_info.php
<?php
include($_SERVER['DOCUMENT_ROOT'] . '/load.php');
function clean($value)
{
return mysql_real_escape_string($value);
}
// FORM: Variables were posted
if (count($_POST))
{
// Prepare form variables for database
foreach($_POST as $column => $value)
${$column} = clean($value);
// Perform MySQL UPDATE
$result = mysql_query("UPDATE customers SET ".$col."='".$val."'
WHERE ".$w_col."='".$w_val."'")
or die ('Error: Unable to update.');
}
?>
I think that you want to update form when submit.so you should
remove submit with a button given below.
<button id="myBtn">Save</button>.
You should add the given below code in ur js file.
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event){
Updateform('give id of the form');
});
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
});
You can retrieve input value in your php code by using unserialize()
as an array.So you can save data to
database and whatever you want to.i hope you get the answer.Hence,your code will become
<form method="POST" action="#" id="form1">
<!-- start id-form -->
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th valign="top">Business Name:</th>
<td><input type="text" name="company_name" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 1:</th>
<td><input type="text" name="address_1" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th valign="top">Address 2:</th>
<td><input type="text" name="address_2" class="inp-form" /></td>
<td></td>
</tr>
<tr>
<th> </th>
<td valign="top">
<input id="where" type="hidden" name="customer_id" value="1" />
<button id="myBtn">Save</button>
</td>
<td></td> </tr> </table> <!-- end id-form --> </form>
Your js code become
var myBtn = document.getElementById('myBtn');
myBtn.addEventListener('click', function(event)
{ Updateform('form1'); });
function updateform(id){
var data = $('#'+id).serialize();
// alert(data);
$.ajax({
type: 'POST',
url: "/ajax/update_company_info.php",
data: data,
success: function(data) {
$('#id').html(data);
// alert(data);
//alert(data);
},
error: function(data) { // if error occured
alert("Error occured, please try again");
},
}); }
update_company_info.php will become
$data=unserialize($_POST['data']);
// you can retrieve all values from data array and save all .
?>
Instead of:
$(".submit").click(function() {
Give your form a id like 'myform': <form method="POST" action="#" id="myform">
And use this for preventing default submission of form:
$("#myform").submit(function(e) {
e.preventDefault();
//your code
}
I have to code to do both of these functions, however, when I try to integrate them its either one or the other. (either the email is sent with the name / email & lands on server.php, or the email is sent with the data & none of the inputs are sent). I want to be able to send both the html table data as well as the users name & email inputs. The code below will simply echo the html data or the users inputs.
This code sends data to the server:
Jquery / Html
<script language="javascript" type="text/javascript" src="jQuery.js">
</script>
<script language="javascript" type="text/javascript">
$(function(){
var dataArr = [];
$("table").each(function(){
dataArr.push($(this).html());
});
$('#sendServer').click(function(){
$.ajax({
type : "POST",
url : 'server.php',
data : "content="+dataArr,
success: function(data) {
alert(data);// alert the data from the server
},
error : function() {
}
});
});
});
</script>
<table id="table" border=1>
<thead> <tr>
<th>First</th>
<th>Last</th>
<th>Date of birth</th>
<th>City</th>
</tr></thead>
<tbody>
<tr>
<td>TEXT1</td>
<td>TEXT2</td>
<td>TEXT3</td>
<td>TEXT4</td>
</tr>
<tr>
<td>TEXT5</td>
<td>TEXT6</td>
<td>TEXT7</td>
<td>TEXT8</td>
</tr>
<tr>
<td>TEXT9</td>
<td>TEXT10</td>
<td>TEXT11</td>
<td>TEXT12</td>
</tr>
</tbody>
</table>
<input id="sendServer" name="sendServer" type="button" value="Send to Server" />
Server.php
<?php
echo $_REQUEST['content'];
?>
This form send data using ajax
<div style="padding:3px 2px;border-bottom:1px solid #ccc">Ajax Form</div>
<form id="ff" action="test.php" method="post">
<table>
<tr>
<td>Name:</td>
<td><input name="name" type="text"></input></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="email" type="text"></input></td>
</tr>
<tr>
<td>Phone:</td>
<td><input name="phone" type="text"></input></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></input></td>
</tr>
</table>
</form>
The jquery script
$('#ff').form({
success:function(data){
$.messager.alert('Info', data, 'info');
}
});
And the php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
echo "Your Name: $name <br/> Your Email: $email <br/> Your Phone: $phone";
I'm sure that I'm just missing something small. When I implement these into my code, an email is sent. The email contains either the name & email, or the html table data. The difference in code is putting a button action="submit" on my code. Whenever the email sent displays the name & email, the page also redirects to the blank php page. Hopefully I'm being clear enough.
Cheers.
Just add a e.preventDefault(); to your submission javascript inside #sendServer's click handler. This will prevent the form from submitting traditionally like it's doing now.
You'll also need to add the parameter e to that function:
$('#sendServer').click(function(e){
// ajax call
e.preventDefault();
}
Or return false; in the same place as was commented below.
There is something wrong with the way I am using the ajax call.
When I place the ajax call inside the block, it executes the error function in the ajax callback. When the ajax call is moved outside the block, the variable subcate passed to server is undefined.
var that = this;
var subCate ='' ;
var tr = $('#tbl').find('tr');
//My block
tr.bind('click', function(event) {
var values = '';
tr.removeClass('highlight');
var tds = $(this).addClass('highlight').find('td');
subCate = tds.find('#myid').text();
alert(subCate);
//Tried moving it out of the block but not much of help
$.ajax({
url: '/playground',
type: 'POST',
data: { id: subCate},
success: function(data){
alert("Sub category recvd");
console.log("successs");
},
error: function(jqXHR){
console.log("failed");
alert("failed");
}
});
});
//Ajax call moved here
Here is the node.js server code :
app.post('/playground', function(req, res) {
debug("Inside post(/playground) ",req.body.id);
res.send('ok', 200);
});
Hi Here is the snippet of HTML table, that will give an idea what the jquery code is doing
<div id="category-container">
<div id="category-form">
<h1></h1>
<p id="sub1" class="subheading">Select a category</p>
<!--hr-->
<div style="margin:20px" class="container">
<table id="tbl" class="table table-bordered table-striped">
<thead>
<tr>
<!--th(style='width:40px') #-->
<th style="width:180px">Name</th>
<th style="width:200px">Location</th>
<th style="width:180px">Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div id="myid"><a id="item" href="/playground/:0">Electronics</a></div>
</td>
</tr>
<tr>
<td>
<div id="myid"><a id="item" href="/playground/:1">Real Estate</a></div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Thanks in advance guys !
Add event.preventDefault() at the top of your bind.
Also, I recommend changing the event binding to the following:
$('#tbl').on('click', 'tr', function(event) {
event.preventDefault();
// your code
});
How can I use jQuery ajax to handle checked checkboxes? How do I then send each checked checkbox in the html table, to ajax.php?
This is what I've tried so far:
ajax.php
session_start();
if (isset($_POST['id']) && isset($_POST['to']) && isset($_SESSION['user']['id'])) {
if (is_numeric($_POST['id']) && is_numeric($_POST['to'])) {
include("mysql_connector.php");
$user = $_SESSION['user']['id'];
$sendTo = mysql_real_escape_string(trim($_POST['to']));
foreach ($_POST['id'] as $id) {
$id = mysql_real_escape_string(trim($id));
mysql_query("UPDATE `email` SET status = '$sendTo' WHERE `email_id` = '$id' AND `userid` = '$user'");
}
}
}
Javascript:
$(".submit").click(function() {
var id = $("#id").val();
var to = $("#bins").val();
var dataString = 'id=' + id + '&to=' + to;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
});
});
html:
<form method="POST">
<table id="inventory" class="table">
<thead>
<tr>
<th style="text-align: center;">Check All</th>
<th>Time Received</th>
<th>Email</th>
<th>Subject</th>
<th>ID</th>
</tr>
</thead>
<tbody>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="2" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>0</td>
</tr>
<tr class="email">
<td style="text-align: center;"><input type="checkbox" name='msg[]' class="id" value="3" /></td>
<td>1231231</td>
<td>test</td>
<td>test</td>
<td>1</td>
</tr>
</tbody>
</table>
</br>
<select name="bins" class="bins">
<option value="1">Archive</option>
<option value="2">Read</option>
<option value="3">Unread</option>
<option value="4">Save</option>
</select>
<input type="submit" name="move" value="Move" class="submit" style="width:auto;"/>
</form>
Thank you for reading.
First, it is invalid to have multiple dom elements with duplicate ids. If those checkboxes need ids, make them unique. If they don't need ids, then just drop them completely.
To get a list of the values of all checked checkboxes, do:
var checkedVals = [];
$("input[type='checkbox']:checked").each(function() {
checkedVals.push($(this).val());
});
Or you can fetch different groups of checkboxes by name:
var checkedMsgVals = [];
$("input[name='msg[]']:checked").each(function() {
checkedMsgVals.push($(this).val());
});
To send these to php, just include them in your data packet when you make the call. To do this you'll want to send an object over, not a querystring.
var dataObj = {'id': id, 'to': to, 'checkedValues': checkedMsgVals };
$.ajax({
type: "POST",
url: "ajax.php",
data: dataObj,
});