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
}
Related
I want to fetch database values into text boxes without refreshing page. with page refresh it goes fine but I don't want to refresh it.
My code is shown below.
PHP
<?php
include 'Connection.php';
$sql=mysqli_query($connect,"select * from `registration`");
while ($row=mysqli_fetch_array($sql))
{
echo "<tr>
<td>".$row['Emp_Code']."</td>
<td>".$row['Full_Name']."</td>
<td>".$row['Permanent_Address']."</td>
<td>".$row['Mobile_No']."</td>
<tr>";
if (isset($_POST['Fetchdetails']))
{
$userid = $_POST['userid'];
$fetchquery = mysqli_query($connect,"select * from `registration` where `Emp_Code` = '$userid'");
if (mysqli_num_rows($sql)>0)
{
while ($row=mysqli_fetch_array($fetchquery))
{
$employeecode=$row['Emp_Code'];
$fullname=$row['Full_Name'];
$permanentaddress=$row['Permanent_Address'];
$mobileno=$row['Mobile_No'];
}
}
}
}
?>
My HTML Code is
<html>
<body>
<div align="center" id="div">
<table width="400" border="1">
<tr align="right" style="background-color:#FFF;">
<td width="100">Permanent Address : </td>
<td width="100">
<input type="text" name="permanentaddress" id="permanentaddress" placeholder="Permanent Address" size="15" value="<?php echo $permanentaddress;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Employee Code : </td>
<td width="100"> <input type="text" name="employeecode" id="employeecode" placeholder="Employee Code" size="15" value="<?php echo $employeecode;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Full Name : </td>
<td width="100"> <input type="text" name="fullname" id="fullname" placeholder="Full Name" size="15" value="<?php echo $fullname;?>"/> </td>
</tr>
<tr align="right" style="background-color:#FFF;">
<td width="100">Mobile No. : </td>
<td width="100"> <input type="text" name="mobileno" id="mobileno" placeholder="Mobile No." size="15" value="<?php echo $mobileno;?>"/> </td>
</tr>
</table>
</div>
<br>
<div align="center">
<input type="submit" name="Fetchdetails" value="Fetch Details" id="Fetchdetails" />
</div>
</body>
</html>
How can I fetch values from database into text boxes without refreshing web page?
You can use AJAX to achieve the dynamic loading of the data.An Example would be:
$.ajax({
url: "yourscript.php",
cache: false,
success: function(html){
$("#results").append(html);
}
});
where yourscript.php is your backend script, where the database calls would be executed and returned back to your success on successful request.
Please note that the data should be exchanged in a serialized format(for AJAX requests the most common approach is JSON).
You can achieve this by json.
Try the following code.
PHP Code
<?php
include 'Connection.php';
$userid = $_GET['userid'];
$fetchquery = mysqli_query($connect,"select * from `registration` where `Emp_Code` = '$userid'");
if (mysqli_num_rows($sql)>0)
{
while ($row=mysqli_fetch_array($fetchquery))
{
$return['employeecode']=$row['Emp_Code'];
$return['fullname']=$row['Full_Name'];
$return['permanentaddress']=$row['Permanent_Address'];
$return['mobileno']=$row['Mobile_No'];
}
}
echo json_encode($return);
Javascript Code
$("#Fetchdetails").click(function(e) {
e.preventDefault();
var userId = $(this).attr('data-user-id');
$.ajax({
type: "GET",
url : 'http://localhost/test/get_data.php?userid='+userId,
dataType : 'json',
success : function(response) {
$('#permanentaddress').val(response.permanentaddress);
$('#employeecode').val(response.employeecode);
$('#fullname').val(response.fullname);
$('#mobileno').val(response.mobileno);
},
error : function() {
alert('There was an error');
}
});
});
Note : you have to replace following line with your php file url.
url : 'http://localhost/test/get_data.php
I'm using a MVC framework and in my view I have my javascript code
this is in my view:
<script>
$(document).ready(function(){
$(document).on('click','#filtr',function(){
var id_val = $('#id_val').val();
var key_val= $('#key_val').val();
console.log(id_val);
console.log(key_val);
$.ajax({
url:"<?php echo base_url()?>filter/filtr",
method:"POST",
data:{
id_val:id_val,
key_val:key_val
},
/*beforeSend:function(){
$("container_tab").html("Searching...");
},*/
success:function(data){
$("container_tab").html(data);
}
})
});
});
</script>
<div class="table-responsive">
<table class="table table-striped table-hover" id="dataTables-example">
<tr>
<td>
Filter by...
</td>
<td>
ID: <input type="text" id="id_val" name="id_val" value="3" />
</td>
<td>
KEY: <input type="text" id="key_val" name="key_val" value="asdf12" />
</td>
<td>
<button type="button" class="btn btn-info btn-sm" id="filtr">FILTER</button>
</td>
</tr>
<br />
<div id="container_tab"></div>
</table>
</div>
I want the table that comes back from my controller to fill <div id="container_tab"></div>
in my filter controller I have my filtr function, but this function for now does not return $filter_list even though I'm still not doing the actual query.
public function filtr(){
$filter_list = '';
$filter_list .= '
<tr>
<td style="vertical-align: middle;" class="text-center">this should be sent to view as a table row</td>
</tr>
';
echo $filter_list;
}
when I do a console.log within my javascript function the values '3' and 'asdf12' are display but I'm not getting anything back on screen from my controller function calling filtr.
There is a minor error in your success function, your containor has a id called container_tab so use a # in front of its name like this
success:function(data){
$("#container_tab").html(data);
}
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
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.
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,
});