Having Issue On Uploading Loaded Image by jQuery Ajax on Server - javascript

I am trying to save a loaded image on Server Using jQuery,Ajax and PHP.
Here is the code I have for Ajax part:
<script>
$(function () {
$("#uploadimage").on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
var imgloader = $.ajax({
type: "POST",
url: "imgLoader.php",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formData);
}
});
imgloader.fail(function () {
console.log('Error');
});
imgloader.done(function (data) {
$('#res').text(data);
});
});
});
</script>
and I have this PHP on imgLoader.php
<?php
if (isset($_FILES["file"]["type"])) {
$file = $_FILES['file']['tmp_name'];
$newloc = "newupload/" . $_FILES['file']['name'];
move_uploaded_file($file, $newloc);
} else {
echo 'There is Something Wrong?!';
}
?>
but I am getting the
There is Something Wrong?!
on the page without uploading the image on server. Can you please let me know what I am doing wrong? (I know this is not a secure and safe way to upload image to server, but please be informed that I am trying to lean the whole process of uploading without validation, sanitizing or filtering)
Thanks

AJAX doesn't do file uploads. It's not designed for that. For uploading files without page refreshing you will have to use any jquery ajax plugin.For e.g.
http://www.malsup.com/jquery/form/
This problem is already discussed in following link:
PHP and Ajax file upload - Can't get the tmp_name with $_FILES

Related

Header PHP not working after AJAX call from Javascript

so, this is probably a dumb question, but is it possible to execute the header function in a php file if I'm getting a response with AJAX?
In my case, I have a login form that gets error codes from the PHP script (custom error numbers hardcoded by me for testing) through AJAX (to avoid reloading the page) and alerts the associated message with JS, but if the username and password is correct, I want to create a PHP cookie and do a redirect. However I think AJAX only allows getting data, right?
This is my code:
JS
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
}
});
PHP
if(empty($user)){
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
setCookie(etc...); //this is
header('admin.php'); //what is not executing because I'm using AJAX
}else{
echo 902;
}
}
Please sorry if the question doesn't even make sense at all but I couldn't find a solution. Thanks in advance!
EDIT: I did not include the rest of the code to avoid complicating stuff, but if you need it for giving an anwser I'll add it right away! (:
You're right, you can't intermix like that. The php would simply execute right away, since it has no knowledge of the javascript and will be interpreted by the server at runtime, whereas the js will be interpreted by the browser.
One possible solution is to set a cookie with js and redirect with js as well. Or you could have the server that receives the login request set the cookie when the login request succeeds and have the js do the redirect after it gets a successful response from the server.
You can't do like that because ajax request process in backed and return the particular response and if you want to store the cookies and redirect then you should do it in javascript side while you get the response success
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location = "admin.php";
}
});
if(empty($user)){
setCookie(etc...); //this is
echo 901;
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo response// what every you want to store
}else{
echo 902;
}
}
If the ajax response satisfies your condition for redirection, you can use below:
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
var responseCode = parseInt(response);
alert(codes[responseCode]);
window.location="%LINK HERE%";
}
});
It's kind of ironic that you use ajax to avoid loading the page, but you'll be redirecting in another page anyway.
test sending data in json format:
Javascript
$.ajax({
type: 'POST',
url: 'validate.php',
data: $this.serialize(),
success: function(response) {
if(response.success){
window.location="%LINK HERE%";
}else{
var responseCode = parseInt(response.code);
alert(responseCode);
...
}
}
});
PHP
header("Content-type: application/json");
if(empty($user)){
echo json_encode(['success' => false, 'code' => 901]);
}else{
if(hash_equals($user->hash, crypt($password, $user->hash))){
echo json_encode(['success' => true, 'data' => response]);
}else{
echo json_encode(['success' => false, 'code' => 902]);
}
}

Passing image from form to wordpress using ajax without any plugin

I have made a form on my wordpress theme through which i want user to upload image .This is my HTML
<input type="file" id="file" />
<button id="uplod" ">Upload</button>
and below is my js
jQuery("#uplod").click(function()
{
console.log("trying to fetch image");
var selectedFile = jQuery('#file').get(0).files[0];
console.log(selectedFile);
var ajaxdata=
{
action:"reg_upload_img",
img:"selectedFile"
}
jQuery.post(ajaxurl, ajaxdata,function(res)
{
jQuery(".divError").html(res);
});
});
and my function in functions.php file of theme is
function fiu_upload_file(){
$error = '';
var_dump($_FILES);
wp_die();
}
add_action('wp_ajax_reg_upload_img', 'fiu_upload_file');
add_action('wp_ajax_nopriv_reg_upload_img', 'fiu_upload_file');
what should i add in my js code and php code so that image of form can be passed to my wordpress directory so that i can save and handle it in wp database
You can't upload files with jQuery.post(), only XMLHttpRequest can be used with FormDataand jQuery.ajax() can be used which uses XMLHttpRequest internally.
jQuery("#uplod").click(function(e) {
e.preventDefault();
var fd = new FormData($("#file"));
fd.append("action", "reg_upload_img");
fd.append("img","selectedFile");
$.ajax({
url: url,
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});
});
and a small typo with your button's attributes, you have an extra ":
<button id="uplod">Upload</button>
//----------------^-----------one extra '"' removed from here.

AJAX Codeigniter - You did not select a file to upload(error)- How to pass the file through AJAX

I am trying to upload images via an AJAX call and Codeigniter:
My View:
<?php echo form_open_multipart('upload/do_upload'); ?>
<input type="file" name="userfile" id="userfile" size="20" />
<br />
<input type="submit" value="upload" id="upload_file_1" />
</form>
My Ajax Call:
$(document).ready(function(){
$(function() {
$('#upload_file_1').click(function(e) {
e.preventDefault();
var filename = $("#userfile").val();
$.ajax({
url :'index.php/upload/do_upload',
secureuri :false,
fileElementId: 'userfile',
dataType : 'json',
type : 'POST',
done : function (data)
{
alert(data);
}
});
});
});
});
and my controller:
class Upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$this->load->view('upload_form', array('error' => ' '));
}
function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000000';
$config['max_width'] = '10240';
$config['max_height'] = '7680';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
echo "error!";
echo "<pre>";
print_r($error);
echo "<pre/>";
} else {
echo "done!";
}
}
}
but it gives me an error saying : "You did not select a file to upload. "; without AJAX it works fine, probably my AJAX call is not right! Could you please let me know if I am doing something wrong?
Thanks
In my very recent project i used below code to upload files with formdata asynchronously using jquery ajax,
However i was not able to upload files with success: function() of jQuery so i used complete to process server response. You can try with success:function().
You will receive your data in $_Post & file in $_FILES variable.
If only want to upload files. change it like wise.
Hope this will help you.
Also look at this tutorial:http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
function frm_submit(){
var form = new FormData(document.getElementById('frmSample')); //frmSample is form id
var file = document.getElementById('userfile').files[0]; //userfile file tag id
if (file) {
form.append('userfile', file);
}
$.ajax({
url: 'path/to/upload/script',
type: 'POST',
xhr: function() { // custom xhr
//progressHandlingFunction to hangle file progress
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // for handling the progress of the upload
}
return myXhr;
},
data: form,
cache: false,
contentType: false, //must
processData: false, //must
complete: function(XMLHttpRequest) {
var data = JSON.parse(XMLHttpRequest.responseText);
console.log(data);
console.log('complete');
},
error: function() {
console.log('error');
}
}).done(function() {
console.log('Done Sending messages');
}).fail(function() {
console.log('message sending failed');
});
}//function frm_submit ends here
i used this javascript library
https://github.com/blueimp/jQuery-File-Upload
and got file uploading working with ajax - drag/drop + progress bars, and returns the appropriate file icon or image thumbnail that could be downloaded straight away. it was quite difficult to get it fully working and abstracted so the same routine handled multiple types of uploads each with their own restrictions.
the link will give some basic example code, it is worth a look.
pete

trying to upload a file using HTML5 and ajax

I have been attempting to get a nice neat file upload using ajax, and from the many items on SO I have been able to get the framework done as follows:
My HTML:
<form enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input type="button" value="Upload" />
Pretty straight forward.
My PHP storeSales.php
if ($_FILES["file"]["name"] != NULL) {
if (file_exists("accounting/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"], "accounting/" . $_FILES["file"]["name"]);
}
}
$file = fopen($_FILES['myfile']['name'],'r') or die('cant open file');
and my .js:
$(":button").click(function(){
var formData = new FormData($('form')[0]); if (formData !=null) {
alert("Got the file");
} else {
alert("nothing Here");
}
$.ajax({
url: 'storeSales.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(result)
{
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
When I try to upload a file, I get the alert in my .js file that says "Got the file" but in the php code I get the error that a file cannot be empty. From everything I have been able to find, I thought I was doing the php correctly. what is the correct way to handle this? Am I missing something else?
You can't use ajax to upload files - it's an illegal operation (via the dry Ajax route) without a third-party script. In short, you can't pass $_FILES data via Ajax. Only $_POST data. You need to find a plugin.
Try Uploadify:
http://www.uploadify.com/

Form or jQuery Ajax?

When a form sends variable with GET Method, the URL changes, putting the variables that you are passing in this way
url?variable=....
How can I get the same result with jQuery Ajax? Is it possible? Thank you
set path in your php layout/view file where you include this code
<script>
var path="<?php echo $this->webroot;?>";
</script>
and add following jquery code to post the data through ajax.
$.ajax({
type: 'POST',
url: path+'homes/createEvent',
data: {eventname:eventname,manager:manager},
async: false,
success: function(resulthtml)
{
alert(resulthtml);
},
error: function(message)
{
alert('error');
}
});
and on homes_controller.php, u will get this ajax data in createEvent function,
<?php
function createEvent()
{
$eventName=$_POST['eventname'];
$manager=$_POST['manager'];
}
?>

Categories

Resources