Upload an image using a modal - javascript

I want to upload an image using modal. I know how to to that using an HTML form, but I am not sure how to use an ajax request to send data to the controller. Is it possible to use the controller that I have now? Thanks in advance!
The controller:
public function postCreatePost(Request $request)
{
...
$post->longitude = $request['longitude'];
if($request->user()->posts()->save($post))
{
$message = 'Post Successful';
};
$file = $request->file('image');
$filename = $post->id.'.jpg';
if($file)
{
Storage::disk('local')->put($filename, File::get($file));
}
return redirect()->route('dashboard')->with(['message' => $message]);
}
The ajax request that I have so far:
$('#modal-save').on('click',function(){
//create ajax request
$.ajax({
method: 'POST',
url: urlEdit, //url route is defined in the dashboard html script
//pass the post content and id to body and postId which will be used in the Post controller edit method
//need the token to avoid error
data: {body: $('#post-content').val(), postId: postId, _token: token}
})
.done(function (msg){
//console.log(msg['message']);
//console.log(JSON.stringify(msg));
$(postBodyElement).text(msg['new_content']); //update the post w/o refreshing the page
$('#edit-post').modal('hide'); //hide the modal
})
});
The modal:
<div class="modal" tabindex="-1" role="dialog" id="edit-post">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form enctype="multipart/form-data">
<div class="form-group">
<label for="post-content">Edit Post</label>
<textarea class="form-control" name="post-content" id="post-content" rows="5"></textarea>
{{-- copy meta data using jquery?--}}
{{-- add a separate image form here--}}
<label for="image">Image (jpg only)</label>
<input type="file" name="image" class="form-control" id="image">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
</div>
</div>
</div>
</div>

The controller looks fine. But you are not passing the image:
Try this
$('#modal-save').on('click',function(){
//create ajax request
$.ajax({
method: 'POST',
url: urlEdit, //url route is defined in the dashboard html script
//pass the post content and id to body and postId which will be used in the Post controller edit method
//need the token to avoid error
data: {
body: $('#post-content').val(),
postId: postId,
_token: token,
image:$('#image').val()
}
})
.done(function (msg){
//console.log(msg['message']);
//console.log(JSON.stringify(msg));
$(postBodyElement).text(msg['new_content']); //update the post w/o refreshing the page
$('#edit-post').modal('hide'); //hide the modal
})
});
You can then get the image in the controller:
if( $request->hasFile('image') ) {
$file = $request->file('image');
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
}

You are not sending an image to the server end. Please use the formData object to send media to the server.
/** New form data object */
var formData = new FormData();
/** append post content */
formData.append('postcontent', $('#post-content').val());
/** append post id */
formData.append('postId', postId);
/** append token */
formData.append('_token', token);
/** append image */
formData.append('image', $("input[type=file]")[0].files[0]);
In your ajax call send formData in data
$.ajax({
method: 'POST',
url: urlEdit,
data: formData,
cache: false,
contentType: false,
processData: false
}).done(function (msg){
$(postBodyElement).text(msg['new_content']);
$('#edit-post').modal('hide'); //hide the modal
})

Related

I am trying to upload video in laravel but not able to do so

Here is the Ajax part to add the video Url in the database.I am getting the value of Video title and video desc in database but not getting the url.
<div class="modal fade" id="addVideo" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-headerr">
<h5 class="modal-title" id="exampleModalLabel" data-toggle="modal">Add New Video</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" style="display:none"></div>
<form class="image-upload" method="post" action="" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Title</label>
<input type="tetx" name="addvideoTitle" id="AddvideoTitle" placeholder="Add a title"
class="form-control" />
</div>
<div class="form-group">
<label>Discription</label>
<input type="text" name="Addvideodesc" id="Addvideodesc" placeholder="Add a discription"
class="form-control" />
</div>
<div class="form-group">
<label>Add a video</label>
<input type="File" name="add-video" id="add-video" placeholder="Add a video to upload"
class="form-control" />
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="saveNewVideo">Save</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$(document).on('click','#saveNewVideo',function(){
var add_videotitle= $('#AddvideoTitle').val();
var add_videoDesc= $('#Addvideodesc').val();
var add_video= $('#add-video').val();
$.ajax({
type: "POST",
dataType: "json",
url: '{{ url('/event/saveEvent') }}',
data: {
'add_videoDesc': add_videoDesc,
'add_videotitle': add_videotitle,
'add_video':add_video,
_token: '{{csrf_token()}}'
},
success: function (data){
}
});
});
});
</script>
Controller code is written for adding video url in database I have written the value and getting the response but not actually saving the data in database.
public function saveEvent(request $request){
try{
if(!$request->ajax())
throw new \Exception('Not a valid Request');
$event =new Event();
$event->user_id=Auth::user()->id;
$event->event_name=$request->event_name;
$event->date=$request->event_date;
$event->time=$request->event_time;
$event->location=$request->event_location;
$event->cost=$request->event_cost;
$event->join_url=$request->event_join;
$event->add_video_title=$request->add_videotitle;
$event->add_video_desc=$request->add_videoDesc;
if($request->hasfile('add_video'))
{
$image = $request->file('add_video');
$extention= $image->getClientOriginalExtension();
$filename = time() . '.'. $extention;
$path = public_path('video');
$image->move('assets/video', $filename);
$imageurl=$path."/". $filename;
$event->video = $filename;
}
$event->save();
return response()->json(['status'=>true,'message'=>'Event Added Successfully','data'=>$event]);
}//end here try
catch(\Exception $e)
{
return response()->json(['status'=>false,'message'=>$e->getMessage()]);
}
}
According to Laravel Docs, in the case of Ajax calls - you could, for example, store the token in an HTML meta tag::
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript">
// and then include in your ajax header like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#saveNewVideo').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$.ajax({
type:'POST',
url: '{{ url('/event/saveEvent') }}',
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
alert('Video has been uploaded successfully');
}
},
error: function(response){
$('#file-input-error').text(response.responseJSON.message);
}
});
});
</script>
That code is checking for the extension but not the MIME type. You should use the appropriate MIME type:
Video Type Extension MIME Type
Flash .flv video/x-flv
MPEG-4 .mp4 video/mp4
iPhone Index .m3u8 application/x-mpegURL
iPhone Segment .ts video/MP2T
3GP Mobile .3gp video/3gpp
QuickTime .mov video/quicktime
A/V Interleave .avi video/x-msvideo
Windows Media .wmv video/x-ms-wmv
If you are not sure about the MIME type of the file you are testing you can try $file->getMimeType()
public function store(Request $request)
{
$request->validate([
'video' => 'mimetypes:video/x-ms-asf,video/x-flv,video/mp4,application/x-mpegURL,video/MP2T,video/3gpp,video/quicktime,video/x-msvideo,video/x-ms-wmv,video/avi|max:204800'
]);
if($request->hasfile('add_video')) {
$unique_id = strtolower(str_replace('.', '', uniqid('', true)) . time());
$videoFile = $request->file('add_video');
$extension = $videoFile->getClientOriginalExtension();
$fileNameToStore = $unique_id . '.' . $extension;
$filepath = $videoFile->storeAs('video', $fileNameToStore);
$event->video = $filepath;
}
$event->save();
}
Store Files in Storage Folder
$file->storeAs('files', $fileName);
// storage/app/files/file.pdf
Store Files in Public Folder
$file->move(public_path('files'), $fileName);
// public/files/file.pdf
To display data on the front-end side.
$videoPath = !empty($pp_question->video) && Storage::exists($pp_question->video) ? Storage::url($pp_question->video) : asset(Storage::url('default/video.mp4');

Why my ajax post is not working codeigniter? The page is refreshing

// save new employee record
$('#saveEmpForm').submit('click',function(){
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
});
<form id="saveEmpForm" method="post">
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-2 col-form-label">Jenis</label>
<div class="col-md-10">
<input type="text" name="jenis" id="jenis" class="form-control" required>
<input type="hidden" id="input_id" name="input_id" class="form-control " value="{$input_id}">
</div>
</div>
<div class="form-group row">
<label class="col-md-2 col-form-label">Jarak</label>
<div class="col-md-10">
<input type="text" name="jarak" id="jarak" class="form-control" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
Save function in controller file
public function save(){
$data=$this->inputs_model->saveEmp();
echo json_encode($data);
}
Save function in Model
public function saveEmp(){
$data = array(
'input_id' => $this->input->post('input_id'),
'jenis' => $this->input->post('jenis'),
'jarak' => $this->input->post('jarak'),
'created_at' => date("Y-m-d h:i:sa"),
'updated_at' => date("Y-m-d h:i:sa")
);
$result=$this->db->insert('input_jenis_industri',$data);
return $result;
}
The code are as stated above, my ajax function to save the data is not working. It is not saving the data in the db. What can cause the problem?
My ajax function calls the InputPembangunan/save to save the data, then the controller try to the save data using the save() function. It is saved using the model saveEmp()
The following is incorrect, there is no click involved in a submit event
$('#saveEmpForm').submit('click',function(){
Change to
$('#saveEmpForm').submit(function(event){
event.preventDefault()// prevent normal form submit
without refreshing the page you have to call event.preventDefault() method after submit event.
replace this
$('#saveEmpForm').submit('click',function(){
with
$('#saveEmpForm').on('submit',function(){
event.preventDefault()
Change this
<button type="submit" class="btn btn-primary">Save</button>
to
<button type="button" class="btn btn-primary">Save</button>
You can onlick() method. Actually I used like this;
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="save()" class="btn btn-primary">Save</button>
</div>
than add jquery
function save() {
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
URL: "<?php echo site_url('InputPembangunan/save')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data) {
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else {
//do something
}
},
error: function(jqXHR, textStatus, errorThrown) {
//do error form
}
});}
Use the following way,
$( "#saveEmpForm" ).submit(function( event ) {
event.preventDefault();
/** Your Existing Code ***/
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
/** Your Existing Code ***/
});
Also, you can check the jQuery reference from this link:
https://api.jquery.com/submit/#submit
Replace
$('#saveEmpForm').submit('click',function(){
with
$(document).off('submit','#saveEmpForm').on('submit','#saveEmpForm',function(event) {
event.preventDefault(); //to prevent default submit action
...rest of the code
})
also check for any errors on the browser dev tool

Javascript, Ajax : Bad Request 400

I'm working on ASP Net Core Project and I'm trying to send to my controller with JQuery Ajax function from a partial view modal, parameters.
The recovered URL is correct for example : http://localhost:44321/Validations/ValidationRefuse?ficheId=24&commentaire=Commentaire%20de%20test
But it's always :
Failed to load resource: the server responded with a status of 400 (Bad Request)
My Javascript :
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse?ficheId=" + ficheId + "&commentaire" + commentaire,
type: 'POST',
contentType: 'application/html',
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
My C# method :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ValidationRefuse(int ficheId, string commentaire)
{ ... }
My Partial View :
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Validez-vous cette fiche ?</h5>
<button type="button" class="btn btn-outline-dark btn-circle" data-dismiss="modal" aria-label="Close">
<i class="fa fa-close"></i>
</button>
</div>
<form asp-controller="Validations" asp-action="ValidationParResponsable" asp-route-id="#Model.FicheId" asp-route-eId="#Model.EnseignantId">
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="ficheId" asp-for="FicheId" />
<input type="hidden" asp-for="EnseignantId" />
<input type="hidden" asp-for="EtatId" />
<label class="control-label font-weight-bold">Commentaire :</label>
<textarea class="form-control" id="inputCommentaire" asp-for="Commentaire" placeholder="Votre commentaire"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="buttonRefusFiche">Refuser</button>
<button type="submit" class="btn btn-success">Valider</button>
</div>
</form>
I hope it's understandable, thanks for your responses. :)
When you use a POST request you have to send the parameters in the body of the request, not in the URL like that :
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse",
type: 'POST',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType : "html",
data : {
ficheId : ficheId,
commentaire : commentaire
},
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
I also changed the contentType and added dataType.
For more information about ajax Post see documentation

Sending data using ajax to the controller in rails

I am new to JS and rails so recently facing lots of difficulties about using ajax in rails environment. I will very appreciate if you contribute to developing my project. What I am trying to do is that Once a user selects data from the modal, I want to send the selected data to an action in the controller so that I can handle the data. I am not really sure where I can start with that. Please help guys :( Thanks a lot
view:
<form id= "selected_form" action="" method="">
<div id= "selected_form">
<p id="checkids"></p>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Select Task</h4>
</div>
<div class="modal-body">
<fieldset>
<% #tasks.each do |task|%>
<div>
<label><input type="checkbox" value="<%=task.id%>" name="selected"><%=task.title%></label>
</div>
<% end %>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" id="save" class="btn btn-default" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
JS
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/users/<%= current_user.id %>/test", // route of your rails action
data: {checked_items: checkedItem.join(", ")}, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){}
})
});
});
});
</script>
Please check script below
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/things", // route of your rails action
data: {checked_items: checkedItem }, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){...}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){...}
})
});
});
});
</script>
For simplicity you can inject rails path to that controller as dataset attribute.
for e.g
<form method="post" data-url="<%= tasks_path %>">
and in js part
$('#save').on('click', function (e) {
e.preventDefault();
$.ajax({
type: $(this).method || "GET",
url: this.dataset.url,
data: $(this).serialize(),
success: function (response) {
console.log(response)
},
error: function (error) {
console.log(error);
}
});
});

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

Categories

Resources