I'm trying to post data from a form with an ajax post. Currently I am just debugging this by alerting the data sent, via a php script.
So my code html :
<form id="form_sewa">
<input type="hidden" name="penyewaan" id="penyewaan" value="">
<div class="form-group col-md-12">
<label for="nama_anak">Nama Anak:</label>
<input type="text" data-mini="true" name="nama_anak" id="nama_anak" value="">
</div>
<div class="form-group col-md-12">
<label for="jumlah_uang">Jumlah Uang:</label>
<input type="number" data-mini="true" name="jumlah_uang" pattern="[0-9]" id="jumlah_uang" value="">
</div>
<div class="form-group col-md-12">
<label for="harga_kamar"><b>Harga</b> Kamar:</label>
<input type="number" data-mini="true" name="harga_kamar" pattern="[0-9]" id="harga_kamar" value="">
</div>
<div class="form-group col-md-12">
<!-- Untuk tanggal -->
<label for="tanggal_masuk">Tanggal <b>Masuk:</b></label>
<input id="tanggal_masuk" name="tanggal_masuk" data-mini="true" />
</div>
<br>
<div class="form-group col-md-12">
<label for="tanggal_keluar">Tanggal <b>Keluar:</b></label>
<input id="tanggal_keluar" name="tanggal_keluar" data-mini="true" />
</div>
<br>
<div class="form-group col-md-12">
<label for="no_kamar"><b>Nomor</b> Kamar:</label>
<input type="number" data-mini="true" name="no_kamar" pattern="[0-9]" id="no_kamar" value="">
</div>
<input type="submit" data-role="button" data-theme="f" data-inline="true" data-icon="check" id="submitSwa" />
Kembali
</form>
In JavaScript
$(document).ready(function(){
$("#submitSwa").click(function(){
$.ajax({
url: "http://localhost/apri2/php/crudpenyewaan.php",
type: "post",
cache:false,
data: {
nama_anak: $('#nama_anak').val(),
jumlah_uang: $('#jumlah_uang').val(),
harga_kamar: $('#harga_kamar').val(),
tanggal_masuk: $('#tanggal_masuk').val(),
tanggal_keluar: $('#tanggal_keluar').val(),
no_kamar: $('#no_kamar').val()
},
success: function(response){
alert(response);
},
error: function(){
alert('Error while request..');
},
complete: function() {
$.mobile.loading("hide");
}
});
});
});
And in php
<?php
print_r($_POST);
?>
I have tried methods like submithandler, formdata serialize, but the alert doesn't show up and my url looks like this after clicking submit:
Related
When i submit form it doesnot update value in database mysql.Its a form written in php.
here is my php and html. I want that the form should not reload and it must submit the changes in database without reloading the page and show preloader for 1 sec on submitting form.
HTML,PHP AND ACTION of form: Here action is the current page where this form is avalilable
detail_customer.php
<?php
$server = "localhost";
$username = "root";
$pass = "";
$dbname = "stinkspolitics_pl";
$conn = mysqli_connect($server, $username, $pass, $dbname);
if (isset($_GET['detail_customer'])) {
$quest_id = $_GET['detail_customer'];
$get_quest = "SELECT * FROM questions WHERE quest_id = '$quest_id'";
$getting_quest = mysqli_query($conn, $get_quest);
while ($row = mysqli_fetch_assoc($getting_quest)) {
$quest_title = $row['quest_title'];
$category_id = $row['category_id'];
}
}
if (isset($_POST['submit'])) {
$quest_t = $_POST['quest_t'];
$update = "UPDATE questions SET quest_title = '$quest_t' WHERE quest_id = '$quest_id'";
$run_update = mysqli_query($conn, $update);
if ($run_update) {
echo 'hello';
}
}
?>
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php
" method="POST" class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<?php echo $category_id ?>" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<?php echo $quest_title ?>" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
JS Code
index.js
$("#form-submit").on("submit", function () {
// e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: formData,
success: function (data) {
$(".alert-success").show();
$(".alert-success").fadeOut(4000);
console.log(data);
},
error: function (data) {
$(".alert-danger").show();
$(".alert-danger").fadeOut(4000);
console.log(data);
},
});
return false;
});
Ajax Success Response But not updating data in mySQL
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php" method="POST"
class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<br />
<b>Warning</b>: Undefined variable $category_id in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>62</b><br />
" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<br />
<b>Warning</b>: Undefined variable $quest_title in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>66</b><br />
" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
The condition if (isset($_POST['submit'])) { will never evaluate to true, since there is no input element in the form with name="submit" (the button with name='submit' does not send the attribute by default).
Either change the condition:
if (isset($_POST['quest_t'])) { ...
Or, include an input element with name='submit', for example:
<input name="submit" type="hidden" />
Also, make sure to move the $_POST check at the beginning of the file and ensure that no other code will be evaluated in the PHP file (e.g. the rest of the HTML code) if a POST request has been received.
Just return false after at the end of the method.
jQuery has its own way of ensuring "preventDefault()" and it is just returning false from the submit handler.
Full background on this here:
event.preventDefault() vs. return false
Issue has been solved. By changing path and then putting path of js file again.
I currently have a form that is multi-step; it doesn't do anything fancy per step, it simply does display: none on the previous step to hide the previous fields and move the user forward.
It submits via AJAX and has required fields.
Is there any way to capture the data from each step of the form, and then, if the user drops off or never submits the form, send the captured data - I'm not worried about any issues in regards to data protection, as it doesn't apply in this situation.
The form basically looks like this:
<form>
<div class="step-1">
<label>First Field
<input type="text" id="field1" name="field1" maxlength="50">
</label>
<label>Second Field
<input type="text" id="field2" name="field2" maxlength="50">
</label>
next step
</div>
<div class="step-2">
<label>Third Field
<input type="text" id="field3" name="field3" maxlength="50">
</label>
<label>Fourth Field
<input type="text" id="field4" name="field4" maxlength="50">
</label>
<input type="submit" id="send" name="submit" />
<span id="submitdata"></span>
</div>
</form>
The bit I'm struggling with is knowing when the user drops... Does it need to invoke some kind of session per the form?
You could automatically submit the form when the user leaves the page, using the beforeUnload event:
var notSubmitted = true;
$('form').on('submit', function() { notSubmitted = false; });
$(window).on("beforeunload", function() {
return notSubmitted ? $('form').submit() : null;
})
$("form").submit(function (e) {
e.preventDefault();
// ... ajax submission goes here ...
return false;
});
If you need to record that it is a 'by default' submission, then you could use a hidden form element instead of the variable notSubmitted. The hidden element would give you that data in the form.
Try this code:
$(document).ready(function () {
//alert("hi");
setTimeout(function () {
$("#msg").hide(1000);
}, 3000);
$("form#product_form").submit(function (e) {
//alert('hi');
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '<?php echo site_url('C_home/pro_add'); ?>',
type: "POST",
data: formData,
dataType: "json",
contentType: false,
processData: false,
success: function (result) {
//alert(result);
$("#product_form").trigger('reset');
window.location.href = "<?php echo site_url('C_home/data_tbl'); ?>";
}
});
return false;
});
$("#product_form").validate({
rules: {
name: "required",
category_id: "required",
image: "required",
description: "required",
qty: "required",
price: "required"
},
messages: {
name: "Product name is required",
category_id: "Please Select Category name",
image: "Plases Select Product Image",
description: "Product Description is required",
qty: "Product Quantity is required",
price: "Product Price is required",
}
})
});
<script src="<?php echo base_url(); ?>assets/js/jquery.bootstrap.wizard.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.validate.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/wizard.js"></script>
<div class="wizard-container">
<div class="card wizard-card ct-wizard-orange" id="wizard">
<form id="product_form" method="POST" enctype="multipart/form-data">
<div class="wizard-header">
<h3>
Jquery Accordion
</h3>
</div>
<ul>
<li>Product Panel 1</li>
<li>Product Panel 2</li>
<li>Product Panel 3</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="about">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="form-group">
<label>Product Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Product Name" required="" />
</div>
<div class="form-group">
<label>Select Category</small></label>
<select class="form-control" id="category_id" name="category_id" required="">
<option></option>
<!-- <option>--Select Category Name--</option> -->
<?php
foreach ($category as $row) {
?>
<option value="<?php echo $row['category_id']; ?>"><?php echo $row['category_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="account">
<div class="row">
<div class="col-sm-4 col-sm-offset-1">
<div class="picture-container">
<div class="picture">
<img src="<?php echo base_url(); ?>assets/img/default-avatar.png" style="height: 100px;" class="picture-src" id="wizardPicturePreview" title=""/>
<input type="file" class="form-control" name="image" id="wizard-picture" required="">
</div>
<h6>Choose Picture</h6>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Product Description</label>
<textarea class="form-control" name="description" id="description" placeholder="Enter Product Description" rows="5" required></textarea>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="address">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="form-group">
<label>Product Qty</label>
<input type="text" class="form-control" name="qty" id="qty" placeholder="Enter Product Qty" required />
</div>
<div class="form-group">
<label>Product Price</label>
<input type="text" class="form-control" name="price" id="price" placeholder="Enter Product Price" required />
</div>
</div>
</div>
</div>
</div>
<div class="wizard-footer">
<div class="pull-right">
<button type='button' class='btn btn-next btn-fill btn-warning btn-wd btn-sm' name='next' id="next" />Next</button>
<button type='submit' class='btn btn-finish btn-fill btn-warning btn-wd btn-sm' name='submit' value='Submit' />Submit</button>
</div>
<div class="pull-left">
<input type='button' class='btn btn-previous btn-fill btn-default btn-wd btn-sm' name='previous' id="prev" value='Previous' />
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</div>
I am using twitter bootstrap file upload, i want to store the image on databese and also i want to move in one folder,i spent lot of times, i can't get the file name value. see here enter firstname and select one image after submit the form ,now i got first name value but i cant get photo upload value...
<form class="form-horizontal form-bordered" method="POST" id="newUserForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-3 control-label">First Name<span class="star_mark"> *</span></label>
<div class="col-sm-6">
<input type="text" class="form-control" id="fname" name="fname" value="" aria-required="true" required="" data-msg-required="Please enter your firstname" placeholder="Enter your firstname">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Photo Upload<span class="star_mark"> *</span></label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="file" name="file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-info btn-block" type="submit" id="user-submit">Submit</button>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#user-submit').click(function(event){
event.preventDefault();
if($('#newUserForm').valid()){
//console.log('success');
$.ajax({
type:'POST',
url :"php/register-newuser.php",
data: $('form#newUserForm').serialize(),
success: function(data) {
//var res=jQuery.parseJSON(data);// convert the json
console.log(data);
},
error:function(exception){
alert('Exeption:'+exception);
}
});
}
else{
console.log('please select all fields');
}
});
});
</script>
register-newuser.php
$fstname=$_POST['fname'];// i got ans here
$filename = basename($_FILES['file']['name']);
$newuser = array("fstName" => $fstname,'photoname' => $filename);
echo json_encode($newuser);
print_r($_FILES)//means nothing will happen, i didn't get any value like filename,size,extension....
To make an upload with AJAX you can use a jQUery plugin, for example this one. Bootstrap has nothing to do with upload.
I have form where i want to submit the whole data everything is fine except the radio button. The problem occurs when the radio buttons are in controller scope but they work fine out of controller scope. i am getting all other fields value properly except the radio button and i dont know where i am making mistake i am confuse why its not working...
Here is the angular script which is working fine...
//handling form controller
app.controller('myForm',function($http,$scope){
$scope.formData={};
$scope.saveCashbook=function()
{
console.log(this.formData);
$http({
method: "POST",
url: 'cashbook/save_cash_entry',
data: $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data) {
if (data.status == 'success') {
alert('all okay');
} else {
alert(data)
}
});
}
});
Here is my html in which two way data-binding isnt working while the radio buttons are in scope and when i placed them out from controller scope two way data binding start working but than i wont be able to get my radio button value in my controller where i am saving them to database.
<div class="col-sm-12" ng-controller="myForm">
<form name="supplier_form" id="myform" ng-submit="saveCashbook()" >
<div class="form-group col-sm-2" style="padding-top:30px;">
<label for="" class="label label-info">جمع</label>
<label class="control-label radio-inline">
<input type="radio" class="purple" value="jama" name="jamabanam" ng-model="formData.jamabanam" >
</label>
<label for="" class="label label-danger">بنام</label>
<label class="control-label radio-inline">
<input type="radio" class="purple" value="banam" name="jamabanam" ng-model="formData.jamabanam" >
</label>
</div>
<div class="form-group col-sm-2">
<label for="packing" class="control-label">رجسٹر</label>
<select id="register" name="register_id" ng-model="formData.register_id" class="form-control search-select two" >
<option value=""> </option>
<? $query=$this->dba->get_dropdown('register',array('id','name'));
foreach($query as $key=>$value):
?>
<option value="<?=$key?>"><?=$value; ?></option>
<? endforeach;?>
</select>
</div>
<div class="form-group col-sm-4">
<label for="raqam" class="control-label">نام</label>
<select id="name" name="name" ng-model="formData.name" class="form-control search-select two"></select>
</div>
<div class="form-group col-sm-2 has-error">
<label for="nuqsani-raqam" class="control-label">کھاتہ نمبر</label>
<input type="text" class="form-control" name="khata_id" ng-model="formData.khata_id" id="khata_no" >
</div>
<div class="form-group col-sm-2 has-success">
<label for="nuqsani-raqam" class="control-label">رقم</label>
<input type="text" name="raqam" class="form-control" ng-model="formData.raqam" id="raqqam">
</div>
<div class="form-group col-sm-12">
<label for="raqam" class="control-label">تفصیل</label>
<input type="text" name="details" ng-model="formData.details" id="details" class="form-control" >
</div>
<input type="submit" value="submit" name="submit" id="submit">
</form>
</div>
Here is my php function where i am priniting the whole $_POST
public function save_cash_entry()
{
print_r($_POST);
exit();
}
I have a html form as follows:-
<form class="form-horizontal" role="form" method="post" action="" id="scheduler_form">{%csrf_token%}
<div class="form-group">
<label for="url" class="col-sm-3 control-label">URL</label>
<div class="col-sm-6">
<input type="url" name="url" class="form-control">
</div>
</div>
<div class="form-group">
<label for="reporttemplate" class="col-sm-3 control-label">SELECT REPORT TEMPLATE</label>
<div class="col-sm-4">
<select name="report_template_id" id="report_list_sel" class="form-control" data-placeholder="Choose a Template" required="required"></select>
</div>
</div>
<div class="form-group">
<label for="frequency" class="col-sm-3 control-label">FREQUENCY</label>
<div class="col-sm-9">
<label class="radio-inline" for="inlineRadio1">
<input type="radio" name="frequency" id="inlineRadio1" value="hourly" checked="checked">Hourly</label>
<label class="radio-inline">
<input type="radio" name="frequency" id="inlineRadio2" value="Daily">Daily</label>
<label class="radio-inline">
<input type="radio" name="frequency" id="inlineRadio3" value="Weekly">Weekly</label>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-3 control-label">EMAIL</label>
<div class="col-sm-6">
<input type="email" name="email" class="form-control">
</div>
</div>
<label for="alerts" class="col-sm-3 control-label" style="padding-right:23px">ALERTS</label>
<div class="form-group">
<div class="checkbox col-sm-offset-3" id="alert_list" style="height:100px;overflow-y:auto"></div>
</div>
<button type="submit" class="btn btn-warning pull-right" id="create_schedule">CREATE</button>
<button type="button" class="btn btn-default pull-right closediv" data-dismiss="setup_blk" aria-label="Close">CANCEL</button>
</form>
I have a generic method to make an Ajax call.
function makeAJAXRequest(_uri, _method, _data, _contenttype, _datatype, _context, _processdata, _successHandler, _errorHandler){
var _jqXHR = $.ajax({
url: _uri,
type: _method,
data: _data,
contentType: _contenttype,
dataType: _datatype,
context: _context,
processData: _processdata,
cache: true
});
_jqXHR.done( _successHandler );
_jqXHR.fail( _errorHandler );
}
Now I am binding create_schedule button as follows.
$('#create_schedule').on('click', function (event) {
// Call a function createScheduler to build json data for AJAX - POST call and get response.
createScheduler();
});
function createScheduler() {
var _schedulerData = {};
$.each($('#scheduler_form'), function () {
_schedulerData[this.name] = this.value;
console.log(_schedulerData);
});
makeAJAXRequest(
API_SCHEDULE,
'post', _schedulerData,
'',
'json', {},
true,
createUserScheduleSuccessHandler,
createUserScheduleErrorHandler);
function createUserScheduleSuccessHandler(_data) {
console.log(_data);
}
function createUserScheduleErrorHandler(jqXHR, textStatus, errorThrown) {
console.log('Error')
}
}
Now I am getting confused as how to populate the form data and make the post request. Any help here.
Change
<button type="submit" class="btn btn-warning pull-right" .... >
To
<button type="button" class="btn btn-warning pull-right" .....>
OR:
you can call the prevenDefault method when button click fired.
event.preventDefault();
console.log( $( '.form-horizontal' ).serialize() );
serializing the form will get all the data from form controls.