how to automatically reload a page after jquery ajax is finished [duplicate] - javascript

This question already has answers here:
Ajax Upload image
(6 answers)
save a image in the folder and getting the image name using ajax
(2 answers)
Closed last month.
here is my code for uploading some images on server
everything works except success - reloading the page after uploading is finished
I tried with another params - for example 20000 - without success
please help
inpfi.on('change', function(){
var flist = inpfi[0].files;
var fd = new FormData();
for(let i = 0; i < flist.length; i++){fd.append('flist[]', flist[i]);}
$.ajax({
url: 'a_slike_up.php',
type: 'post',
data: fd,
dataType: 'json',
contentType: false,
processData: false,
success: function(){setInterval('location.reload()', 7000);}
})
});
update
I tried plain js and it works
So I need the same - but in my jquery code
function handler_finito(e){
location.href = location.href;
}
inpfi.on('change', function(){
// ...
var ajax = new XMLHttpRequest();
ajax.addEventListener("load", handler_finito, false);
ajax.open("POST", "a_slike_up.php");
ajax.send(fd);
});

use setTimeout function instead of setInteval:
success: function(data) {
setTimeout(function(){
location.reload();
}, 7000);

Related

How do I automatically submit an upload form when a file is selected? how to replace upload button my code is below [duplicate]

This question already has answers here:
Load a file automatically without using a click button
(4 answers)
Closed 4 years ago.
Code:
<script type='text/javascript'>
$(document).ready(function(){
// Upload
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files[0];
fd.append('file',files);
fd.append('request',1);
// AJAX request
$.ajax({
url: 'addremove.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
var count = $('.uploaded-images .image-content').length;
count = Number(count) + 1;
// Show image preview with Delete button
$('.uploaded-images').append("<div class='image-content' id='content_"+count+"' ><img class='image-responsive' src='"+response+"' width='125' height='125'><span class='delete' id='delete_"+count+"'>×</span><span class='under-approval'>Under Approval</span></div>");
}else{
alert('file not uploaded');
}
}
});
});
// Remove file
$('.uploaded-images').on('click','.image-content .delete',function(){
var id = this.id;
var split_id = id.split('_');
var num = split_id[1];
// Get image source
var imgElement_src = $( '#content_'+num+' img' ).attr("src");
// AJAX request
$.ajax({
url: 'addremove.php',
type: 'post',
data: {path: imgElement_src,request: 2},
success: function(response){
// Remove <div >
if(response == 1){
$('#content_'+num).remove();
}
}
});
});
});
</script>
This is my Questions:
How do I automatically submit an upload form when a file is selected?
how to replace upload button my code is below
Anyone who have experience in this field, please suggestion me any solution for this problem, thank you.
You can use the following JQuery code:
$("#fileInput").change(function () {
$('#form').submit();
});
You can use this:
$('#file').on('change', function() {
$("#but_upload").click();
});
or better just put your click code into change event.
$('#file').on('change', function() {
var fd = new FormData();
var files = this.files[0];
...
});

$_FILES["sendImageFile"]["name"] return null value [duplicate]

This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 6 years ago.
I want to upload image without page loading, here sendImageFile is the value of file field. Now when I trying to upload any file from file_upload_to_user.php but every time $_FILES["sendImageFile"]["name"] returns null value.
<form enctype="multipart/form-data" method="post" name="img_upload_form" id="img_upload_form" action="file_upload_to_user.php">
<input name="sendImageFile" id="sendImageFile" type="file" accept=".png, .jpg, .jpeg"/>
<input type="submit" name="photoUploadToSend" id="photoUploadToSend" style="display:none" />
</form>
JS
var frm = $('#img_upload_form');
frm.submit(function (ev) {
var sendImageFile = document.getElementById("sendImageFile").value;
var to_hash = "000000000";
var dataString = 'sendImageFile='+sendImageFile+"&to_hash="+to_hash;
$.ajax({
type:"POST",
url:"file_upload_to_user.php",
data:dataString,
cache:false,
success: function(info) { alert(info);}
});
}
document.getElementById("sendImageFile").onchange = function change(){
// Upload image
document.getElementById("photoUploadToSend").click();
}
If you want to upload a file with ajax then you have to do it with FormData. And to send a formData with jQuery you need to send two other properties to to disable sending wrong stuff. so it's just easier to use fetch...
var form = document.getElementById("img_upload_form")
var fd = new FormData(form)
fetch("file_upload_to_user.php", {method: 'POST', body: fd})
To send a formdata with jQuery ajax you have to set this two:
processData: false,
contentType: false,
You need to use formData
var formData = new FormData();
formData.append('file', $('#sendImageFile')[0].files[0]);
formData.append('to_hash',"000000000");
$.ajax({
url : 'file_upload_to_user.php',
type : 'POST',
data : formData,
processData: false,//prevent automatic processing
contentType: false,//do not set any content type header
success: function(info) { alert(info);}
});

how to submit a form with file uploading using ajax...? [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
i created a form. Thats shown below...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sbt").click(function(){
var re=$("#file").val();
$.ajax({
type: "POST",
url: "loadajax.php",
data: $("#data").serialize()+ '&photo=' +re,
success: function(data) {
$("#datas").html(data);
},
error: function(){
alert('error handing here');
}
});
});
});
</script>
Ajax response page
<?php
echo "<pre>";
print_r($_POST);
var_dump($_FILES);
?>
All input values are returned.but file is not uploaded.I don't know how to upload file using ajax. Please help me...
Try This
$("#sbt").click(function(){
var pht = $("#ph").val();
var str2 = "your_folder/"; // destination folder, if needed
var upvid = str2.concat(pht);
var data = new FormData();
data.append( 'photo', $('#photo')[0].files[0] );
data.append( 'pht', pht );
$.ajax({
type: "POST",
url: "loadajax.php",
processData: false,
contentType: false,
cache:true,
data: data,
success: function(data){
$("#datas").html(data
} ,
error: function(){
alert('error handing here');
}
});
});
<?php
$a = $_POST['pht'];
$file = str_replace( "\\", '/', $a );
$ofile = basename($file);
?>
You have to use a plugin for this, jQuery doesn't support this out of the box. The best know plugin is ajaxForm
This will post the form to the given url in the form action field using ajax. There are events available to add validations and post-submit funcions.
you can also do like this:
function upload() {
// id of the form "documentUploadForm"
var form = document.getElementById("documentUploadForm");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
var url = '<c:url value="/loadajax.php"/>';
xhr.open('POST', url, true);
xhr.onload = function(e) {
if (xhr.status === 200) {
outputData = JSON.parse(xhr.responseText);
console.log("Response:" +outputData);
}
};
xhr.send(formData);
}

how can I cancel an Ajax request? [duplicate]

This question already has answers here:
Abort Ajax requests using jQuery
(18 answers)
How to cancel/abort jQuery AJAX request?
(8 answers)
Closed 8 years ago.
In phonegap how to cancel an ajax request in program, I would like to set cancel button for control the request when it's too slow
$.ajax({
type: "GET",
url: url,
success: function(m) {
alert( "success");
}
});
hi it's similar as Abort Ajax requests using jQuery,anyway This can help you
var ab = $.ajax({ type: "GET", url: url, success: function(m) { alert( "success"); } });
//kill the request
ab.abort()
Store the promise interface returned from ajax request in a global variable and abort it on cancel click
var result = $.ajax({ type: "GET", url: url, success: function(m) { alert( "success"); } });
$('#cancel').click(function() {
result.abort();
});
var request= $.ajax({ type: "GET", url: url, success: function(m) { alert( "success"); } });
$('#cancel').click(function() {
request.abort();
});
this will abort the request from the client(browser) side but note : if the server has already received the request, it may continue processing the request (depending on the platform of the server) even though the browser is no longer listening for a response. There is no reliable way to make the web server stop processing a request that is in progress.

How to upload file through Jquery/AJAX [duplicate]

This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 9 years ago.
I am currently POSTING my form through AJAX with the following code:
$(document).ready(function(){
$("form#createForm").submit(function() { // loginForm is submitted
$("form#createForm input#createForm_submit").attr('disabled','disabled');
tinyMCE.triggerSave();
$.ajax({
type: "POST",
dataType: "json",
url: "perform", // URL of the Perl script
data: $("#createForm").serialize(),
// script call was successful
// data contains the JSON values returned by the Perl script
success: function(data){
$('div.form-group').each(function(){
$(this).removeClass('has-error');
});
if (data.error) { // script returned error
var myList = $('ul.msg-list').empty();
$.each(data.msg, function(key,item) {
$("div."+key).addClass('has-error');
$('<li>').text(item.errtxt).appendTo(myList);
});
$('div#create_createresult').html('some error').html(myList);
$('div#create_createresult').addClass("text-danger");
$("form#createForm input#createForm_submit").removeAttr('disabled');
} // if
else
{ // login was successful
//$('form#login_loginform').hide();
$('div#create_createresult').text(data.msg);
$('div#create_createresult').addClass("success");
} //else
} // success
}); // ajax
$('div#login_loginresult').fadeIn();
return false;
});
});
Now I want to add the posibility of uploading a picture in the same form and just implement it in this JQUERY and in the same server-side script. My only problem is, I don't know how to do it.. I have tested the above, and I find, that it doesn't pass the $_FILES-variable to my server side script.
Can anyone lead me in any direction of, what I need to do, to add the possibility of image upload with this script?
try to use this.
// grab your file object from a file input
$('#fileInput').change(function () {
sendFile(this.files[0]);
});
// can also be from a drag-from-desktop drop
$('dropZone')[0].ondrop = function (e) {
e.preventDefault();
sendFile(e.dataTransfer.files[0]);
};
function sendFile(file) {
$.ajax({
type: 'post',
url: '/targeturl?name=' + file.name,
data: file,
success: function () {
// do something
},
xhrFields: {
// add listener to XMLHTTPRequest object directly for progress (jquery doesn't have this yet)
onprogress: function (progress) {
// calculate upload progress
var percentage = Math.floor((progress.total / progress.totalSize) * 100);
// log upload progress to console
console.log('progress', percentage);
if (percentage === 100) {
console.log('DONE!');
}
}
},
processData: false,
contentType: file.type
});
}

Categories