How to populate this form data and post it with jquery - javascript

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.

Related

How to submit form including image on button click [duplicate]

This question already has answers here:
Sending formdata for file upload using ajax
(3 answers)
Closed 9 months ago.
I have this HTML:
<form id="form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<div class="mb-3">
<label for="design_title" class="form-label">Ttile of the design</label>
<input type="text" name="design" class="form-control" id="design_title">
</div>
</div>
<div class="col">
<div class="mb-3">
<label for="design" class="form-label">Upload a new design</label>
<input type="file" name="design" class="form-control" id="design">
</div>
</div>
</div>
<div class="mb-3">
<div class="row">
<div class="col">
<label for="fontsize" class="form-label">Enter the font size</label>
<input type="number" name="design_font_size" class="form-control" id="fontsize">
</div>
<div class="col">
<label for="position_x" class="form-label">Position X</label>
<input type="number" name="design_x" class="form-control" id="position_x">
</div>
<div class="col">
<label for="position_y" class="form-label">Position Y</label>
<input type="number" name="design_y" class="form-control" id="position_y">
</div>
</div>
</div>
<div class="mb-3">
<label class="form-label" for="domain">Choose a domain</label>
<select name="domain" id="domain" class="form-control" data-form="design_output">
<option value="">--Choose--</option>
<?php
$get_domain = mysqli_query( $mysqli, "SELECT * FROM eg_domains");
if( mysqli_num_rows( $get_domain ) > 0 ) {
while( $get_result = mysqli_fetch_array( $get_domain, MYSQLI_ASSOC ) ) {
$domain_name = $get_result['domain_name'];
$company = $get_result['company_name'];
$domain_id = $get_result['domain_id'];
echo "<option value='$domain_id'>$domain_name ($company)</option>";
}
}
?>
</select>
</div>
<button type="button" class="btn btn-primary ajax-btn output-desing" data-form="output_design">Output Design</button>
<button type="submit" class="btn btn-success ajax-btn">Save Design</button>
<div class="mt-3">
<div class="result"></div>
</div>
</form>
Now, on Output Design button click I want to get all the data including image.
So, I am doing this in JQuery/Ajax:
$(document).on("click", ".output-desing", function (e) {
e.preventDefault();
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = $("#form").serialize() + "&form=" + form_name;
// var data = '1';
console.log(data);
$.ajax({
dataType: "html",
type: "GET",
url: 'helper/process.php',
data: data,
contentType: false,
cache: false,
processData: false,
beforeSend: function () {
$(".output-design").val("Please wait...");
},
success: function (data) {
$(".output-design").html(data);
}
});
});
But I can get only form data not image data.
How can I get all the data including image data on that button click?
Anyways, I fix it this way:
var form = document.querySelector(".output-desing");
var form_name = form.dataset.form;
var data = new FormData(document.getElementById("form"));
data.append('form', form_name);

how to upload files from 2 different file input in from with ajax using formData?

I'm trying to upload 2 file which is in form with ajax but when i print_r($_POST) and print_r($_FILES) it showing me empty array.
here is my html code:
<form id="addFloorEntityTypeFrom" method="POST" action="api/apiRoute.php" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
</div>
</form>
here is my JavaScript code.
var formData = new FormData();
var formDataArray = $(form[0]).serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: baseUrl + 'newIFPAdmin/api/apiRoute.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
this is my server side code..
print_r(json_decode(file_get_contents('php://input'), true));
print_r($_POST);
print_r($_FILES);
exit;
response is:
Array
(
)
Array
(
)
Please try this code. It's working fine. Review screenshot.
https://ibb.co/wJWLfW5
<form id="addFloorEntityTypeFrom" method="POST" action="" enctype="multipart/form-data boundary=----WebKitFormBoundary0BPm0koKA">
<div class="col-md-12">
<div class="form-group">
<label for="categories">Category *</label>
<select class="form-control" id="categories" name="category" required>
<option value="">Please select category</option>
<?php foreach ($categories as $category) {
echo "<option value=\"" . $category['entityTypeId'] . "\">" . $category['entityName'] . "</option>";
} ?>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="typeSVG" class="sr-only">Upload SVG *</label>
<div class="input-group">
<input type="text" name="filename" class="form-control custom-file" placeholder="Please select base svg file" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="typeSVG" name="entityTypeBaseSVG" onchange="this.form.filename.value = this.files.length ? this.files[0].name : ''" required/>
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label for="baseImage" class="sr-only">Upload style Image *</label>
<div class="input-group">
<input type="text" name="baseImage_filename" class="form-control custom-file" placeholder="Please base style image" readonly>
<span class="input-group-btn">
<div class="btn btn-dark custom-file custom-file-uploader">
<input type="file" id="baseImage" name="base_style_image" onchange="this.form.baseImage_filename.value = this.files.length ? this.files[0].name : ''" required />
Browse
</div>
</span>
</div>
</div>
</div>
<div class="col-md-12">
<button type="button" name="addFloorEntity" onclick="SaveEntity(this, true)" class="btn btn-dark mt-3">Save</button>
<button type="button" onclick="closeBaseEntity()" class="btn btn-default mt-3">Cancel</button>
<script>
function SaveEntity()
{
var formData = new FormData();
var formDataArray = $("form").serializeArray();
for(let i = 0; i < formDataArray.length; i++) {
if(formDataArray[i].name !== 'entityTypeBaseSVG' || formDataArray[i].name !== 'base_style_image') {
formData.append(formDataArray[i].name, formDataArray[i].value);
}
}
formData.append('entityTypeBaseSVG', $('#typeSVG')[0].files[0]);
formData.append('base_style_image', $('#baseImage')[0].files[0]);
$.ajax({
method: "POST",
url: 'demo.php',
data: formData,
cache: false,
contentType: false,
processData: false,
}).done(function (response) {
console.log('response', response);
});
}
</script>

Jquery Mobile Ajax Post Insert Data

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:

Collect data from form, stack in object and send it with AJAX using Vue

Trying to collect all the HTML data from my form, then to store it as an object and then send it using ajax request. Any ideas, please? Appreciate some help. I was trying with serialize's jquery, but read this in that way cannot be sent (to an API URL, no PHP) using ajax(post).
<form class="form" action="" method="" id="createProposal">
<div class="form-group">
<label class="col-md-12 control-label" for="asset-drop">Asset</label>
<div class="col-md-12">
<select id="asset-drop" name="asset-drop" class="form-control" >
<option value="1"> {{ this.assets[0] ? this.assets[0].name : '' }} </option>
<option value="2">{{ this.assets[1] ? this.assets[1].name : '' }}</option>
<option value="3">{{ this.assets[2] ? this.assets[2].name : '' }}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="amount-invest">Amount</label>
<div class="col-md-12">
<input id="amount-invest" name="amount-invest" type="text" placeholder="Currency" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="description-input">Description</label>
<div class="col-md-12">
<textarea class="form-control" id="description-input" name="description-input"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary cancel" v-on:click="hideCreatePropolsal">Cancel</button>
<button type="submit" class="btn btn-primary create" v-on:click="formDataCreation">Create</button>
</div>
</form>
i suggest to create an object in your data section which you call proposal and bind your form to that object using v-model, i'm using single file component but it doesn't matter, you can fit that solution to your case :
<template>
<form class="form" action="" method="" id="createProposal">
<div class="form-group">
<label class="col-md-12 control-label" for="asset-drop">Asset</label>
<div class="col-md-12">
<select id="asset-drop" name="asset-drop" class="form-control" v-model="proposal.selectedAsset" >
<option :value="index" :key="index" v-for="(asset,index) in proposal.assets">{{asset}} </option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="amount-invest">Amount</label>
<div class="col-md-12">
<input id="amount-invest" v-model="proposal.amount" name="amount-invest" type="text" placeholder="Currency" class="form-control input-md">
</div>
</div>
<div class="form-group">
<label class="col-md-12 control-label" for="description-input">Description</label>
<div class="col-md-12">
<textarea class="form-control" v-model="proposal.description" id="description-input" name="description-input"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary cancel" v-on:click="hideCreatePropolsal">Cancel</button>
<button type="submit" class="btn btn-primary create" v-on:click="formDataCreation">Create</button>
</div>
</form>
</template>
<script>
export default {
data(){
return{
proposal:{
assets:[],
selectedAsset:'',
amount:'',
description:''
}
}
},
methods:{
hideCreatePropolsal(){
},
formDataCreation(){
/* $.ajax({
url: "yourUrl",
type: "POST",
data:this.proposal,
success: function (response) {
}});*/
}
}
};
</script>
<style>
</style>
you could check the whole code

fileupload is not working in twitter bootstrap

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.

Categories