How to Upload a File Using Jquery's $.Ajax Function with JSON and PHP

How can I upload a file using jquery's $.ajax function with json and php

AJAX doesnt support file uploading. There are plugins like ajaxfileupload which basically creates a hidden form and uploads your file dynamically.

take a look here and read Oli's answer

Send data to json file using jquery/ajax and php

One extra ! in this test got you the exact opposite of what you meant to do (read it as "not"), removing it should help. Also added/changed some tests.

It's also good practice to output something in your ajax query, so you can get some feedback from the server in your browser dev tools.

<?php
var_dump($_POST);

if (isset($_POST['params'])) {
$params = $_POST['params'];
$jsonObject = json_encode($params);
if (is_writable('js/details.json')) {
file_put_contents('js/details.json', $jsonObject);
echo "success";
} else {
echo "file is not writable, check permissions";
}
} else {
echo "invalid params";
}

UPDATE : Also updated your jQuery code to pass the params variable under a params key, for it to be picked up correctly server-side (no need to stringify as json by the way, jQuery does it on your behalf):

    var object = {
name: 'John',
occupation: 'Lawyer'
}

$(".testing-php").click(function () {
$.ajax({
type: 'POST',
data: {params:object},
url: 'details.php',
success: function (data) {
console.log(params);
alert('success');
},
error: function () {
alert('error');
}
});

UPDATE : Also removed a test to accomodate an array-typed $_POST['params'].

Using jquery ajax upload file then get json format reponse but can not be display json data

Step 1: Use dataType as JSON

     $.ajax({
url: "upload.php?act=upload",
data : form_data,
type : 'POST',
dataType : "json",
processData : false,
contentType : false,
success : function (data) {
alert(data.code);
},
});

Step2: Use JSON.parse() method

 $.ajax({
url: "upload.php?act=upload",
data : form_data,
type : 'POST',
processData : false,
contentType : false,
success : function (data) {
var result = JSON.parse(data);
console.log(result);
},
});

jQuery Ajax File Upload

File upload is not possible through AJAX.

You can upload file, without refreshing page by using IFrame.

You can check further details here.


UPDATE

With XHR2, File upload through AJAX is supported. E.g. through FormData object, but unfortunately it is not supported by all/old browsers.

FormData support starts from following desktop browsers versions.

  • IE 10+
  • Firefox 4.0+
  • Chrome 7+
  • Safari 5+
  • Opera 12+

For more detail, see MDN link.

jQuery AJAX file upload PHP

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.

Your HTML is fine, but update your JS jQuery script to look like this:

(Look for comments after // <-- )

$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.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(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});

And now for the server-side script, using PHP in this case.

upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:

<?php

if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}

?>

Also, a couple things about the destination directory:

  1. Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
  2. Make sure it's writeable.

And a little bit about the PHP function move_uploaded_file, used in the upload.php script:

move_uploaded_file(

// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],

// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);

$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:

move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);

And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.

how to pass JSON data to php using ajax post

1) How can I examine the posted data? I.e. "Received Data: "+WHAT in syslog to see its structure.

As I understand you are debugging the code, so syslog can be not the best idea.
I would simply use the browser network console to see the content of requests and a simple php file like this to see the content of $_POST:

<?php
echo json_encode($_POST);

In more complex cases - use the actual debugger.

2) JSON parse error? Most examples I see use this stringify function. then they use json_decode to get the values. Why the parse error?

You are trying to use the json key in your $_POST, but you didn't instruct jQuery to add it, so you are receiving not what you expected.

There are few issues with your $.ajax call, here is the commented version:

$.ajax({
type: 'POST',
url: './json.php',
dataType: 'json', // Note: dataType is only important for the response
// jQuery now expects that your server code
// will return json

// here you need to add the 'json' key
data: {'json': JSON.stringify(data)},

// the success method has different order of parameters
//success: function(xhr, status, errorMessage) {
success: function(data, status, xhr) {
alert("response was "+data);
},
error: function(xhr, status, errorMessage) {
$("#debug").append("RESPONSE: "+xhr.responseText+", error: "+errorMessage);
}
});

Now on the server you will have $_POST['json'] with serialized string and you can json_decode it.

Alternatively you can send the JSON data without serialization:

var data = {'test': 'abc'};

$.ajax({
type: 'POST',
url: './json.php',
// No 'JSON.stringify()', just send your data
data: data,
...
});

And on the server you will have $_POST['test'] with abc value (so you have your json already converted into array).

How to write file upload function ajax, jquery, php? How should I write my '.submit()' using Ajax function?

Please use the below files code to upload the files and return success or error in the jason format:

index.php file code

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>Files Upload</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data" >
<input id="file-upload" type="file" name="fileToUpload[]" multiple required>
<input type="submit" id="file-submit" value="Upload Selected Files">
</form>

<script type="text/javascript">
$(document).ready(function(){
$("#file-submit").click(function(event){
event.preventDefault();
var formdata = new FormData($(this).parents('form')[0]);

$.ajax ({
type: "POST",
url: "upload.php",
dataType : 'json',
data: formdata,
success: function(data){

if(data.status){
alert(data.status);
}else{
alert(data.error);
}
},
processData:false,
contentType: false,
cache: false
});
return false;
})
});
</script>
</body>
</html>

upload.php file code here

<?php
function getExt($name){
$array = explode(".", $name);
$ext = strtolower(end($array));
return $ext;
}

//create global array
$allowed = array('jpg', 'png', 'jpeg', 'mp4');
$message = array();
$error = array();
$jason = array();

if(isset($_FILES['fileToUpload']) && !empty($_FILES['fileToUpload'])){
foreach ($_FILES['fileToUpload']['name'] as $key => $name) {
$tmp = $_FILES['fileToUpload']['tmp_name'][$key];
$ext = getExt($name);
$size = $_FILES['fileToUpload']['size'][$key];

// check the extension is valid or not
if(in_array($ext, $allowed) == true){
$filename = md5($name) . time() .'.'.$ext;
//check the size of the file
if($size <= 10485760){
if(move_uploaded_file($tmp, 'uploadFiles/'.$filename) === true){
$message['status'] = 'File is uploaded successfully';

}else{
$message['error'] = 'File is not uploaded';
}
}else{
$message['error'] = 'File size more than 2MB';
}
}else{
$message['error'] = 'File Type not allowed';
}
}

echo json_encode($message);exit();

}
?>

Hope this help!!



Related Topics



Leave a reply



Submit