Ajax call with .net MVC - ajax

I am trying to use Ajax to Submit a form. But when I do submit the page is reloaded and the url changes. I think that the url changes because of the #Html.AntiForgeryToken();
See my code bellow :
This is how my form looks like :
#model PersonModel
....
<form action="SubmitLead" class="new-lead">
#Html.AntiForgeryToken();
<div class="col-md-12">
<p>
<input type="hidden" value="#Model.TrackingCode" id="hdnTrackingCode" />
My name is #Html.TextBoxFor(model => model.FirstName,
new { #placeholder =
Html.DisplayNameFor(model => model.FirstName) })
#Html.TextBoxFor(model => model.Surname, new { #placeholder = Html.DisplayNameFor(model => model.Surname) })
</p>
</div>
<div class="clearfix"></div>
<div class="col-md-12 text-center">
<button type="submit" id="btnSubmit" class="orange-button">Get Quotes Now</button>
</div>
</form>
#if (Model.Results != null &&
Model.Results.IsSuccessful)
{
<div class="col-md-12 text-center">
<img src="~/Content/Images/Products/new-success.png" height="24px" />
<p id="result"></p>
</div>
}
Please see my script here :
#section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('.new-lead').submit(function (event) {
$.ajax({
url: '#Url.Action("Lead/SubmitLead")',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function (result) {
var resultMessage = "success";
$('result').html(resultMessage);
}
})
})
})
</script>

Do this way
<form onsubmit="return submit(thi)" class="new-lead">
....
</form>
<script>
function submit(e){
$.ajax({
url: '#Url.Action("Lead/SubmitLead")',
type: 'POST',
data: $(e).serialize(),
dataType: 'json',
success: function (result) {
var resultMessage = "success";
$('result').html(resultMessage);
}
})
return false;
}
</script>

Related

Boostrap Modal, browse for photo and submit via ajax to controller with [FromForm] IFormFile file

I want to create a reusable upload feature for images and have created a partialView for this. On click, the partial is loaded via ajax call and the user can browse for an image, the chosen image is displayed and on submit the file should be passed to the controller but the url for submission is always a 404.
Load the Bootstrap Modal
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#add-contact" data-url="#Url.Action("ShowModalUploadForm", new { Id= Model.Id })">
Add contact
</button>
var placeholderElement = $('#modal-placeholder');
$(document).on('click', 'button[data-toggle="ajax-modal"]', function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});
This works...The issue is when I submit, the URL that is fored appears to not match what the controller is expecting
PartialView (omitted unnecessary portions)
<form id="UploadPhoto" asp-action="UploadPhoto" enctype="multipart/form-data" method="post">
<input name="VolunteerId" id="VolunteerId" type="hidden" value="#Model" />
<div class="col-md-12">
<div class="form-group">
<label>Upload Image</label>
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Browse… <input type="file" id="imgInp">
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<img id='img-upload' name='img-upload' />
</div>
</div>
</form>
$(document).on('click', '#btnSubmitUpload', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var dataToSend = new FormData(form.get(0));
$.ajax({
url: '#Url.Action("UploadPhoto", "Volunteer", new { Area = "Admin" })',
method: 'post',
data: dataToSend,
processData: false,
contentType: false
}).done(function (data) {
//Do stuff here
}
});
});
$(document).on('change', '.btn-file :file', function () {
var input = $(this),
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [label]);
});
$(document).on('fileselect', '.btn-file :file', function (event, label) {
var input = $(this).parents('.input-group').find(':text'),
log = label;
if (input.length) {
input.val(log);
} else {
if (log) alert(log);
}
});
$(document).on('change', '#imgInp', function () {
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#img-upload').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
VolunteerController
[HttpPost]
private async void UploadPhoto([FromForm] IFormFile file)
{
//await _storage.SaveBlobAsync("volunteers", file, BlobType.Image);
}
Open the F12 developer tools, where is your misalignment? Or we can also use the FormData object.
View:
#model ImageFileUpload.Models.Human
#{
ViewBag.Title = "SaveData";
}
<h2>SaveData</h2>
<div>
Create New
<br /><br />
<table class="table table-responsive">
<thead>
<tr style="background-color:#333;color:white;">
<th>Human Name</th>
<th>Human Image</th>
<th>Human Phone</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody id="SetHumanList">
<tr id="LoadingStatus"></tr>
</tbody>
</table>
</div>
#using (Html.BeginForm("SaveData", "Human", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{
<div class="modal fade" id="MyModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h4 id="ModalTitle"></h4>
</div>
<div class="modal-body">
<fieldset id="SubmitForm">
#Html.HiddenFor(a => a.HumanId, new { #id = "HumId" })
<div class="form-group">
#Html.TextBoxFor(a => a.HumanName, new { #id = "HumName", #class = "form-control", #placeholder = "Name" })
</div>
<div class="form-group">
<input type="file" id="UploadFile" name="Upload" class="form-control w" />
</div>
<div class="form-group">
#Html.TextBoxFor(a => a.HumanPhone, new { #id = "HumPhone", #class = "form-control", #placeholder = "Phone" })
</div>
<div class="form-group">
<button id="SaveRecord" type="button" class="btn btn-warning">Create</button>
</div>
</fieldset>
</div>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
<script src="~/Scripts/jquery.form.min.js"></script>
#Scripts.Render("~/bundles/jqueryval")
<script>
function AddNewHuman() {
$("#MyModal").modal("show")
}
$("#SaveRecord").click(function () {
var formData = new FormData();
formData.append("Upload", $('#UploadFile')[0].files[0]); //append the image file
var other_data = $('form').serializeArray();
$.each(other_data, function (key, input) { //append other input value
formData.append(input.name, input.value);
});
$.ajax({
type: "POST",
url: "/Human/SaveData",
data: formData,
contentType: false, // Not to set any content header
processData: false, // Not to process data
success: function (result) {
alert("Success");
window.location.href = "/Human/index";
//$("#MyModal").modal("hide"); //this line is unnecessary because the user has been redirect
}
})
});
</script>
}
Result

My previously edited data is edited again when I update second data in codeigniter using ajax

I am using codeigniter framework to develop my project. I am also using AJAX to edit the data. When I edit the first data it is being edited correctly but when I am updating the second data without refreshing the browser then previous edited data or current editing data both are updated with new result. Please solve my problem. Thanks in advance.
function editFunction(id)
{
$.ajax({
url: "edit_result/" +id,
data: {id:id},
type: "post",
async: false,
dataType: 'json',
success: function(response){
$('#reg_no').val(response.reg);
$('#total_marks').val(response.tot_marks);
$('#grade').val(response.grade);
},
error: function()
{
alert("error");
}
});
$('#updateBtn').click(function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $(this).serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
alert('success');
},
error: function()
{
alert("error");
}
});
}
});
}
I am performing edit operation on modal. Please check also HTML code
<div class="modal fade" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h2 class="modal-title">Edit Result</h2>
<p class="message" style="color: red;"></p>
</div>
<div class="modal-body">
<form role="form" id="updateForm">
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Reg No :</label>
<input type="text" class="form-control" id="reg_no" readonly="">
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Total Marks :</label>
<input type="number" class="form-control" id="total_marks" placeholder="Enter total marks" onfocus="colorFunction(this)" name="tot_marks">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Grade</label>
<?php
$firstItem[''] = 'Please select one...';
$options = array(
'A++' => 'A++ (90% & above)',
'A+' => 'A+ (80% to 89%)',
'A' => 'A (60% to 79%)',
'B+' => 'B+ (50% to 59%)',
'B' => 'B (40% to 49%)',
);
$options = array_merge($firstItem, $options);
$selected_option = $this->input->post('grade', TRUE);
echo form_dropdown('grade', $options,$selected_option,['class'=>'form-control','id'=>'grade','onfocus'=>'colorFunction(this)']); ?>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success pull-right" data-dismiss="modal" id="updateBtn">Update</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
I have got an answer of my question. I am using off('click') in code you can see update code below.
$('#updateForm').off('click','#updateBtn').on('click','#updateBtn',function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $("#updateForm").serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
if(response=='1')
{
$('.alert-success').show();
$('.alert-success').html('Result Updated Successfully').fadeIn().delay(4000).fadeOut('slow');
$('#example1').DataTable().ajax.reload();s
}
},
error: function()
{
alert("error");
}
});
}
});
play a game at view first. i guess you are not using primary key of db to update. let me explain.
at view:
at one more input element which type is hidden and has value your primary key . assign it an id having value tbl_id example
<input type="hidden" value="<?php echo {variable that has your primary key } ?>" id="tbl_id" >
and at ajax call before you start writing it
var id = $("#tbl_id").val();
when you call controller check you have id available or not
next you are going to call a model to update.
that is where your other all data get update.
when you are going to call model use statement before it
if($id != '') { // $id is what you have shared via ajax call
$this->model_name->update_function($id,$array); // $array is all other fields as per codeigniter need
} else { echo "unable to capture id"; exit; }
and last you update model..
all done by ajax :)

Two ajax call for two forms, latter not working

I've tried everything. The form posts fine when not using Ajax, I switch the places so it would be first, I deleted everything and just gave it an alert to show when clicking submit... I can't pin-point the problem.
The second ajax just won't submit!
$(document).ready(function() {
$('#writeform').submit(function(event) {
var formData = {
'from': $('input[name=from]').val(),
'to': $('input[name=to]').val(),
'textbox': $('input[name=textbox]').val()
};
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
// ajax the login
$(document).ready(function() {
$('#loginform').submit(function(event) {
var formData = {
'username': $('input[name=username]').val(),
'pass': $('input[name=pass]').val()
};
$.ajax({
type: 'POST',
url: 'login.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
function loadLogDiv(){
$("#logfunction").load("login.php");
}
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
loadLogDiv();
setInterval( loadLogDiv, 4000);
});
Heres the page itself:
<div id="loginpage">
<form id="loginform" action="login.php" method="POST">
<div id="username">
<label for="username">User Name</label>
<input type="text" name="username" placeholder="User Name" />
<!-- errors will go here -->
</div>
<div id="pass">
<label for="pass">Password</label>
<input type="password" name="pass" placeholder="Password" />
<!-- errors will go here -->
</div>
<input type="submit">Submit</input>
</form>
<div id="logfunction"></div>
</div>
<div id="footer">
<form id="writeform" action="process.php" method="POST">
<div id="from">
<label for="from">From</label>
<select name="from">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="to">
<label for="to">To</label>
<select name="to">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="textbox">
<label for="textbox">Text</label>
<input type="text" name="textbox" placeholder="text" />
</div>
<input type="submit">Submit</input>
</form>

laravel 5.1 formData - AJAX - PHP- Uploading multiple files

I can not get the formData from the file upload
form.blade.php
<form method="POST" class="form-horizontal" enctype="multipart/form-data" id="modal-file-upload">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="folder" value="" id="modal-file-upload-folder">
<div class="modal-header">
<h4 class="modal-title">Upload New File</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="file" class="col-sm-3 control-label">
File
</label>
<div class="col-sm-8">
<input multiple="true" accept="image/*" required="true" id="fileToUpload" type="file" name="file[]">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="close_upload_view()">Cancel</button>
<button class="btn btn-primary" id="btn-upload">Upload File</button>
</div>
</form>
Controller
public function uploadMultiFile(Request $request) {
// getting all of the post data
$data = $request->input('formData');
var_dump($data); current return null
}
<script>
// Confirm file delete
function close_upload_view() {
$("#modal-file-upload").modal("hide");
return false;
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$("#modal-file-upload").submit(function(e){
e.preventDefault();
//var formData = new FormData(document.getElementById('modal-file-upload')[0]);
var fd = new FormData();
var ins=document.getElementById('fileToUpload').files.length;
for(var x=0;x<ins;x++)
{
fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}
var folder = $("input#modal-file-upload-folder").val();
var token = $("input[name=_token]").val();
var dataString = 'formData='+fd+'&folder='+folder+'&token='+token;
$.ajax({
type: "POST",
url: '{!! url() !!}/admin/upload/multifile',
cache: false,
data : dataString,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server it
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
</script>

cannot upload file using ajax with formdata

I have the following code in my form.
I try to upload the files via ajax using jquery.
Other data fields in the form was submitted fine. But i cant add FILES to the POST request.
Here is my html code:
<div class="form-group">
<div class="col-lg-2">
<label class="lab pull-right">Image:</label>
</div>
<div class="col-lg-2">
<input type="file" name="nimp" required>
</div>
</div>
<div class="form-group">
<div class="col-lg-2">
<label class="lab pull-right">Thumb Image:</label>
</div>
<div class="col-lg-2">
<input type="file" name="ntimp" id="ntimp" required>
</div>
</div>
My JQ Code:
$(document).ready(function(e) {
$('button.submit').click(function(e) {
e.preventDefault();
var a=new FormData();
alert(a);
$('.edit_form_prod_div').hide();
$.ajax({
type:"POST",
url:"ep.php",
data:a,
cahe: false,
processData:false,
contentType: false,
success: function(response){
$('.edit_prod_response').html(response)
},
error:function(response)
{ alert("Error Occures"); }
});
$('.edit_prod_response').show();
});
});
Try This Code
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<input type="file" name="files"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function ()
{
$("#btnSubmit").click(function()
{
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "FileUploadHandler",
data: data,
processData: false, // Importent
contentType: false, // Importent
cache: false,
timeout: 600000,
success: function (data)
{ alert("File Uploaded...!")
}
});
});
</script>

Resources