dropzone.js and ajax call = empty $_FILE, $_POST - php

I am trying to send form variables to PHP via AJAX and show the result in console.log. But the console shows always no value for data. I donĀ“t know what's wrong. What I have so far:
Part of jQuery Code:
...
init: function() {
this.on('success', function(csvFile, json) {
// AJAX
$.ajax({
url : "tests.php",
type : "POST",
data : this.csvFile
}).done(function (data) {
// Bei Erfolg
console.log("Erfolgreich:" + data);
}).fail(function() {
// Bei Fehler
console.log("Fehler!");
}).always(function() {
// Immer
console.log("Beendet!");
});
});
Part of HTML Code:
<form action="tests.php" class="dropzone" id="myAwesomeDropzone">
<input type="text" name="testname" value="das bin ich"/>
</form>
PHP Code:
if(!empty($_FILES)){
$test = $_FILES['file']['tmp_name'];
echo test;
}
if(!empty($_POST)){
$test2 = $_POST['testname'];
echo $test2;
}

Your HTML code and PHP works fine (just need to fix "echo test" to "echo $test" in your tests.php). Dropzone automatically attach itself to anything with class "dropzone" and it will do ajax requests to your server after you select a file.
If you want to programmatically:
HTML
<div id="myDZ">
Drop your file
<input type="text" id="testname" name="testname" value="hello_world"/>
<button id="upload">upload</button>
</div>
jQuery:
<script type="text/javascript">
$("#upload").click(function(e){
myDZ.processQueue();
})
var myDZ = new Dropzone("#myDZ", {
url: "tests.php",
autoProcessQueue: false,
init: function(){
this.on('sending', function(xhr, fd1, fd2){
//append extra data here
fd2.append("testname", $("#testname").val());
});
this.on('success', function(file, responseText){
//do after successful upload
console.log(responseText);
})
}
});
</script>
you can remove "autoProcessQueue: false" and remove the button stuff if you want it to auto upload once a file is selected.
more events can be found here: http://www.dropzonejs.com/#event-list

Related

Get AJAX POST Using PHP

I have a drpcategory dropdown in a form. I will just paste the dropdown code below;
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
Then I AJAX post every time I make a selection in the above drpcategory dropdown as below;
<script>
$(function(){
$('#drpcategory').on('change',function()
{
$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
});
});
</script>
This seems to be currently working as I'm getting outputs like below in Chrome Browser > Inspect > Network tab every time I make a selection in drpcategory. Here is the screenshot;
The question is how can I capture this AJAX post data using PHP within the same page and echo it within the same page? So far I have tried;
<?php
if(isset($_POST['drpcategory']))
{
echo 'POST Received';
}
?>
I'm looking for a solution using only PHP, JQuery and AJAX combined.
This question was later updated and answered here:
AJAX POST & PHP POST In Same Page
First of all, this line -> type: $(this).attr('post') should be type: $(this).attr('method'),. So this will give the value ** type:post** and
As far as i understand, you are asking to send ajax whenever you select options from drpcategory. Why are you submitting the entire form for this. If i where you, i should have done this problem by following way
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
On you php side, you can get your data like,
echo $_POST['drpcategory'];
I recommend you read the documentation for the ajax function, I tried to replicate it and I had to fix this:
$.ajax({
// If you don't set the url
// the request will be a GET to the same page
url: 'YOU_URL',
method: 'POST', // I replaced type by method
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});
http://api.jquery.com/jquery.ajax/
OUTPUT:
First change to $value
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category2 = file($category, FILE_IGNORE_NEW_LINES);
foreach($category2 as $value)
{
echo "<option value='".$value."'>".$value."</option>";
}
?>
</select>
then add url
<script>
$(function()
{
$('#form').submit(function(e)
{
e.preventDefault();
$.ajax({
url:'folder/filename.php',
type: 'post',
data: '{ID:" . $Row[0] . "}',
success: function(result) {
console.log(result);
}
});
});
$('#drpcategory').on('change',function()
{
$("#form").submit();
});
});
try request
if(isset($_REQUEST['ID']))
The result will/should send back to the same page
Please try this code:
$.post('URL', $("#FORM_ID").serialize(), function (data)
{
alert('df);
}
I think you have an eroror syntax mistake in ajax jQuery resquest because ajax post 'http://example.com/?page=post&drpcategory=Vehicles' does not return this type url in browser Network Tab.
<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.
Here ajax request example
$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
type: 'post',
data: drpcategory,
success: function(result) {
console.log(result);
}
});
});
`
It sounds like you're trying to troubleshoot several things at once. Before I can get to the immediate question, we need to set up some ground work so that you understand what needs to happen.
First, the confusion about the URL:
You are routing everything through index.php. Therefore, index.php needs to follow a structure something like this:
<?php
// cleanse any incoming post and get variables
// if all your POST requests are being routed to this page, you will need to have a hidden variable
// that identifies which page is submitting the post.
// For this example, assume a variable called calling_page.
// As per your naming, I'll assume it to be 'post'.
// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
// set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
header('Content-Type: application/json');
print json_encode(array('message' => 'Your submission was received'));
// if this is from an ajax call, simply die.
// If from a regular form submission, do a redirect to /index.php?page=some_page
die;
}
// if you got here, there was no POST submission. show the view, however you're routing it from the GET variable.
?>
<html>
(snip)
<body>
<form id="form1" method="post">
<input type="hidden" name="calling_page" value="page" />
... rest of form ...
<button id="submit-button">Submit</button>
</form>
}
Now, confusion about JQuery and AJAX:
According to https://api.jquery.com/jquery.post/ you must provide an URL.
All properties except for url are optional
Your JQuery AJAX will send a post request to your index.php page. When your page executes as shown above, it will simply print {message: "Your submission was received"} and then die. The JQuery will be waiting for that response and then do whatever you tell it to do with it (in this example, print it to the console).
Update after discussion
<div class="form-group">
<label>Category</label>
<select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
<?php
$category = ''.$dir.'/template/post/category.txt';
$category = file($category, FILE_IGNORE_NEW_LINES);
foreach($category as $category)
{
echo "<option value='".$category."'>$category</option>";
}
?>
</select>
</div>
<!-- HTML to receive AJAX values -->
<div>
<label>Item</label>
<select class="" id="drpitem" name="drpitem"></select>
</div>
<script>
$(function(){
$('#drpcategory').on('change',function() {
$.ajax({
url: '/receive.php',
method: 'post',
data: $(this).serialize(),
success: function(result) {
workWithResponse(result);
}
});
});
});
function workWithResponse(result) {
// jquery automatically converts the json into an object.
// iterate through results and append to the target element
$("#drpitem option").remove();
$.each(result, function(key, value) {
$('#drpitem')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
</script>
receive.php:
<?php
// there can be no output before this tag.
if(isset($_POST['drpcategory']))
{
// get your items from drpcategory. I will assume:
$items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');
// send this as json. you could send it as html, but this is more flexible.
header('Content-Type: application/json');
// convert array to json
$out = json_encode($items);
// simply print the output and die.
die($out);
}
Once you have everything working, you can take the code from receive.php, stick it in the top of index.php, and repoint the ajax call to index.php. Be sure that there is no output possible before this code snippet.

Input type file - ajax upload, and php script

I am trying to use jquery( v. 1.11.3 )ajax, in conjunction with jquery.validate 1.15 to upload a form that includes input type file. You can see from the js comment lines some of everything I have tried. With each of the variations the php script returns "no image file". Of course, if I remove the jquery script, the form submits fine with accompanying page refresh. I really wanted to eliminate the page refresh for a better UX but I am having no luck getting this to work. If someone could help me fix my code, I'd really appreciate it. Please Note: I have researched numerous examples of jquery ajax .post but these examples are not helping me as those code structures don't work with Jquery.Validate plugin. I also found this answer here: File Upload PHP AJAX but as you can see from my code comments, I have tired this with no luck.
I must be missing something.
Heading ##The html and js:
<!DOCTYPE html>
<html>
<body>
<form action="imguploadTest.php" method="post" enctype="multipart/form-data" id="addItemsForm" name="addItemsForm">
<label>Select image to upload:</label>
<input type="file" name="itemImg" id="itemImg" />
<label>Name</label>
<input type="text" name="itemName" class="form-control" placeholder="Item Name..." maxlength="25" value="Really Cool Hoodie" />
<input type="submit" value="Upload Form" name="submit">
<div>
<div id="results"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script src="js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.min.js"></script>
<script>
$(document).ready(function(){
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if (element.parent('.radio-inline').length || element.parent('.checkbox-inline') ) {
error.insertAfter(element.parent().parent());
} else {
error.insertAfter(element);
}
}
});
$('#addItemsForm').validate({ // initialize the plugin
debug: true,
submitHandler: function(){
//var formData = $('#addItemsForm').serialize();
//var data = new FormData($('#addItemsForm'));
//var form = $('form')[0];
//var formData = new FormData(form);
//console.log(addform);
var frmData = new FormData($(this)[0]);
$.ajax({
url: "imgUploadTest.php",
data: frmData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
.done( function(res, jqXHR, textStatus) {
console.log(res);
//$('#results').html('<h4>Thumb link: ' + res["thumb"] + '<h4>');
//$('#results').append('<h4>Small link: ' + res["small"] + '<h4>');
//$('#results').append('<h4>Name: ' + res["name"] + '<h4>');
})
.fail( function (res, jqXHR, textStatus, errorThrown){
alert("failed! " + jqXHR, textStatus);
});
return false;
} // submitHandler
}); // validate
}); // doc ready
</script>
</body>
</html>
Heading ##The PHP:
<?php
include 'imguploader.class.php';
// FUNCTIONS
function imagehandler($item_attr_ID) {
$imgId = $item_attr_ID;
$img = new imgUploader($_FILES['itemImg']);
$time = time();
$thumb = $img->upload('mobileApp/uploads/', $imgId.'_thumb', 100,100); // change these numbers for display
$small = $img->upload('mobileApp/uploads/', $imgId.'_small', 400,400); // change these numbers for display
//$full = $img->upload_unscaled('mobileApp/uploads/', $time);
if($thumb && $small){ // && $full
return array($thumb, $small);
/* TO SHOW IMAGE
echo '<img src="'.$thumb.'" alt="aPicture" /> <img src="'.$small.'" alt="aPicture" /> <img src="'.$full.'"alt="aPicture" />';
*/
} else {
echo ( 'ERROR! '.$img->getError() ); // --> error code 011.1
}
} // end imagehandler()
// Processes
if (!empty( $_FILES["itemImg"]) ){
$item_attr_ID = "jPlayerandtheGirls_8_1456";
list($item_img_thumb, $item_img_small) = imagehandler($item_attr_ID);
if ($item_img_thumb && $item_img_small){
$r["thumb"] = $item_img_thumb;
$r["small"] = $item_img_small;
} else {
$r["thumb"] = "No Thumb";
$r["small"] = "No Small";
$r["name"] = "Didn't get to name";
echo json_encode($r);
}
} else {
$r = "No image file";
echo json_encode($r);
}
if (!empty( $_POST["itemName"] )){
$r["name"] = $_POST["itemName"];
json_encode($r);
}
?>
Ok I am able to answer my own question, though I am not exactly sure about the theory that goes with it as I am relatively new to JS/Jquery. .serialize() does not work. I think this is because by definition, files are binaries and thus can not be serialized - but don't quote me. So you have to use FormData to send the file. I was aware of this but could not come up with the proper syntax for use with jquery validation 1.15. See the answer below. Hope it helps someone to save some time.
first correct the rookie mistake with my code: add type: 'post'
second: the variable to hold your form's data, including the input type="file" is this var formData = new FormData($('#useYourFormElementIdHere')[0]);
So the final is this:
$.ajax({
type: "POST",
url: "imgUploadTest.php",
data: formData,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
}).done({}).fail({}).always({})

I want to upload file my file

I was getting undefined file as an error in my php while uploading a file.
function click_submit_form() {
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data: $('#id_frm_charity_details').serialize(),
success: function (data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data'>
<input id="id_file" name="file" class="input-file" type="file"> <a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
In my php
<?php
$files = $_FILES['file']['name'];
$files_tmp = $_FILES['file']['tmp_name'];
$copy = copy($files_tmp, $files);
//echo $_POST['file'];
move_uploaded_file($files_tmp, "C:\wamp32\www\jb_from_live\src\uploaded_files/" . $files);
?>
If i use the above line then it says undefined index 'file'.But the execution not going after $files=$_FILES['file']['name'];
It says undefined index file.
Send image to this format
$('#form').submit(function() {
var img=$('#image').val();
var forms=($(this).serialize());
$.ajax({
type:"POST",
url: "do.php?do=upload",
data:forms+'&r='+encodeURIComponent(img),
success: function(result){ //your code }
});
Try this in your code like this
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function click_submit_form(){
var action = "jb_data_charity_submit.php";
// alert("I step"+$('#id_frm_per_details, #id_frm_acc_details , #id_frm_charity_details').serialize());
var img=$('#id_file').val();
var forms=($('#id_frm_charity_details').serialize());
$.ajax({
url: 'jb_data_charity_submit.php',
type: 'POST',
data:forms+'&r='+encodeURIComponent(img),
// data: $('#id_frm_charity_details').serialize(),
success: function(data_in) {
//alert(data_in);
if (data_in != null && !isEmpty(data_in) && (data_in).indexOf('VALIDATION_ERROR') != -1) {
var value = data_in.substr(data_in.indexOf('VALIDATION_ERROR'), data_in.indexOf('|#END#'));
var array_str = value.split('|')
//alert(array_str[0]);
//alert(array_str[1]);
//alert(array_str[2]);
var id_val = "#id_" + array_str[1].trim();
show_error(id_val, array_str[2])
} else {
window.location.replace('jb_charity_regn_confirm.html');
alert(data_in);
// alert("FINAL");
}
}
});
return false;
}
</script>
<form class='form-vertical' id='id_frm_charity_details' name='frm_charity_details' action='jb_data_harity_submit.php' enctype='multipart/form-data' >
<input id="id_file" name="file" class="input-file" type="file">
<a onclick='click_submit_form();' href="#" class="btn btn-info btn-custom8 btn-large "><i class=" icon-play"></i> Submit Application</a>
</form>
I recommend you to use FormData instead of serialize(). The advantage of using formData is that you can also upload pdf,xml,JSON files by specifying their content-type.
For eg:
var fData = new FormData();
fData.append("XML", new Blob([ xml ], { type: "text/xml" });
fData.append("JSON", new Blob([ JSON.stringify(json) ], { type: "application/json" }));
fData.append("PDF", file);
Make sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
You cannot upload a file via ajax that simply unfortunately, for security reasons js doesn't have access to file data and therefore cannot post it via the form serialize function.
If you want to validate other parts of the form and then submit you could write a function like this
function submit(){
var valid = true;
//TODO: check validation on form, set valid to false if incorrect
if( valid )
document.forms[0].submit();
return false;
}
If you want to use HTML5 have a geez at this answer which utilizes the FormData() function:
How can I upload files asynchronously?
Otherwise if you with to upload a file asynchronously you'll have to look for a jsp or flash fallback plugin.
Here's a really good one:
http://blueimp.github.io/jQuery-File-Upload/

getting response from a php script

So I created a html site with multiple forms, using jQuery dialog UI for display and jQuery form plugin for ajax submission.
Form looks like this:
<form id="login_form" action="admin.php" method="post">
Username: <input type="text" name="username" id="username"/><br/>
Password: <input type="password" name="password" id="password"/>
</form>
...the form options look like this:
$('#login_form').dialog({
buttons:{
"Login": function(){
var options = {
success: function(data){
alert(data);
$(this).dialog("close");
$('#news_form').dialog("open");
},
timeout: 3000,
fail: function(data){
alert('fail');
},
clearForm: true
};
// bind form using 'ajaxForm'
$('#news_form').ajaxSubmit(options);
},
"Exit": function(){
$(this).dialog("close");
}
}
});
...and the php file is a simple:
<?php
$data = 'Herro!';
echo $data;
?>
Problem is that on success the form returns the html page that was the source of the submit and not 'Herro!' like i anticipated. So what am i doing wrong?
Both the admin.html and the admin.php files are in the same dir.
Also the web is run locally via xampp, but i tried to put it on a web server as well with no improvements.
FINAL EDIT: the problem was in fact because I was calling a different form object in the DOM to submit the data, a form that doesn't have the action property set. Thanks to everyone for a quick solution.
Change $('#news_form').ajaxSubmit(options); to $('#login_form').ajaxSubmit(options);
Try wrapping the result in a JSON object(in the php file) and on the java script end you can now decode this JSON object using any standard json javascript library(you can download one here: http://www.JSON.org/json2.js).
Then you the below code
admin.php:
<?php
$data = json_encode('Herro!');
echo $data;
?>
Then in your html(javascript) you can make this little adjustment:
<script>
var result; //adjustment 1
$('#login_form').dialog({
buttons:{
"Login": function(){
var options = {
success: function(data){
result = JSON.parse(data); //adjustment 2
alert(result); //adjustment 3
$(this).dialog("close");
$('#news_form').dialog("open");
},
timeout: 3000,
fail: function(data){
alert('fail');
},
clearForm: true
};
// bind form using 'ajaxForm'
$('#news_form').ajaxSubmit(options);
},
"Exit": function(){
$(this).dialog("close");
}
}
});
</script>
remeber to reference the json2.js file you downloaded in your page. Let me know if this helps you.

image upload with ajax and php

I want to use ajax to upload image.
In this module:
On clicking browse and selecting image, it will be uploaded and displayed over file field.
After adding title and description, and clicking on the button, that image will be displayed below and upper image field will be blank
You can't upload files through AJAX. You need to work with IFRAMEs or a Flash-Based uploader.
Actualy you can upload images with the ajax function in Jquery in atleast the lates version of chrome.
HTML:
<form action="/" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="image"/>
<button type="submit">
</form>
JS:
$("form").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
return false;
});
This script will send a post request with the created file data to the current page through Ajax. You can change the destination obviously through changing the url parameter.
Try to use JQuery plugin for uploading an image.
May be http://www.uploadify.com/
This will give an idea how to do it.
Assuming you have a handle on the server side.. here is a small function and example on how to implement the 'iframe hack' in javascript.
html
<form name="image-upload">
<input type="file" name="image" /></br>
<button type="submit" name="upload">Upload</button>
<div id="upload-results"></div>
</form>
javascript
var fileUpload = function(form /* HTMLElement */, action /* Form Action URL */, callback /* Callback function */) {
/* vars */
var atribs = {
"target": "upload_iframe",
"action": action,
"method": "post",
"enctype": "multipart/form-data",
"encoding": "multipart/form-data"
}, iframe;
/* iframe listener */
var ilistener = function() {
var results;
listener.remove(this, 'load', ilistener);
if( 'contentDocument' in this ) {
results = this.contentDocument.body.innerHTML;
} else if ( 'contentWindow' in this ) {
results = this.contentWindow.document.body.innerHTML;
} else if ( 'document' in this ) {
results = this.document.body.innerHTML;
} else {
throw "i'm dead jim :/";
}
callback.apply(this,[results]); // call the callback, passing the results
this.parentNode.removeChild(this); // remove the iframe
};
/* create the iframe */
form.parentNode.appendChild(FragBuilder([{"tagName": "iframe","id": "upload_iframe","name": "upload_iframe","style": {"height": "0","width": "0","border": "0"}}]));
/* collect the iframe back */
iframe = By.id('upload_iframe');
/* set the form properties */
for( var attr in atribs ) {
if( attr in form ) {
form[attr] = atribs[attr];
}
}
/* attach the event listener to the iframe */
listener.add(iframe, 'load', ilistener);
/* submitting the form */
form.submit();
};
// get the form, and the results area
var form = document.forms['image-upload'], results = By.id('upload-results');
// listen for the form submit, capture it, and run the iframe upload.
listener.add(form, 'submit', function(e) {
e.preventDefault();
results.innerHTML = 'Uploading...';
fileUpload(this, 'server.php' /* really anything */, function(data) {
console.log(data);
results.innerHTML = "Uploaded!";
});
});
Please note: for simplicity purposes I have used the following utilities.
https://github.com/rlemon/FragBuilder.js DocumentFragment builder from JSON input.
https://gist.github.com/2172100 event listener, and By utility functions.
*these are both easily removed.

Categories