I am adding additional form on button click.
In my form, i have one drop down. When user select value from drop down, i am populating other fields value based drop down selection. You can see in my code i am sending ajax call to retrieve the values before setting them in input field.
code
<script>
$(document).ready(function(){
var index = 0;
$("#testButton").click(function() {
$("#jBuyer").clone().appendTo("#jointBuyer");
index++;
});
});
</script>
When clone done, the form fields along with data copied to next form.
I don't want it to happen because it is a problem? How can i stop it?
With my little knowledge i can understand the problem is with duplicate Name or Id but don't how i can generate them dynamically and then can set their values.
If you interested to know my full code, please see below.
full code
<div id="jointBuyer" class="JointBuyerDive" style="display:none">
<div id="jBuyer">
<div id="inner"class="col-lg-6">
<form id="buyerForm" role="form" method="POST" enctype="multipart/form-data">
<label>Buyer</label>
<div class="form-group">
<label>Unit No.</label>
<select class="form-control" name="junitId" id="junitId" onmousedown="this.value='';" onchange="getUnit(this.value);">
<option>Please Select Unit No</option>
<?php
$sql_query= "select * from tble_units";
$run_query =mysqli_query($con, $sql_query);
while($row = mysqli_fetch_array($run_query )){
$unit_no =$row ['unit_no'];
$unit_ID =$row ['unit_ID'];
?>
<option value="<?php echo $unit_ID;?>"><?php echo $unit_no;?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label>Type</label>
<input type="text" name="unitTypeE" id="unitTypeE" class="form-control" readonly>
</div>
<div class="form-group">
<label>No of Car Parking Purchase</label>
<input type="text" name="noOfCarParkingE" id="noOfCarParkingE" class="form-control" readonly>
</div>
</div>
</div>
<div>
Ajax call
function getUnit(value) {
var dataString = 'id=' + value;
$.ajax({
type: "POST",
url: "getUnitData.php",
data: dataString,
cache: false,
success: function(result) {
var obj = JSON.parse(result);
$('input[name=unitTypeE]').val(obj[0]);
$('input[name=noOfCarParkingE]').val(obj[1]);
$('input[name=floorE]').val(obj[2]);
$('input[name=unitAreaE]').val(obj[3]);
$('input[name=commentsE]').val(obj[4]);
}
});
}
You can reset form after clone it.
Like this code:
var clonedForm = $("#buyerForm").clone();
$("#jBuyer").append(clonedForm);
clonedForm[0].reset();
and then you should set unique id to cloned form:
clonedForm.attr("id","uniqueId");
append after edit:
and then in ajax call you should use this code to change only one dropdown:
first change onchange="getUnit(this)" and then:
function getUnit(obj) {
var currentForm = obj.parents("form");
var dataString = 'id=' + obj.value;
$.ajax({
type: "POST",
url: "getUnitData.php",
data: dataString,
cache: false,
success: function(result) {
var obj = JSON.parse(result);
currentForm.find('input[name=unitTypeE]').val(obj[0]);
currentForm.find('input[name=noOfCarParkingE]').val(obj[1]);
currentForm.find('input[name=floorE]').val(obj[2]);
currentForm.find('input[name=unitAreaE]').val(obj[3]);
currentForm.find('input[name=commentsE]').val(obj[4]);
}
});
}
Related
I need someone to help me please to insert multiple products to cart, adding single one is working fine but I have one product which inserting with no issue and related products which have checkboxes where I need to add it but dont know how
enter image description here
ajax for adding product:
<script>
$(function(){
$('.add_to_cart').on("click", function () {
var id = ($("#item_id").val());
$.ajax({
url: 'cart/' + id+'/edit',
type: "get",
success: function (data) {
$('#myModal').modal('hide');
$('#cart_product').html(data);
}
});
});
});
</script>
add in controller
public function edit(Request $request,$id)
{
$quantity=$request->quantity;
$product=Product::find($id);
Cart::add($id,$product->product_title,$quantity,$product->product_price);
$products = Cart::content();
foreach($products as $Product){
echo '<div class="OrderItem_root styles_base styles_spacing-base">
<div class="OrderItem_quantity styles_just-right styles_base styles_spacing-base">'.$Product->qty.'</div>
<div class="OrderItem_container">
<div class="OrderItem_category"></div>
<div class="OrderItem_itemHeader">
<div id="cartprice" class="OrderItem_total">$'.$Product->price*$Product->qty.'</div>
<input id="mycartprice" type="text" name="mycartprice" value="'.$Product->price.'" hidden="">
</div>
<div>
</div>
<div>
<button class="remove_item OrderItem_action Button_root" data-id="'.$Product->rowId.'" data-price="'.$Product->price*$Product->qty.'" data-qty="'.$Product->qty.'" type="submit">Remove</button>
</div>
</div>
</div>';
}
}
related items
foreach($products as $Product){
echo '<div class="SuggestedItem_container">
<label>
<input id="ppleadd" type="checkbox" onchange = "AutoCalculateMandateOnChange(this)">
<span id="related_item" class="SuggestedItem_name">'.$ProductDetails->product_title.'</span><span class="SuggestedItem_price styles_small styles_base styles_spacing-base">+$'.$ProductDetails->product_price.'</span></div></div>
</div>
</label>';
}
to solve this issue use this
<input id="ppleadd" type="checkbox" class="get_value" data-id="'.$ProductDetails->product_id.'" >
$(document).ready(function(){
$('.testbtn').on("click", function (){
var insert=[];
$('.get_value').each(function(){
if($(this).is(":checked"))
{
insert.push($(this).attr('data-id'));
}
});
insert=insert.toString();
$.ajax({
url:"add-to-cart",
method:"get",
data:{insert:insert},
success:function(data){
} }); }); });
Apparently in the DOM have changed the values, even changed the ID of the form with the idea that the script no longer has effect but when you click Publish, nothing happens. Searching I tried to use "prop" instead of "attr" but it still does not work. I think it's because of the "e.preventDefault ()". But I do not know how to disable it. This is my code.
As you can see once the request is sent, the input and the "send" button are deactivated and when the values are received, they change the id of the form, the id and name of the button and it is renamed "Publish".
<script>
jQuery(function($){
var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
$('[id^="form-search"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
});
</script>
Here my html
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<button id="search" name="search" class="btn btn-success boton">Search</button>
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
Here a fiddle showing that happened (check DOM).
JSFiddle.net
//var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
// when the action is plugin url.
$(document).on('submit','[id^="form-search"]', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/getapi.php',
data : $(this).serialize(),
cache: false,
beforeSend: function(){
$('input#keyword').prop('disabled', true);
$('button#search').prop('disabled', true);
$('#resuls').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
$('input#keyword').prop('value', 'PUBLISH DATA');
$('button#search').prop({disabled: false, id:'publish', name:'publish'}).html('Publish');
$('span#help').hide();
$('[id^="form-search"]').prop('action','publish.php');
$('[id^="form-search"]').prop('id', 'form-publish');
var countResults = $('input#total_data').val();
for (var i = 1; i <= countResults; i++) {
$('#lista>select').clone().prop({ id: "cat_"+i, name: "cat_"+i}).appendTo('.category_'+i);
}
$('#lista').remove();
});
});
// when the action point to publish.php === This is what you need
$(document).on('submit','[id^="form-publish"]', function(e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type : 'POST',
url : url,
data : $(this).serialize(),
cache: false,
beforeSend: function(){
// do your pre-processing
}
}).done(function(data) {
// do your post processing.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="" method="post" class="form-search" id="form-search">
<fieldset>
<!-- Form Name -->
<legend>Name</legend>
<div class="form-group">
<input id="keyword" name="keyword" required="" type="text">
<input type ="submit" id="search" name="search" class="btn btn-success boton">Search</button>
<!-- change the button type to submit type -->
<span class="help-block" id="help">Help</span>
<div id="lista" style="display:none">Test</div>
</div>
</fieldset>
<div id="result"></div>
</form>
I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.
Undefined Index :- File
Here's my code.
HTML
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
Ajax
$("#add_product").click(function(e) {
e.preventDefault();
product_name = $("product_name").val();
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $("#add_new_product").serialize(),
success: function(response) {
//
alert(response);
}
})
});
PHP
if (0 < $_FILES['file']['error']) {
echo ":!";
} else {
echo "ASa";
}
What am I missing here?
Can you try using FormData():
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The above is a sample code, but you may use it to modify it.
you can use FormData
$("#add_product").click(function(e) {
e.preventDefault();
var fdata = new FormData()
fdata.append("product_name", $("product_name").val());
if ($("#file")[0].files.length > 0)
fdata.append("file", $("#file")[0].files[0])
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: fdata,
contentType: false,
processData: false,
success: function(response) {
//
alert(response);
}
})
});
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
We need to acknowledge first is that we need to APPEND both Form Input Data and Form File(s) into a single FormData variable.
Here is my solution in which I have enabled Multi File option so that this solution can fit for all examples.
It is Important to include name attribute in the input controls to make it work properly on server side in most of cases. If you are using C# then you can use simply Request.Form["nameAttribute"] to simply get the function. It is similar for Java and other languages.
My Sample Code is
$(document).ready(function () //Setting up on Document to Ready Function
{
$("#btnUpload").click(function (event) {
//getting form into Jquery Wrapper Instance to enable JQuery Functions on form
var form = $("#myForm1");
//Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
var params = form.serializeArray();
//Getting Files Collection
var files = $("#File1")[0].files;
//Declaring new Form Data Instance
var formData = new FormData();
//Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
//Now Looping the parameters for all form input fields and assigning them as Name Value pairs.
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
//disabling Submit Button so that user cannot press Submit Multiple times
var btn = $(this);
btn.val("Uploading...");
btn.prop("disabled", true);
$.ajax({
url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc
method: "post",
data: formData,
contentType: false,
processData: false,
success: function () {
//Firing event if File Upload is completed!
alert("Upload Completed");
btn.prop("disabled", false);
btn.val("Submit");
$("#File1").val("");
},
error: function (error) { alert("Error"); }
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" id="myForm1">
<p><textarea id="TextArea1" rows="2" cols="20" name="TextArea1"></textarea></p>
<p><input id="File1" type="file" multiple="multiple" /></p>
<input id="btnUpload" type="button" value="Submit" />
</form>
For a working example (asp.net C# with handlers) you can visit sample code on https://github.com/vibs2006/HttpFileHandlerFormDataSample
I'm pretty stuck here.
I'm using a live search lookup script (AJAX) to lookup customers in the database using a input field. Upon selection I click my chosen customer. Then the form I am filling out for the customer is filled with those details from the database. The problem is only some of the time once clicked the fields are populated with data. It is completely intermittent, if I repetitively click the same customer eventually they will populate, it appears as though it works in bursts and fails it appears as though there is no pattern.
Thanks for any help in advance :)
// ########## LIVE SEARCH FUNCTION ########## //
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
// ########## LIVE SEARCH FUNCTION ########## //
// ########## DATA POPULATE FUNCTION ########## // NOT WORKING ALL THE TIME
$( document ).ajaxComplete(function() {
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
$('#custid').val($clicked.find('.customerIdS').text());
$('#firstName').val($clicked.find('.firstNameS').text());
$('#lastName').val($clicked.find('.lastNameS').text());
$('#companyName').val($clicked.find('.companyNameS').text());
$('#streetAddressP').val($clicked.find('.streetAddressS').text());
$('#suburbP').val($clicked.find('.suburbS').text());
$('#stateP').val($clicked.find('.stateS').text());
$('#postcodeP').val($clicked.find('.postcodeS').text());
$('#phoneNumber').val($clicked.find('.phoneNumberS').text());
$('#emailAddress').val($clicked.find('.emailAddressS').text());
});
});
// ########## DATA POPULATE FUNCTION ########## // NOT WORKING ALL THE TIME
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="content" style="float:right;">
<input id="searchid" class="search" type="text" placeholder="Search for customer using first name, last name or company name."></input>
<br></br>
<div id="result" style="display: none;">
<div class="show" align="left">
<div class="selection">
<span class="customerIdS">
3628
</span>
<span class="firstNameS">
David
</span>
<span class="lastNameS">
Dodrel
</span>
-
<span class="companyNameS"></span>
,
<span class="streetAddressS">
101 Woodward Place
</span>
,
<span class="suburbS">
Suburb
</span>
<span class="stateS">
State
</span>
<span class="postcodeS">
Postcode
</span>
<span class="phoneNumberS"></span>
<span class="emailAddressS"></span>
</div>
</div>
</div>
<div id="customerDetails" class="row">
<div class="col-sm-6">
<label for="firstName">First Name</label>
<input type="text" name="firstName" id="firstName">
<label for="lastName">Last Name</label>
<input type="text" name="lastName" id="lastName">
<label for="companyName">Company Name</label>
<input type="text" name="companyName" id="companyName">
</div>
<div class="col-sm-6">
<label for="phoneNumber">Phone Number</label>
<input type="text" name="phoneNumber" id="phoneNumber">
<label for="emailAddress">Email Address</label>
<input type="text" name="emailAddress" id="emailAddress">
</div>
</div>
Try using the code below, instead yours. Also, please, check the comments explaining what i think was wrong with your code.
jQuery(function(){
jQuery(".search").on("keyup", function() {
var searchId, dataString;
searchId = jQuery(this).val();
dataString = "search=" + searchId;
if (searchId) {
jQuery.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html) {
jQuery("#result").html(html).show();
}
});
}
});
jQuery(document).on("click", function(e){
//No need to use "live" here since this whole block of code will be executed once the DOM is ready
var $clicked = jQuery(e.target);
if (!$clicked.hasClass("search")) {
jQuery("#result").fadeOut();
}
});
jQuery("#searchid").on("click", function(){
jQuery("#result").fadeIn();
});
//This is only attached once since your "#results" div is there from the beginning and you only change its content, you don't remove and attach it again.
jQuery("#result").on("click", ".selection", function(e){
//You were getting jQuery(e.target) but i assume it wasn't what you wanted since you were getting the element that was clicked inside "#result" and not "#result" itself (that is where you find your content and then assign values based on it)
var $clicked = jQuery(this);
jQuery('#custid').val($clicked.find('.customerIdS').text().trim());
jQuery('#firstName').val($clicked.find('.firstNameS').text().trim());
jQuery('#lastName').val($clicked.find('.lastNameS').text().trim());
jQuery('#companyName').val($clicked.find('.companyNameS').text().trim());
jQuery('#streetAddressP').val($clicked.find('.streetAddressS').text().trim());
jQuery('#suburbP').val($clicked.find('.suburbS').text().trim());
jQuery('#stateP').val($clicked.find('.stateS').text().trim());
jQuery('#postcodeP').val($clicked.find('.postcodeS').text().trim());
jQuery('#phoneNumber').val($clicked.find('.phoneNumberS').text().trim());
jQuery('#emailAddress').val($clicked.find('.emailAddressS').text().trim());
});
});
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....