There is a script that needs to update the data on the page in a specific div. But instead of updating, the block with the div is simply hidden and in order for it to appear again, you need to reload the page. The data comes in data, but here is $ ("# userPost" + id) .html (data); something doesn't work.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.infinite-scroll').on('click', '#editPostButton', function(e) {
e.preventDefault();
var id = $(this).data('id');
var user_id = $('#userForm').val();
var form = document.getElementById('EditPostForm'+id);
var formData = new FormData(form);
// var formData = $('#EditPostForm'+id).serialize();
$.ajax({
url: "id"+user_id+"/"+id+"/edit",
type: "POST",
data: formData,
success: function(data) {
console.log(data);
$("#userPost"+id).html(data);
$("#closeButton"+id).click();
},
error: function() {
console.log('error');
},
processData: false,
contentType: false,
});
});
And div
<div id="userPost{{$post->id}}">
#if($post->img)
<div>
<img src="{{$post->img}}" class="img-fluid">
</div>
#endif
<br>
#if($post->title)
<div class=" mr-1 mb-3 titleleft">
<h5 style="color: black"><b>{{$post->title}}</b></h5>
</div>
#endif
#if($post->message)
<div class="text-muted text-small margins" style="white-space: pre-wrap;">{{mb_strimwidth($post->message, 0, 600, " . . . Read more")}}</div>
#endif
#if($post->videoPost)
<div class="embed-responsive embed-responsive-16by9 mt-4 mb-2">
<iframe class="embed-responsive-item" src="{{$post->videoPost}}" allowfullscreen></iframe>
</div>
#endif
</div>
Try doing this way:
$("#userPost"+id).load(url);
or
$("#userPost"+id).html(data).load(url);
Related
VIEW FILE
<div class="col-sm-4">
<label>Other Images</label>
<div class="input-group control-group img_div form-group" >
<input type="file" name="image[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success btn-add-more" type="button">Add</button>
</div>
</div>
</div>
<div>#foreach($image as $image)
<p><img src="{{asset('/files/'.$image->images)}}" height="50px" id="{{$image->id}}" class="photo"/>
<button class="removeimg" data-id="{{$image->id}}" data-token="{{ csrf_token() }}">Remove</button></p>
#endforeach
</div>
AJAX
$(document).ready( function () {
$(document).on('click', '.removeimg',function(){
var confirmation = confirm("are you sure to remove this record?");
if (confirmation) {
var id = $(this).data("id");
// console.log(id)
var token = $(this).data("token");
var $obj = $(this);
$.ajax(
{
url: "{{ url('image/delete') }}/"+id,
type: 'post',
dataType: "JSON",
data: {
"id": id,
"_token": token,
},
success: function (res)
{
// $(this).parents('.photo').remove();
$obj.parents('.photo').remove();
console.log("it Work", res);
}
});
console.log("It failed");
}
});
});
CONTROLLER
public function imgdelete($id){
Image::find($id)->delete($id);
return response()->json([
'success'=> 'Image deleted successfully!'
]);
}
When I delete the image, page gets redirected to product listing. Page should not get refresh when I delete the image. Can you please help me with correction?? NOTE: This process takes place on editproduct page.
You can prevent the default event for the button:
$(document).on('click', '.removeimg',function(event){
event.preventDefault();
.....
});
I am trying to upload a directory with large number of dicom files using Django and JQuery ajax. Each file size is not more than 600kb. I can upload 200 files at a time. If I increase the number of files (tried to upload 14000 files), it doesn’t work. The site gets stuck and it’s not showing any error. Can anyone please help me with this problem? I have attached my code below. Thanks in advance.
View.py:
def handle_uploaded_file(f,filePath):
with open(filePath+'/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def UploadScanView(request):
if request.method == 'POST':
form = create_scan_form(request.POST)
if form.is_valid():
scan = form.save(commit=False)
scan.project_id = form.cleaned_data.get('project_id')
directory_name = request.POST.get('directories')
json_to_dictionary = json.loads(directory_name)
print(json_to_dictionary)
for upload_file in request.FILES.getlist('file'):
file_path = settings.MEDIA_ROOT+'/'+os.path.dirname(json_to_dictionary[upload_file.name])
print(file_path)
if os.path.exists(file_path):
handle_uploaded_file(upload_file, file_path)
else:
os.makedirs(file_path)
handle_uploaded_file(upload_file,file_path)
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
else:
form = create_scan_form()
return render(request, 'fileupload/basic_upload/scan_upload.html', {'form': form})
HTML and JQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
/*fileupload div*/
$(document).ready(function(){
$("#my-file").on('change',function(e){ //submit(function(e){
$("#file-wrap p").text('Now click on Upload button');
});
$("#my-form").on('submit',function(e){ //submit(function(e){
files = document.querySelector("#my-file").files;
var directories = {}
for (var file of files) {
file.webkitRelativePath
directories[file.name] = file.webkitRelativePath
}
directories = JSON.stringify(directories);
document.querySelector("#directories").value = directories
var eventType = $(this).attr("method"); // get method type for #my-form
var eventLink = $(this).attr("action"); // get action link for #my-form
//alert(directories);
//////
var formData = new FormData(this);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
headers: { "X-CSRFToken": '{{ csrf_token }}' },
type: eventType,
url: eventLink,
//data: new FormData(this), // IMPORTANt
data: formData,
cache: false,
contentType: false,
processData: false,
// this part is progress bar
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
if (e.lengthComputable) {
var percentComplete = e.loaded / e.total;
percentComplete = parseInt(percentComplete * 100);
$('.myprogress').text(percentComplete + '%');
$('.myprogress').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function(getResult) {
$('#my-form')[0].reset(); // reset form
$("#file-wrap p").html('Drag and drop file here'); // change wrap message
}
});
e.preventDefault();
});
});
/*fileupload div*/
</script>
<form id="my-form" method="POST" action="{% url 'fileupload:upload_scan' %}" enctype="multipart/form-data"> <!--independentSub-->
{% csrf_token %}
<div id="user_form" class="container">
<div class="form-group col-sm-4" id="project_id">
{{ form.project_id|as_crispy_field }}
</div>
<!--fileupload div-->
<div id="independentSubDiv" class="row">
<div id="file-wrap" class="form-group col-sm-6" >
<p>Drag and drop file here</p>
<input id="my-file" type="file" name="file" multiple webkitdirectory directory draggable="true">
<input type="text" id="directories" name="directories" hidden />
</div>
</div>
<div style="padding-left: initial" id="independentSubDiv" class="form-group col-sm-7" >
<button type="submit" class="btn btn-primary btn-lg btn-block" name="submit_btn" id="submit_btn">Submit</button>
</div>
<div class="progress form-group col-sm-7" style="padding-left: initial" id="progressDiv" >
<div class="progress-bar progress-bar-success myprogress " role="progressbar">0%</div>
</div>
</div>
</form>
how to get id when I click the card, I get id in concole.log .
but I don't know get id when card was clicked.
here is the code :
$.ajax({
url : 'https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?',
type: 'get',
dataType: 'json',
data : {
's' : 'Soccer'
},
success: function(result){
let league = result.countrys;
$.each(league, function(i, data){
$('#club-list').append(`
<div class="col-md-4 p-2">
<div class="card shadow" onCLick="console.log(`+data.idLeague+`)">
<img src="`+ data.strBadge +`" class="card-img-top p-2" alt="...">
<div class="card-body">
<p class="card-text">`+ data.strLeague +`</p>
</div>
</div>
</div>`);
});
$('.card').on('click', function(){
$.ajax({
url : 'https://www.thesportsdb.com/api/v1/json/1/lookup_all_teams.php?',
type: 'get',
dataType: 'json',
data: {
// 'id' : '4328'
'id' : /* HOW TO GET ID FROM CARD WHEN USER CLICK CARD ? */
},
success: function(result){
let team = result.teams;
$.each(team, function(i, data){
$('#club-detail').append(`
<div class="col-md-4 p-2">
<div class="card shadow">
<img src="`+ data.strTeamBadge +`" class="card-img-top p-2" alt="...">
<div class="card-body">
<p class="card-text">`+ data.strTeam +`</p>
</div>
</div>
</div>`);
});
// window.location.href = "league.php";
console.log(team);
}
});
});
}
});
https://www.thesportsdb.com/api/v1/json/1/lookup_all_teams.php?id=4328 /* HOW TO GET ID WHEN USER CLICK CARD ? */
enter image description here
use class instead of id. because multiple id with same key won't work
$.ajax({
url : 'https://www.thesportsdb.com/api/v1/json/1/search_all_leagues.php?',
type: 'get',
dataType: 'json',
data : {
's' : 'Soccer'
},
success: function(result){
let league = result.countrys;
$.each(league, function(i, data){
$('#club-list').append(`
<div class="col-md-4 p-2">
<div class="card shadow" data-id="${data.idLeague}">
<img src="`+ data.strBadge +`" class="card-img-top p-2" alt="...">
<div class="card-body">
<p class="card-text">`+ data.strLeague +`</p>
</div>
</div>
</div>`);
});
$(document).on('click','.card', function(e){
console.log(this.dataset.id);
});
}
});
i try to make upload image with ajax without form, when i am sent data without the image, data successfully submitted to the database, but when i am adding an image, when i try to submit, no response at all,
this is my template code :
<input type="hidden" name="lesson_id" value="{{-- $lessons->id --}}">
<input type="hidden" name="parent_id" value="0"> -->
<div class="form-group">
<label>Komentar</label>
<textarea rows="8" cols="80" class="form-control" name="body" id="textbody0"></textarea>
</div>
<ul class="right">
<input type="file" name="image" id="image" />
<img id="myImg" src="#" />
<button type="button" class="btn btn-primary" onClick="doComment({{ $lessons->id }},0)" >Kirim</button>
and this is my script for submit data :
function doComment(lesson_id, parent_id) {
var body = $('#textbody'+parent_id).val();
var image = $('#image').prop('files')[0];
if (body == '') {
alert('Harap Isi Komentar !')
}else {
var postData =
{
"_token":"{{ csrf_token() }}",
"lesson_id": lesson_id,
"parent_id": parent_id,
"image": image,
"body": body
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
type :'POST',
url :'{{ url("lessons/coments/doComment") }}',
dataType: 'json',
data : postData,
beforeSend: function(){
// Show image container
swal({
title: "Sedang mengirim Komentar",
text: "Mohon Tunggu sebentar",
imageUrl: "{{ asset('template/web/img/loading.gif') }}",
showConfirmButton: false,
allowOutsideClick: false
});
{{-- $("#loader").show(); --}}
},
success:function(data){
if (data.success == false) {
window.location.href = '{{ url("member/signin") }}';
}else if (data.success == true) {
$('#textbody'+parent_id).val('');
swal({
title: "Komentar anda sudah terkirim!",
showConfirmButton: true,
timer: 3000
});
getComments();
}
}
});
}
}
Can any one help me?
postData = new FormData();
if(!!file.type.match(/image.*/)){
postData.append("image", file);
$.ajax({
type : 'POST',
url : '{{ url("lessons/coments/doComment") }}',
data : postData,
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}
I have fancybox, where I want to submit a form. Also I want to handle that form by PHP code which is inside the same page. Below is my code.
function lunchModal(itemID){
jQuery('.share').on('click', function(){
$data = '<div class="shareModal" ><div class="modal-header"><h3>Share Form Submission</h3></div> \
<form action="" class="shareForm" method="post">\
<div class="modal-body">\
<div class="control-group">\
<label for="inputEmail" class="control-label">Enter Share Email</label>\
<div class="controls">\
<input type="email" id="inputEmail" placeholder="Share Email" name="email">\
<input type="hidden" value="'+itemID+'" id ="documentID">\
</div>\
</div>\
</div>\
<div class="modal-footer">\
<div class="controls">\
<button type="submit" class="btn btn-primary" id="submit">\
<i class="icon icon-envelope"></i>Share</button>\
</div>\
</div>\
</form>\
</div>';
jQuery.fancybox({
height : '55%',
autoDimensions: false,
width: '70%',
scrolling: 'auto',
padding: '20px',
title: false,
content: $data,
transitionIn: 'elastic',
transitionOut: 'elastic',
easingIn : 'easeOutBack',
easingOut : 'easeInBack',
centerOnScroll: 'true',
onComplete: submitForm()
});
item_id = false;
});
};
function submitForm() {
jQuery('#submit').on('submit', function(e) {
e.preventDefault();
//var dataString = {
// 'action' : 'shareDocument'
//};
var email = jQuery('#inputEmail').val();
var id = jQuery('#documentID').val()
var dataString = 'email='+email+'&documentID='+id;
//jQuery.extend(true, dataString, form_data);
console.log(dataString);
jQuery.fancybox.showActivity();
jQuery.ajax({
url: window.location.pathname,
type: 'POST',
data: dataString,
beforeSend: function() {
console.log(dataString);
},
success: function(data) {
alert('Document shared successfully');
}
});
return true;
});
}
Now my problem is When I submitting the form, the page is reloading, although I have used ajax form submit. Can anyone help me in this regard?
button type="submit"
this will reload ur page bcz ur submitting value to the declared page.
so you have to change ur code like below
input type="button" onclick="submitForm()"
this wont reload ur page.