HTML prevent from redirect upload php - php

I need to prevent the page redirected to the upload php when click upload button.
How can I do this in below code.
<form id="myForm" action="http://example/DB_1/AccessWeb/file_upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
</form>
<button onclick="myFunction()"> Upload
</button>
<script>
function myFunction(){
document.getElementById("myForm").submit();
}
</script>

A very basic, quickly written example of how to send a file - using ajax to the same page so that the user doesn't get redirected. This is plain vanilla javascript rather than jQuery.
The callback function can do more than print the response - it could, for instance, be used to update the DOM with new content based upon the success/failure of the upload.
<?php
$field='fileToUpload';
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
$obj=(object)$_FILES[ $field ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
if( $error==UPLOAD_ERR_OK ){
/*
This is where you would process the uploaded file
with various tests to ensure the file is OK before
saving to disk.
What you send back to the user is up to you - it could
be json,text,html etc etc but here the ajax callback
function simply receives the name of the file chosen.
*/
echo $name;
} else {
echo "bad foo!";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>File Upload - using ajax</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var bttn=document.getElementById('bttn');
bttn.onclick=function(e){
/* Assign a new FormData object using the buttons parent ( the form ) as the argument */
var data=new FormData( e.target.parentNode );
var xhr=new XMLHttpRequest();
xhr.onload=function(e){
document.getElementById('status').innerHTML=this.response;
}
xhr.onerror=function(e){
alert(e);
}
xhr.open('POST',location.href,true);
xhr.send(data);
};
},false);
</script>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
Select image to upload:
<input type='file' name='fileToUpload'>
<input type='button' id='bttn' value='Upload' />
</form><div id='status'></div>
</body>
</html>

Using JQuery AJAX methods will allow you to send and receive information to a specified url without the need to refresh your page.
You will need to include the JQuery library in your HTML page aswell. You can either download it and put it in your project folder or include an online library here, like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
So your form will now look like this:
<form id="myForm" method="post" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
<input type="submit">
</form>
Then you can use this code to simply upload your image to your file upload page (tested and working for myself):
<script>
$(document).ready(function ()
{
$("#myForm").submit(function (e)
{
//Stops submit button from refreshing page.
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response)
{
alert('success');
},
error: function ()
{
alert('failure');
}
});
});
});
</script>

use AJAX With jQuery
$("#myForm").submit(function()
{
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(response) {
//Handle the response here
});
return false;
});

Related

Jquery change not working with Ajax call inside [duplicate]

For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});

posting text file thru jQuery ajax in php and download the response file

Requirement:
I have to submit a form in a PHP file which has a file type input. I need jQuery ajax to post this text file to lets say processFile.php
processFile.php will take this text file as input and after processing will return a csv file which I want to download at the client.
I have seen many posts but nothing is helping me out.
HTML:
<form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
<input type="file" name="image" id="image"/>
<br/><input type="submit" name="download" class="submit" value="Submit"/>
</form>
jQuery:
$(document).ready(function(){
$(".submit").click(function(e){
var urlstring = "processFile.php"
var form_data = new FormData($(this)[0]);
$.ajax({
url : urlstring,
type: "POST",
data : postData,
success:function(result){
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
window.open(uri, 'result.csv');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('failed');
echo (errorThrown);
}
});
});
});
I have tried hundreds of solutions given on the net but none is working.
Here I am providing complete working example:
HTML File:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(result) // A function to be called if request succeeds
{
e.preventDefault(); //stop the browser from following
window.location.href = 'upload/'+result;
}
});
}));
// Function to preview image after validation
});
</script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
Download
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>
PHP File:
<?php
if(isset($_FILES["file"]["type"]))
{
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo $_FILES["file"]["name"];
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>
Try to upload any file.
Is this useful for you?

JQuery AJAX POST not returning anything

Can't figure out what's wrong but all that happens is the URL changes to "http://localhost/?search=test" if I enter "test" for instance.
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$("#Form").submit(function(e) {
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
</script>
</head>
<body>
<form id=Form>
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
search.php
<?php
echo 'The search is '. $_POST['search'];
?>
You're missing the action and method on your form, which are necessary for the form to generate a submit event.
<form id="Form" method="post" action="search.php" />
Now that we have the action and method defined, why not just take it from the form instead of re-writing it in Javascript? That would be better for re-usability. Also note that you have to assign event handlers when the DOM is ready. At the time you're assigning the event, the DOM element doesn't exist, so it will do nothing:
<script type="text/javascript">
$(document).ready(function() { // Here, after DOM is ready
$('#Form').submit(function(e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
// At this point, we already have the response from the server (we got it asynchronously)
// Lets update a div, for example <div id="response_message"></div>
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
// Another option (same as before but with a function): Pass the response data to another function already defined: processData() in this case
// Use one or another, they're the same
processData( data );
},
error: function(err) {
alert('An error just happened...');
}
});
});
});
// This functions only receives data when the asynchronous call is finished
function processData( data )
{
$('#response_message').text( data );
// Div already has data, show it.
$('#response_message').show();
}
</script>
Note that in asynchronous calls you DO NOT expect a return. It simply doesn't exist by design (because the script would be blocked until the data is ready, and that's called synchronous). What you do in asynchronous calls is to define a function/method that will be called at any time when the data is ready (that's the success handler function). You don't know at what time it will be called, you only know that it will be called when data has been fetched and the argument will be the actual response from the server.
1st you forget " Form id and good to add method=""
<form method="post" action="#" id="Form">
2nd try to use e.preventDefault(); in the beginning not the end
3rd try to rearrange the code
<body>
<form method="post" action="#" id="Form">
Search: <input type="text" name="search" id="search" /><br />
<input type="submit" value="Submit" />
</form>
<script>
$("#Form").on('submit',function(e) {
e.preventDefault(); // use it here
$.ajax({
type: "POST",
url: "search.php",
data: $("#Form").serialize(),
success: function(data)
{
alert(data);
}
});
});
</script>

Upload files with Ajax and Jquery

I've been trying to figure out how to upload a file through ajax for the past several hours and nothing.
Here's the code:
HTML:
<form action="" method="post" id="uploadForm" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<input type="submit">
</form>
JS:
<script>
jQuery(document).ready(function(){
jQuery('form#uploadForm').on('submit', function(e){
e.preventDefault();
var file = jQuery('#image')[0].files[0];
var form_data = new FormData( jQuery("form#uploadForm")[0] );
form_data.append( 'image', file );
jQuery.ajax({
url: 'index.php?a=do',
type: 'POST',
processData: false,
contentType: false,
cache: false,
data: form_data,
success: function(response) {
console.log(response);
},
});
return false;
});
});
</script>
PHP:
<?php
$a = isset($_GET['a']) ? $_GET['a'] : '';
if($a <> '') {
echo "result - ";
var_dump($_POST);
die();
}
?>
As a result I get an empty array, however if I leave the file field empty, then I get:
result - array(1) {
["image"]=>
string(9) "undefined"
}
I've tried serialize(), serializeObject(), serializeArray(), $.param and every damn time I get "undefined function" error in console.
I went through dozens of similar questions on stackoverflow and nothing helped. I tried doing $.post instead of $.ajax and the "data" field which contains form_data is empty.
I need this for a Wordpress plugin and I'm trying to avoid using 3rd party JS plugins for the upload part.
$_FILES is where you check for uploaded files not $_POST.
Also in your code you actually upload the file twice as it is in the form you instantiated the form data object with then you add it again with append.
Do either
var form_data = new FormData( jQuery("form#uploadForm")[0] );
or
var form_data = new FormData();
form_data.append( 'image', file );
<html>
<head>
<title>Ajax file upload</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert(data);
}
});
}));
</script>
</head>
<body>
<div class="main">
<h1>Ajax Image Upload</h1><br/>
<hr>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<div id="image_preview"><img id="previewing" src="noimage.png" /></div>
<hr id="line">
<div id="selectImage">
<label>Select Your Image</label><br/>
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</div>
</form>
</div>
</body>
</html>

jQuery and php file upload

I do not understand, and google does not give me the answer. I want to upload a file and the results show in the div without page relode, but I can not get it!!!!
html:
<form method="post" action="process/pic2.php" enctype="multipart/form-data" id="userpic">
<p>Izvēlies bildi: <input type="file" name="img_to_upload" /><input type="submit" name="upload" value="Augšupielādēt" /></p>
</form>
jquery:
jQuery(function(){
jQuery('#userpic').submit(function(){
jQuery.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: jQuery('#userpic').attr('action'),
data: jQuery('#userpic').serialize(),
success: function(data){
if(data){
jQuery('#picinfo').html(data);
}else{
jQuery('#uerpic').fadeOut(500);
jQuery('#picinfo').html('<center><img src="img/loader.gif" /></center>');
window.location = 'index.php';
}
}
});
return false;
});
});
and my php:
if(isset($_FILES['img_to_upload']['name']) && !empty($_FILES['img_to_upload']['name'])){
echo 'Done!';
}else{
echo 'Error!';
}
all the time showing the "error" text..
P.S. Sorry for bad English.
Normally, to do a form-submission, and stay on the same page, you'll have to prevent the default form action with Javascript, something like this:
$("#userpic").submit(function(event) {
event.preventDefault();
...
});
But, uploading an image via Ajax is pretty tricky--see:
uploading files with jquery $.ajax and php

Categories