How can I upload file with AJAX using PHP? - javascript

I want to upload file to server using AJAX and PHP. Here is what I've tried so far but it is not working for me.
The server throws this error:-
Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 3
Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 7
Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 7
Client side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript">
function valid(){
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'test.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('#result').html(data); // display response from the PHP script, if any
}
});
}
</script>
</head>
<body>
<div id='result'></div>
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick='valid()'>Upload</button>
</body>
</html>
And here is client side code, test.php:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name'])){
echo "file uploaded";
}
}
?>

These two lines are wrong:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
Use only one version of jQuery: 1.5.1 or 2.1.4 (I suggest the last one)!

As the error message is telling you, there is no 'file' member to the $_FILES associative array in PHP. I think you want 'name'.

Use jQuery File Upload Plugin, It has many cool feature which will save more time and avoid re-inventing the wheel again.
Library:
https://blueimp.github.io/jQuery-File-Upload/
PHP Setup Guide:
https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'server/php/'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 999000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});

This works for me always:
function valid(){
var formData = new FormData();
formData.append('file', $("#sortpicture")[0].files[0]);
$.ajax({
url: "test.php",
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: formData,
success: function(data){
// Process response here. May be preview image?
},
error: function(r){
// Handle errors
},
});
}

Related

Make a GET request after POST request is passed sucessfully with Laravel?

I am trying to make a file upload system on AWS based on laravel with ajax. I am talking about a resume parser system where i used the apilayer API to parse the CV from pdf to json.
I tried to make a file upload system where files are uploaded to aws (this works) and after i get the uploaded file url to send to API.
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:doc,docx,pdf|max:2048',
]);
$fileName = time() . '.' . $request->file->extension();
$path = $request->file->storeAs('file', $fileName, 's3');
CVupload::create(['name' => $fileName]);
$urlcv = Storage::disk('s3')->url($path);
return response()->json("$urlcv");
}
}
Everything is ok, but when the API is executed from the below code i receive the error:
Client error: POST https://api.apilayer.com/resume_parser/url?url=https://--.s3.eu-central-1.amazonaws.com/file/-- resulted in a 403 Forbidden response:{"message":"You cannot consume this service"}
I see that the request is POST, and i have to make a GET REQUEST. Maybe its an error in Ajax Script?
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#file-upload').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#file-input-error').text('');
$.ajax({
type: 'POST',
url: "{{ route('resume.store') }}",
data: formData,
contentType: false,
processData: false,
success: (response) => {
if (response) {
this.reset();
$("#showResponseArea span").html(response); //you will paste your response msg to the
$.ajax({
type: 'GET',
url: "{{ route('resume.api') }}",
dataType: 'json',
data: {
'url': response,
}
})
}
},
error: function(response) {
$('#file-input-error').text(response.responseJSON.message);
}
});
});
</script>

How to send the <input type="file"> data from AJAX by putting it in object?

I have a simple upload file in my html like so:
<div class="col-md-12">
<span id="fileUploadErr">Please Upload A File!</span>
<div style="margin-bottom: 10px;"></div>
<input id="pickUpFileAttachment" type="file" name="attachFileObj" size="60" />
</div>
When I click on the "Submit" button the following action occurs:
$("form").submit(function() {
event.preventDefault();
var assignmentObj1 = {
selectionId: trDataSecondTable.selectionId,
inout: "in",
letterReceivedBy: $("#letterReceivedBy").val(),
letterIssuedSubBy: $("#letterIssuedSubBy").val(),
representativeNameEng: $("#representativeNameEng").val(),
letterId: 2,
assessmentNo: 0
imageFile: $("#representativeNameEng").val()
imageTitle:
}
console.log(jsonData);
$.ajax({
url: A_PAGE_CONTEXT_PATH + "/form/api/saveProcessAnexTwo",
method: "post",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(assignmentObj1),
success: function(response) {
},
error: function(response) {
switch (response.status) {
case 409:
alert("error");
}
}
});
});
I need to assign the fileName and the uploaded file while sending from AJAX and need to put it inside the assignmentObj1 variable so I tried: imageFile: $("#representativeNameEng").val() to get the file information but it is not coming. How can I get the file information and send from AJAX by putting it in a local variable? And also how can I get the name of the file which can be placed in the imageTitle: property?
This is how to deal with the file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jquery Ajax File Upload</title>
</head>
<body>
<div class="col-md-12">
<span id="fileUploadErr">Please Upload A File!</span>
<div style="margin-bottom: 10px;"></div>
<input id="pickUpFileAttachment" type="file" name="pickUpFileAttachment" size="60" />
</div>
<div class="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// $("form").submit(function(){
$('#pickUpFileAttachment').change(function(e){
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url : window.location.pathname + "/form/api/saveProcessAnexTwo",
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false,
success: function(response){
alert("suc");
$('.result').html(response.html)
} , error: function(response){
switch(response.status){
case 409:
alert("error");
}}
});
});
//});
});
</script>
</body>
</html>
Easiest method is to use formData to send data:
var data = new FormData();
$.each($('#filecontainer')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have formData object
$.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});
Hope this helps.

json_decode php returns null on valid json

I am trying to send a json object through ajax post in javascript as follows:
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {json: cond},
dataType: 'json',
success: function(response) {
alert(response["json"]);
}
});
cond represents the json object which is something like this(converted with JSON.stringify):
[{"field":"name","condition":"<","value":"John"}]
on testPost.php file I have the following:
<?php
$return=$_POST["json"];
$decoded_json=json_decode($return);
$reply["json"]=$decoded_json;
print_r ( json_encode($reply));
?>
My problem is that Json_decode is returning null.
I have checked the encoding(UTF-8), and also checked that the json witch i send to the php file has no slashes or anything.
Can anyone help me?
header('Content-Type: application/json');
You need to add this line in PHP before echo.
Then
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {json: cond},
dataType: 'json',
success: function(response) {
alert(response.field);
alert(response.condition);
alert(response.value);
}
});
Your Ajax data converted to
[{json : {"field":"name","condition":"<","value":"John"}}]
It's not valid because of json : side.
Convert your Jquery to
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {"json": cond},
dataType: 'json',
success: function(response) {
alert(response["json"]);
}
});
And There is works example here,
<?php
if(count($_POST) > 0){
print_r($_POST);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
var cond = [{"field":"name","condition":"<","value":"John"}];
$.ajax({
type: 'POST',
url: 'a.php',
data: {"json" : cond},
dataType: 'text',
complete: function(response) {
$("body").html(response.responseText);
}
});
})
</script>
</head>
<body>
</body>
</html>
try using stripslashes() then json_decode()
$decoded_json = json_decode(stripslashes($return));

Jquery Unable to make Ajax Request to Server

I am trying to make an AJAX Request through JQuery
The below is my code .
But when i debugged through Mozilla Firebug i observed that ,there is no Request hitting to the Server .
Could anybody please tell me where i am doing wrong .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JQuery Example</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'ajax/balances',
processData: false,
timeout: 10000,
type: "POST",
contentType: "application/xml",
dataType: "json",
data: '<MyReq user="' + User + '" katha="' + ivalitiKatha + '" />',
success: function(data) {
},
error : function() {
alert("Sorry, The requested property could not be found.");
}
});
});
</script>
</body>
</html>
This is my web.xml on server side
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/ajax/*</url-pattern>
</servlet-mapping>
Maybe adding <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> to the head instead of the body helps!
First of all I would recommend moving the CDN JQuery into the head section of the website.
Secondly I have tested the code above and the issue looks to lie with the (data) you are posting in the JSON / AJAX request.
If you remove it or amend to JSON the request returns a result e.g.
$.ajax({
url: 'test',
processData: false,
timeout: 10000,
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"foo": "bar"}',
success: function(data) {
alert('Success');
},
error : function() {
alert("Sorry, The requested property could not be found.");
}
});​
You will need to format the data as a JSON request
data: '{"foo": "bar"}',
Hope this helps

How do I send an ajax post request to a specific module in Drupal6?

I want to send an ajax post request to a module named sampleTest in Drupal6.
I have tried some bits of codes but I do not know how to put the module url in the jquery ajax function.
<script type="text/javascript">
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost/drupal/www/admin/build/modules/module/get/contact',
dataType: 'json',
data: "test",
success:function(data) {
alert("123");
},
complete: function(data){
alert("complete");
}
});
});
});
</script>
You can't send an AJAX request to a module as such, rather you implement a path in your module (using hook_menu()), provide a page callback for that path that outputs the AJAX response, and then call that path in your AJAX call. This is a very basic example:
function mymodule_menu() {
$items['ajax-test'] = array(
'access callback' => TRUE,
'page callback' => 'mymodule_ajax_callback',
'type' => MENU_CALLBACK
);
}
function mymodule_ajax_callback() {
$post_data = $_POST;
// Do something with the post data
$output = array('status' => 'OK');
// For Drupal 6
drupal_json($output);
exit();
// Or for Drupal 7, just in case you want to know
drupal_json_output($output);
drupal_exit();
}
Then your JS would look like this:
$(function(){
$("#one").click(function(){
$.ajax({
type: 'POST',
url: '/drupal/ajax-test',
dataType: 'json',
data: "test",
success:function(data) {
alert(data.status);
},
complete: function(data){
alert("complete")
}
});
});
});

Categories