Here is my ajax
$(".submit").click(function(){
var vp = $("input#vehicle_plate").val();
var vm = $("input#vehicle_model").val();
var vt = $("input#vehicle_type").val();
var da = $("input#date_acquired").val();
var ad = $("input#assigned_driver").val();
var dataString = 'vehicle_plate='+ vp + '&vehicle_model='+ vm + '&vehicle_type='+ vt + '&date_acquired='+ da + '&assigned_driver='+ ad;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
And here is my PHP where i pass my 'dataString'
<?PHP
include("db.classes.php");
$g = new DB();
$g->connection();
if($_POST)
{
$vehiclePlate = $g->clean($_POST["vehicle_plate"],1);
$vehicleModel = $g->clean($_POST["vehicle_model"],1);
$vehicleType = $g->clean($_POST["vehicle_type"]);
$assignedDriver = $g->clean($_POST["assigned_driver"],1);
$ad = date('Y-m-d', strtotime($_POST["datepicker"]));
$g->add($vehiclePlate, $vehicleModel, $vehicleType, $assignedDriver, $ad);
}
$g->close();
?>
And here is my database query
public function add($vehiclePlate, $vehicleModel, $vehicleType, $assignedDriver, $ad)
{
$sql = "insert into vehicles(`vehicle_plates`,`DA`,`type`, `model`, `driver`) values('$vehiclePlate', '$ad', '$vehicleType', '$vehicleModel', '$assignedDriver')";
if(!mysql_query($sql))
{
$this->error = mysql_error();
return true;
}
else
{
return false;
}
}
the AJax returns succesful but when i try and see the table in my databse the inserted row are al 'Undefined' what seems to be causing this?
EDIT:
Here is my HTML
<div id="rform">
<form action = "list.php" method="post">
<fieldset>
<legend>Fill Up the Form</legend><br>
<div>
<label class="label-left">*Vehicle Plate:</label>
<input class="label-left" type="text" name="vehicle_plate" id="inputbox1" value maxlength="50">
</div>
<div>
<label class="label-left">*Vehicle Type:</label>
<select class="label-left" id="inputbox" name ="vehicle_type" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value="Motorcycle">Motorcycle</option>
<option value="Tricycle">Tricycle</option>
<option value="Pick-up">Pick-up</option>
<option value="Truck">Truck</option>
</select><br><br>
</div>
<div>
<label class="label-left">*Vehicle Model:</label>
<input class="label-left" type="text" name="vehicle_model" id="inputbox" value maxlength="50">
</div>
<div>
<label class="label-left">Date Acquired:</label>
<input class="label-left" name="date_acquired" id="datepicker" value maxlength="50"><br><br>
</div>
<div>
<label class="label-left">Assigned Driver:</label>
<input class="label-left" type="text" name="assigned_driver" id="inputbox" value maxlength="50"><br><br>
</div>
<div>
<label class="label-custom" color = red>NOTE: "*" Fields are required</label><br><br>
</div>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
<input id="button" type="submit" value="Add" name = "subBtn" class = "submit"/>
</fieldset>
</form>
</div>
Well the problem is with your selectors:
var vp = $("input#vehicle_plate").val();
var vm = $("input#vehicle_model").val();
var vt = $("input#vehicle_type").val();
var da = $("input#date_acquired").val();
var ad = $("input#assigned_driver").val();
Your input selectors doesn't have any id attribute instead you need to select them by their name attribute (or you can give id attributes to your html input elements so your above selectors will work):
var vp = $("input[name=vehicle_plate]").val();
var vm = $("input[name=vehicle_model]").val();
var vt = $("input[name=vehicle_type]").val();
var da = $("input[name=date_acquired]").val();
var ad = $("input[name=assigned_driver]").val();
It will pass your values correctly to server.
you are concatenating your dataString like a GET - string which is used for passing it via URLs but doesn't work in POST - requests like this.
you have to pass your POST data inside an javascript-object:
data: { vehicle_plate: vp, vehicle_model: vm, vehicle_type: vt }
...and so on.
Use serialize() it's simpler and less prone to errors.
$(".submit").click(function () {
var dataString = $("#rform form").serialize();
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function () {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
Related
I am trying to populate my form fields with AJAX when a request is being made. I was able to successfully made the request and fetched data, but the issue I am facing is that the input fields are not being populated.
If I populate the return data into a div it will display but not displaying in a form fields.
My HTML code
<form id="fm" method="post" novalidate>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="descr" id="descr" multiline="true" data-options="label:'Description:'" style="width:100%;">
</div>
<div style="margin-bottom:10px">
<input class="easyui-textbox" name="unit" id="unti" style="width:100%" data-options="label:'Unit:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="rate" id="rate" style="width:100%" data-options="label:'Rate:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="fixing" id="fixing" style="width:100%" data-options="label:'Fixing:'">
</div>
<div style="margin-bottom:10px">
<input class="easyui-numberbox" name="quantity" id="quantity" style="width:100%" data-options="label:'Quantity:'">
</div>
</form>
jQuery Code
function load_click(param)
{
var resp = $("#loadstatus");
$.ajax({
type: "POST",
url: "boqs/load.php",
data: {},
dataType: 'json',
beforeSend: function(){
resp.html(' <img src="../assets/img/rot_small.gif" />');
},
success: function (data) {
if (Array.isArray(data) && data.length) {
for (var i = 0; i < data.length; i++) {
//for each value in the json response
$(".descr").val(data[i].descr);
$(".unit").val(data[i].unit);
$(".rate").val(data[i].rate);
$(".fixing").val(data[i].fixing);
$(".quantity").val(data[i].quantity);
//alert(data[i].descr);
} // for
resp.html('');
}
});
}
PHP source code
$sql = "SELECT * FROM bill_preparation ORDER BY id DESC LIMIT 1";
$ret2 = $db->query($sql);
$json_resp = array();
while($row = $ret2->fetchArray(SQLITE3_ASSOC)){
$json_array['descr'] = $row['descr'];
$json_array['unit'] = $row['unit'];
$json_array['rate'] = $row['rate'];
$json_array['fixing'] = $row['fixing'];
$json_array['quantity'] = $row['quantity'];
//$json_array['amount'] = $row['amount'];
array_push($json_resp, $json_array);
}
//$result["rows"] = $items;
echo json_encode($json_resp, true);
Thanks to very one for your support. #Patrick suggestion pointed me to the right direction.
I discovered using $(".descr").val(data[i].descr); doesn't work in easyui form so I used $(".descr").textbox('setValue',data[i].descr); which worked.
I hope this help someone working with easyui.
i am newbie in jquery and ajax programming. I have searched the answer about getting value from checkbox and pass it to PHP Page with AJAX, but it didn't work for me. Maybe someone can help me to get value from checkbox and pass to PHP Page so i can insert it to database.
This is my checkbox code in HTML
<fieldset data-role="controlgroup" id="pilihtambahan" style="margin-top: 5px;">
</fieldset>
$.ajax({
url: host+'/skripsi3/phpmobile/kategori.php',
data: { "id": getacara},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
$("#pilihkategori").append('<input type="radio" name="radiokategori" class="required" id="'+item.kategori+'" value="'+item.kategori+'" required><label for="'+item.kategori+'">'+item.kategori+'</label>').trigger("create");
});
},
error: function(){
//output.text('There was an error loading the data.');
}
});
and this my html code to pass checkbox and other value to PHP Page
$("#simpansewa").click(function() {
var checkValues = $('input[name=cektambah]:checked').map(function()
{
return $(this).val();
}).get();
var k = $("input[name=radiokategori]:checked").val();
var u = user;
var g = getacara;
var b = $('#brandorder').val();
var d = $('#deskorder').val();
var s = $('#sosmedorder').val();
var t = $('#tambahcat').val();
dt = {user:u,acara:g,brand:b,desk:d,sosmed:s,kat:k,tambah:t,barangsewa:checkValues};
$.ajax({
type: "GET",
url: host+'/skripsi3/phpmobile/preorder.php',
data: dt,
success: function (data){
alert('Data Pemesanan Anda Telah Masuk');
window.location="statustransaksi.html";
},
error: function (e) {
alert('Fail');
}
});
});
this is my preorder.php
<?php
session_start();
include "config.php";
$idtenant = $_GET["user"];
$idacara = $_GET["acara"];
$namabrand = $_GET["brand"];
$deskbrand = $_GET["desk"];
$sosmed = $_GET["sosmed"];
$tambahcat = $_GET["tambah"];
$kategori = $_GET["kat"];
date_default_timezone_set('Asia/Jakarta');
$tanggal = date("d M Y G:i");
$statusbayar = "belumbayar";
$sewa=$_GET['barangsewa'];
$query="INSERT INTO `preorder`(`namaorder`, `sosorder`, `deskorder`, `catatan`, `kategori`, `id_tenant`, `id_acara`, `statuspesanan`, `tanggal`,`statusbayar`,`tambahanbarang`) VALUES ('$namabrand','$sosmed','$deskbrand','$tambahcat','$kategori','$idtenant','$idacara','Waiting','$tanggal','$statusbayar','$sewa')";
$result = mysql_query($query);
?>
Have a nice day!!
create one form and passed it with the use of jQuery serialize() function. This function is get all the data related with the form.
HTML Code
<form id="test">
<input type="radio" class="required" id="item1" name="item" value="1"> One
<input type="radio" class="required" id="item2" name="item" value="2"> Two
<button type="button" id="btn" > Click Me </button>
</button>
</button>
</form>
Javascript
$('#btn').click(function(){
var data = $( "#test" ).serialize()
});
All the data of the test form is assigned to the data variable. Now you can able to pass data variable to the php page with the ajax.
I'm creating a website where the user is supposed to check a couple of checkboxes and then the site will present the data in a table.
I have been looking at this "guide", but cant make it work on my page. I get no results on my index.php, and the submit.php just shows "Array[]"
This is what I have so far:
Index.php holds the checkboxes and the jQuery script.
Checkboxes is in a drop down menu, like this:
<div id="menu">
<div id="mainmenu">Gender</div>
<div id="submenu1" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="male">Male</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="gender" value="female">Female</a></div>
</div>
<div id="mainmenu">Price range</div>
<div id="submenu2" style="display:none">
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="200">200-299$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="300">300-399$</a></div>
<div id="submenu"><a href="#">
<input type="checkbox" name="price_range" value="400">400-499$</a></div>
</div>
jQuery script:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function makeTable(data){
console.log(data);
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getSnowboardFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.id);
}
});
return opts;
}
function updateSnowboards(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#boards tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getSnowboardFilterOptions();
updateSnowboards(opts);
});
checkboxes.trigger("change");
</script>
At last I have submit.php, which holds the php code for selecting the right stuff.
<?php
$pdo = new PDO('mysql:host=localhost;dbname=...', '...', '...');
$opts = $_POST['filterOpts'];
$qMarks = str_repeat('?,', count($opts) - 1) . '?';
$statement = $pdo->prepare("SELECT gender, price_range, brand, model, rocker_type, flex, size_range, image FROM snowboards)");
$statement -> execute($opts);
$results = $statement -> fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
Right now the SELECT query isn't specified, because I don't know how.
If someone knows what I'm doing wrong, or have better suggestion to solve it, please tell.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('form.ajax-form').onclick('login_submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[user_email]').each(function(index, value) {
// console.log(value);
var obj = $(this),
email = obj.attr('user_email'),
value = obj.val();
data[email] = value;
});
obj.find('[user_pass]').each(function(index, value) {
// console.log(value);
var obj = $(this),
pwd = obj.attr('user_pass'),
value = obj.val();
data[pwd] = value;
});
$.ajax({
// see the (*)
url: url,
type: method,
data: data,
success: function(response) {
console.log(response);
// $("#feedback").html(data);
}
});
// console.log('Trigger');
return false; //disable refresh
});
});
</script>
<?php echo form_open('welcome/login', array('class' => 'ajax-form','style'=>'z-index: 202')); ?>
<input name="user_email" type="email" class="login_email" placeholder="Email address" required autofocus>
<br />
<input name="user_pass" type="password" class="login_pass" placeholder="Password" required>
<label class="checkbox">
Forgot login details?
<button class="btn btn-lg btn-info" id="login_submit" style="margin-left:20px;">Sign in</button>
</label>
</form>
<?php if(isset($login_error) && $login_error !=='') { ?><div class="alert alert-danger login_err"><?php echo $login_error; ?></div> <?php } ?>
<!-- </div>-->
Hi i am trying to pass the email and password to the controller in codeigniter.
Any idea how to do that please help?
You could simplify a big deal by doing:
$('#ajax-form').submit(function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(response) {
console.log(response);
// $("#feedback").html(data);
}
});
return false;
});
I have this form in a foreach loop, so it shows multiple times on the same page.
Everything submits fine in each form EXCEPT the radio buttons and checkboxes. They don't save the values to the db.
EDIT: I've narrowed it down to the ajax causing the error but can't figure out how to correct it.
<form action="process.php" method="post" name="editInvoice'.$invoice_id.'" id="editInvoiceForm'.$invoice_id.'" class="editInvoiceForm edit_invoice_container" enctype="multipart/form-data">
<div class="form_item_row">
<input type="radio" value="Unsent" '.$unsent.' name="status"/><span class="choice">Unsent</span>
<input type="radio" value="Sent" '.$sent.' name="status"/><span class="choice">Sent</span>
<input type="radio" value="Paid" '.$paid.' name="status"/><span class="choice">Paid</span>
</div>
<div class="form_item_row">
<label for="include_timelog'.$invoice_id.'">Include Time Log</label>
<input type="checkbox" value="true" '.$include_timelog.' name="include_timelog" id="include_timelog'.$invoice_id.'" />
</div>
<div class="clear"></div>
<div class="form_item_row_btns">
<input type="hidden" value="'.$invoice_id.'" name="hiddenInvoiceID"/>
<input type="submit" class="btn" value="Update Invoice" name="action"/>
</div>
</form>
$query = "UPDATE invoices SET status = ".$db->prep($_POST['status']).", include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);
$(document).ready(function()
{
var action = '';
$(".due_date").datepicker();
$('input[name=action]').click(function(){
action = $(this).val();
});
$(".editInvoiceForm").submit(function() {
$('.editInvoiceForm .form_message').html('<img src="images/loadingAnimation.gif" alt="loadingAnimation" width="30" height="8"/>');
var dataToSend = {};
$(this).find(':input').each(function (i,el) {
dataToSend[el.name] = $(el).val();
});
dataToSend.action = action;
$.ajax({
type: "POST",
url: "process.php",
data: dataToSend,
dataType: "json",
cache: false,
success: function(data){
//console.log(data.status);
if(data.status == 'error'){
$('.editInvoiceForm .form_message').removeClass('status_green').addClass('status_red').html(data.message).append(data.script);
}else{
$('.editInvoiceForm .form_message').removeClass('status_red').addClass('status_green').html(data.message).append(data.script);
}
}
});
return false;
});
});
You need quotes around the value for status in your SQL since the value is a string. Your include_timelog and invoice_id values are integers and do not need quotes.
$query = "UPDATE invoices SET status = '".$db->prep($_POST['status'])."', include_timelog = ".$db->prep((isset($_POST['include_timelog'])?1:0))." WHERE invoice_id = ".$db->prep($invoice_id);