Hi i am trying to submit a form in bootstrap modal. This modal is going to open based on a href click event. This a href tag is going to b generated dynamically in ajax call using Jquery.
format of the a href tag is below to call bootstrap modal.
'<a id="addvideo" data-toggle="modal" data-title="'+field.title+'" data-id="'+field.video_id+'" data-desc="'+field.description+'" data-channelname="'+field.channel_name+'" data-yudate="'+field.created_date+'" href="#form-content">'+field.title+'</a>'
The modal which i am calling is below shown.
<div id="form-content" class="modal hide fade in" style="display: none;">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Add Video</h3>
</div>
<div class="modal-body">
<form name="addvideo" class="form-horizontal" action="#" id="addchannelvideo">
<div class="control-group">
<label class="control-label" for="videotitle">Title</label>
<div class="controls">
<input type="text" id="videotitle" name="videotitle">
</div>
</div>
<div class="control-group">
<label class="control-label" for="videoid">Video ID</label>
<div class="controls">
<input type="text" id="videoid" name="videoid">
</div>
</div>
<div class="control-group">
<label class="control-label" for="videodesc">Description</label>
<div class="controls">
<textarea id="videodesc" name="videodesc"></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="channelname">Channel</label>
<div class="controls">
<input type="text" id="channelname" name="channelname">
</div>
</div>
<div class="control-group">
<label class="control-label" for="actors">Actors</label>
<div class="controls">
<input type="text" id="actors" name="actors">
</div>
</div>
<div class="control-group">
<label class="control-label" for="directors">Directors</label>
<div class="controls">
<input type="text" id="directors" name="directors">
</div>
</div>
<div class="control-group">
<label class="control-label" for="producers">Producers</label>
<div class="controls">
<input type="text" id="producers" name="producers">
</div>
</div>
<div class="control-group">
<label class="control-label" for="musicians">Music Directors</label>
<div class="controls">
<input type="text" id="musicians" name="musicians">
</div>
</div>
<div class="control-group">
<label class="control-label" for="cast">Cast</label>
<div class="controls">
<input type="text" id="cast" name="cast">
</div>
</div>
<div class="control-group">
<label class="control-label" for="yudate">Youtube Uploaded Date</label>
<div class="controls">
<input type="text" id="yudate" name="yudate">
</div>
</div>
<div class="control-group">
<label class="control-label" for="cudate">CMS Uploaded Date</label>
<div class="controls">
<input type="text" id="cudate" name="cudate">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="orderno">Priority video
</label>
<label class="checkbox">
<input type="checkbox" id="hidevideo">Hide in Mobile App
</label>
<button class="btn btn-success" id="submit"><i class="icon-white icon-ok"></i> Submit</button>
<button class="btn btn-inverse"><i class="icon-white icon-circle-arrow-left"></i> Cancel</button>
</div>
</div>
</form>
</div>
</div>
Now to call modal based on click i am using below javascript code and in this code only i am passing data to modal by setting text boxes values in modal using Jquery like below.
$(document).on("click", "#addvideo", function () {
var videoid = $(this).data('id');
var videotitle = $(this).data('title');
var videodesc = $(this).data('desc');
var channelname = $(this).data('channelname');
var yudate = $(this).data('yudate');
$(".modal-body #videoid").val( videoid );
$(".modal-body #videotitle").val( videotitle );
$(".modal-body #videodesc").val( videodesc );
$(".modal-body #channelname").val( channelname );
$(".modal-body #yudate").val( yudate );
});
Ajax call function is below one.
$(document).ready(function(e) {
$('input#submit').click(function() {
var title = $('#videotitle').val();
var videoid = $('#videoid').val();
var description = $('#videodesc').val();
var channel = $('#channelname').val();
var actors = $('#actors').val();
var directors = $('#directors').val();
var producers = $('#producers').val();
var musicians = $('#musicians').val();
var cast = $('#cast').val();
var yudate = $('#yudate').val();
var orderno = 0;
if($("#orderno").is(':checked'))
{
var orderno = 1;
}
var hidevideo = 0;
if($("#hidevideo").is(':checked'))
{
var hidevideo = 1;
}
var postdata = "title="+title+"&videoid="+videoid+"&description="+description+"&channel="+channel+"&actors="+actors+"&directors="+directors+"&producers="+producers+"&musicians="+musicians+"&cast="+cast+"&orderno="+orderno+"&hidevideo="+hidevideo+"&yudate="+yudate;
$.ajax({
type: 'POST',
url: 'addvideo.php',
data: "title="+title+"&videoid="+videoid+"&description="+description+"&channel="+channel+"&actors="+actors+"&directors="+directors+"&producers="+producers+"&musicians="+musicians+"&cast="+cast+"&orderno="+orderno+"&hidevideo="+hidevideo+"&yudate="+yudate,
datatype:'json',
success: function(response) {
$("#form-content").modal('hide');
alert(response);
},error: function(){
alert("video categorization failed");
}
});
});
});
Now my modal is loading fine and values are showing up in assigned text boxes once the modal loaded on click on href tag. But after click on submit it is redirecting to the same php url and all the parameters are adding as query parameters and weird thing is if i open modal second time and try to submit ajax call is working.
$('input#submit').click(function(e) {
e.preventDefault();//
.....rest of the code here
});
if the form elements are loaded dynamically then try delegating click
$(document).on("click", "#submit", function (e) {
e.preventDefault();
});
try using following tested and workinf code for AJAX call
// Get the form data. This serializes the entire form. pritty easy huh!
var form = new FormData($('#form_step4')[0]);
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
You need to load jQuery for this.
Related
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);
I am trying to post a form with dynamic set value on click event by getting undefined respose Here is my code.
$( ".paymentselect" ).click(function() {
var bookingid=$(this).data('id');
$('#paymentstats').css('display','block');
$('#paymentform').attr('action', document.location.origin +"/accounts/" + bookingid);
});
$('#paymentform').submit(function(event){
event.preventDefault();
var data=$('#paymentform').serialize();
$.ajax({
url: $(this).attr('action'),
method: 'POST',
data: data,
beforeSend: function() {
// setting a timeout
$('#wait').html('<i class="material-icons">cached</i>');
},
success: function(data){
if(data.status){
$('#paymentstats').css('display','none');
alert("UPDATED");
//location.reload();
}else
{
alert("something went wrong");
}
}
});
});
On POST bookingid is Undefind. Little Help will be appriciated
EDITED :
<table>
<tr>
<td>
<button class="paymentselect" data-id="NH7003687415654"> Update</button>
</td>
</tr>
<table>
<div id="paymentstats" class="custom-modal">
<!-- Modal content-->
<div class="modal-content">
<div class="card" style="margin-bottom:0px">
<form id="paymentform" method="POST"> //form that will be posted
<div class="body">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<div class="form-line">
<input type="text" class="form-control" id="utr" name="utr" placeholder="" required>
<input type="hidden" class="form-control" id="bookingpaymentid" name="id" placeholder="">
</div>
<label class="small-label" for="utr">Payment UTR(if any)</label>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<div class="form-line">
<input type="text" class="form-control" id="ref" name="ref" placeholder="" required>
</div>
<label class="small-label" for="ref">Payment Ref</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="spin" id="wait"></div>
<button type="submit" class="btn btn-raised bg-pink waves-effect">Submit</button>
<button type="button" class="btn btn-raised bg-red waves-effect" id="close-btn">Close</button>
</div>
</form>
</div>
</div>
As requested Above is my html Code As requested.
I ALREADY TRIED SETTING bookingpaymentid Val on click event But It Also shows Undefined when Form is POST On the Server.
I just figured out that value become undefined when i post form . Any Suggestion
Because you declare bookingid inside $( ".paymentselect" ).click(function() {.
You can try this:
var bookingid = null;
$( ".paymentselect" ).click(function() {
bookingid=$(this).data('id');
$('#paymentstats').css('display','block');
$('#paymentform').attr('action', document.location.origin +"/accounts/" + bookingid);
});
In plunker bookingid is not undefined. Go to plunker address and check browser console to see variable's values.
You might be having trouble to load order of your scripts file. As you can see in plunker make sure to load your js codes end of the body tag.
I have created a view as:
<div class="container" style="padding-top:20px">
<div class="row">
#foreach (var item in Model)
{
<div class="col-lg-4" style="padding-top:20px;">
<div class="card" style="width:18rem">
<img src="#Url.Content(item.ImagePath)" class="card-img-top" />
<div class="card-body">
<div class="row">
<h5 class="card-title">#item.ProductName</h5>
<p style="color:crimson"> ( Rs #item.ProductPrice )</p>
</div>
#*Details*#
<button class="btn btn-primary btndetails" data-product-id="#item.Id" #*data-target="#loginModal" data-toggle="modal"*#>Details</button>
</div>
</div>
</div>
}
</div>
when I click the Details button the JavaScript function is invoked in which I am making an ajax call to Admin controller and GetProduct actionMethod which takes an Id, Gets the data with that id and returns a JSON object:
<script>
$(document).ready(function () {
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
}
});
});
});
</script>
Its all working correct until here, I get the object in success function response object but now I want to display that object in a MODAL that I have created as:
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="modal fade" data-backdrop="static" id="loginModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"> Details</h4>
<button class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
#using (Html.BeginForm())
{
}
</div>
<div class="modal-footer">
<button class="btn btn-success">Save</button>
<button class="btn btn-primary" data-dismiss="modal">Close</button>
<button class="btn btn-danger">Delete</button>
</div>
</div>
</div>
</div>
</div>
So in short I want to display the object I received in JavaScript Response object in MODAL I created.
Wait it looks like you are trying to use ASP.Net rendering engine (which is generated during request on SERVER side) to render a result of an AJAX request which is performed by the client.
Sorry friend but that's just not going to work.
I mean if you really have to use ASP.Net to render that form, I'd suggest creating a separate view which just returns the form (Html.BeginForm()) section, then use jquery to paste that into the modal-body class as a raw html.
$('.modal-body').html(response);
It'd be a really bad solution from a MVC point of view and I'd advise against that, but it'd get the job done.
I am succesful in woring out the solution as :
I used getElementById and value functions to get the MODAL input field and then used value function to set the values in response object to MODAL input fields.
My AJAX Call is :
$(".btndetails").on("click", function () {
$.ajax({
method: "POST",
url: "/Admin/GetProduct/" + $(this).attr("data-product-id"),
success: function (response) {
var pName = document.getElementById("pName");
pName.value = response.ProductName;
var pPrice = document.getElementById("pPrice");
pPrice.value = response.ProductPrice;
var pDPrice = document.getElementById("pDPrice");
pDPrice.value = response.DiscountPrice;
var imgTitle = document.getElementById("imgTitle");
imgTitle.value = response.ImageTitle;
var stock = document.getElementById("stock");
stock.value = response.Stock;
var description = document.getElementById("description");
description.value = response.Description;
var img = document.getElementById("img");
img.value = response.ImagePath;
$("#img").attr("src", img);
}
});
});
And the modal i created below it is :
<div class="modal-body">
<form>
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Product Name</label>
<input id="pName" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div>
<img src="" id="img" width="150px" height="150px" style="float:right" />
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Product Price</label>
<input id="pPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Discount Price</label>
<input id="pDPrice" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Image Title</label>
<input id="imgTitle" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Quantity in stock</label>
<input id="stock" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="exampleInputEmail1">Description</label>
<input id="description" type="text" class="form-control" aria-describedby="emailHelp" placeholder="Enter email">
</div>
<div class="form-group col-lg-6">
<div class="col-lg-6">
<label for="exampleInputEmail1">Category</label>
#Html.DropDownList("Category", new SelectList((System.Collections.IEnumerable)ViewData["Category"], "Id", "CategoryName"), new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
</form>
</div>
Anfinal outpur is like :
function slideupSubmit (name) {
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post(target,
$(this).serialize() + '&' + $.param({ 'formName':formName, response : response}),
function (data) {
$(response).html(data);
$(name).hide();
$(name)[0].reset();
}
);
});
};
function resetForm (name){
$(name).show();
};
Im really new at this and only been coding for a few months so if my code is really bad I apologize, and if the solution is very easy, please forgive me.
I wrote this code so I could reuse it to submit diffrent forms on my page and have a response sent to a div above it. Im able to post everything I want but after the first time it posts, if I post again, it will post twice. Then three times. I know I did something wrong but I cant find the error.
I include this on my response to allow the form to be brought back after hiding.
<a onClick="resetForm('.$_POST['formName'].')" href="#" response=""> New Form?</a>
Here is the form.
<!-- Form 1 --->
<div class="row ">
<div class="col-xs-12">
<div class="well well-dark ">
<h4>Update Contacts</h4>
<span class="contactUpdate-response text-success"></span>
<form id="contactUpdate" class="form form-inline hidden contact-form" response=".contactUpdate-response" method="post" action="ajax/contactUpdate.php">
<div class="form-group">
<input hidden name="contact_entry" value="1"/>
</div>
<div class="form-group">
<label>Contact Title:</label>
<input class="form-control" name="contact_title" required />
</div>
<div class="form-group">
<label>Link to Employee</label>
<select name="empId" class="form-control select-emp-name"></select>
</div>
<div class="form-group">
<label>Category:</label>
<select name="category"class="form-control select-contact-categories ">
</div>
<div class="form-group">
<label>Link to Location</label>
<select name="locat_id" class="form-control select-location"></select>
</div>
<div class="form-group">
<label>Number:</label>
<select name="extId" class="form-control select-dig-ext"></select>
</div>
<div class="form-group">
<input hidden name="updateBy" value="24"/>
</div>
<div class="form-group">
<input onclick="slideupSubmit(contactUpdate)" type="submit" class="form-control btn btn-primary" value="Update List" />
</div>
</form>
</div>
</div>
</div>
<!--- -->
<input type="submit" class="form-control btn btn-primary" value="Update List" />
take your event listener out of function
and remove onclick=...
$(name).submit(function ( event ) {
event.preventDefault();
var target = $(this).attr("action");
var response = $(this).attr("response");
var formName = $(this).attr("id");
$.post( target, $(this).serialize()
+'&'+$.param({ 'formName': formName,
response : response}),
function(data){$(response).html(data);
$(name).hide();
$(name)[0].reset();
});
I am trying to upload a file alone with other form data using AJAX. Here I am following this bootstrap and jquery plugin.
I can figure it out without file uploading, But I want to upload a file with my form.
This is how I tried it:
.on('success.form.fv', function(e) {
// Save the form data via an Ajax request
e.preventDefault();
var $form = $(e.target),
formData = new FormData(),
params = $form.serializeArray(),
files = $form.find('[name="new_product_image"]')[0].files,
id = $form.find('[name="product_id"]').val();
// The url and method might be different in your application
$.ajax({
url: './includes/process_edit_products.php',
method: 'POST',
//data: $form.serialize()
data: formData,
cache: false,
contentType: false,
processData: false,
}).success(function(response) {
response = jQuery.parseJSON(response);
// Get the cells
var $button = $('button[data-id="' + response.product_id + '"]'),
$tr = $button.closest('tr'),
$cells = $tr.find('td');
// Update the cell data
$cells
.eq(0).html(response.product_name).end()
.eq(1).html(response.price).end()
.eq(2).html(response.product_des).end();
// Hide the dialog
$form.parents('.bootbox').modal('hide');
// You can inform the user that the data is updated successfully
// by highlighting the row or showing a message box
bootbox.alert('The product is updated successfully.');
});
});
UPDATE: This is my HTML:
<form id="userForm" method="post" class="form-horizontal" enctype="multipart/form-data" style="display: none;">
<div class="form-group">
<label class="control-label" style="width:32%;">ID</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="product_id" readonly />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Name:</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_name" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Price</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_price" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">Product Description</label>
<div class="col-xs-5">
<input type="text" class="form-control" name="product_des" />
</div>
</div>
<div class="form-group">
<label class="control-label" style="width:32%;">New Product Image:</label>
<div class="col-xs-5">
<input type="file" size="32" name="new_product_image">
<p class="help-block">*Only for jpg, gif and PNG files.</p>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-4">
<button type="submit" class="btn btn-primary">Update Product</button>
</div>
</div>
</form>
Can anybody tell me where I have gone wrong. Any help would be greatly appreciating.
Thank you.
I think your formData is empty. Try to put these lines before send:
$.each(files, function(i, file) {
// Prefix the name of uploaded files with "uploadedFiles-"
// Of course, you can change it to any string
formData.append('uploadedFiles-' + i, file);
});
$.each(params, function(i, val) {
formData.append(val.name, val.value);
});
Like they did here http://formvalidation.io/examples/ajax-submit/#using-ajax-to-submit-form-data-including-files