I am trying to upload a file using jquery. Here's the form:
<form id="upload_data" class="project" enctype="multipart/form-data" method="POST">
<select id="project_id" name="project_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="file" id="data" name="data" />
<input type="hidden" name="user_id" id="user_id" value="12" required>
<button type="submit" id="ajax" class="btn btn-primary">Submit</button>
</form>
Here's the jquery part:
$('#upload_data').submit( function( e ) {
var form = $('form');
var formData = new FormData();
$.each($(':input', form ), function(i, fileds){
formData.append($(fileds).attr('name'), $(fileds).val());
});
$.each($('input[type=file]',form )[0].files, function (i, file) {
formData.append(file.name, file);
});
$.ajax( {
url: '../controllers/process.php',
type: 'POST',
enctype: 'multipart/form-data',
data: formData,
processData: false,
contentType: false,
success: function(data)
{
alert(data);
},
error: function(data)
{
alert(data);
}
} );
});
The problem is that I am getting empty post values in process.php:
if (isset($_POST['project_id']) AND isset($_POST['user_id'])){
//process
}else{
echo 'No post data';
}
It always return 'No post data' (But in console, I can see that data has been posted but it's not the case in server.). What am I missing here?
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
jQuery AJAX submit form
and
How to send FormData objects with Ajax-requests in jQuery?
If you are appending a file to formData
formData.append(file.name, file);
You need to use this version of the method as per MDN docs
formData.append(name, value, filename);
That will allow you to present a fieldname, file data, and file name
Also you might consider just submiting the form itself without the need for using formData
Thank you for all your reply. The problem was about max_upload_filesize and post_max_size. I increased the values for these options and now it's working. Thanks.
Related
I've been working on a form where you upload an image and a comment. I got it working in PHP, but now I'd like to do it in AJAX. The reason I'd like to do it in AJAX is because the user has to type all of their text again when the upload fails (due to conditions like: fields can't be empty or the aspect ratio of the image is off). However whatever I do, I fail to do it in AJAX.
I've tried to do it in FormData, with $.post and with $.ajax. I've also looked up a lot of guides, and other posts about this, but nothing seems to work for me.
Below you will find the HTML form, the jQuery AJAX call and the PHP code from the PHP page the AJAX call calls.
HTML FORM
<form action="uploadpost.php" id="postForm" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="postImage">Upload image</label>
<input type="file" id="fileToUpload" name="postImage" class="form-control">
</div>
<div class="form-group">
<label for="description">Write a caption</label>
<textarea name="description" id="postMessage" cols="30" rows="5" class="form-control"></textarea>
</div>
<input type="submit" id="postSubmit" value="Create post" name="upload_image" class="btn btn-primary">
</form>
The AJAX call
<script type="text/javascript">
$(document).ready(function(){
$("#postSubmit").on("click", function(e){
var formData = new FormData($("#postForm"));
//var message = $("#postMessage").val();
$.ajax({
url: "ajax/postUpload.php",
type: "POST",
data: formData,
contentType: "multipart/form-data",
cache: false,
processData:false,
success: function(data)
{
console.log(data);
}
});
e.preventDefault();
});
});
The PHP code in ajax/postUpload.php
<?php
include_once("../classes/Post.class.php");
$post = new Post();
var_dump($_FILES);
if(!empty($_POST)){
$file_tmp_name = $_FILES['postImage']['tmp_name'];
$result = $post->createPost($file_tmp_name);
if($result){
$uploadCheck['check'] = "success";
}else{
$uploadCheck['check'] = "error";
}
header('Content-Type: application/json');
echo json_encode($uploadCheck);
}
?>
Output from console.log(data) on ajax call return
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=0)</i>
<i><font color='#888a85'>empty</font></i>
</pre>
The problem is that I can't send the image nor the message over to that PHP page, which doesn't allow me to do createPost().
var formData = new FormData($("#postForm"));
The argument to FormData should be a DOM form object, not a jQuery object.
new FormData($("#postForm")[0])
Setting the content type manually:
contentType: "multipart/form-data",
… will fail to set the boundary data in it. Say:
contentType: false,
… so that jQuery won't try to set it at all and the XHR object will generate it from the FormData object.
I have a file upload form:
<form class="uploadFile" name="uploadFile" method="post" action="process/uploadBuildImages.php" enctype="multipart/form-data">
<div class="uploadImageButton">Upload Image</div>
<input type="file" id="fileUpload" class="fileUpload" name="picture">
</form>
I am posting this form via ajax and formData like so:
var form = $('.uploadFile')[0];
var formData = new FormData(form);
The issue is that I have this same form output up to 4 times on the same page. I am making a CMS with blog posts and the upload image form is in each of the blog posts.
How can I target and post only from the currently posted form? I know its along the lines of using 'this.form etc but always struggle with .next / closest etc. Will look more into it soon.
If I only have one instance of this form on the page then it works fine, but otherwise I get a no file chosen error.
Thanks!
For reference, full JS:
$(document).ready(function(){
$('.uploadFile').submit(function(){
var form = $('.uploadFile')[0];
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "process/uploadBuildImages.php",
data: formData,
dataType: "json",
contentType: false,
processData: false,
success: function(response){
// actions
}
}
});
}):
And there is at least 4 of the same div structures on the page which follow the same format as:
<div class="blogtest" id="'.$postID.'">
<div class="text">
<div class="postoverlay"></div>
<div class="buildtext" id="'.$postTextID.'">'.$convertedtext.'</div>
<form class="uploadFile" name="uploadFile" style="display:$showUploadForm;" method="post" action="process/uploadBuildImages.php" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<div class="uploadImageButton">Upload Image</div>
<input type="file" id="fileUpload" class="fileUpload" name="picture">
</form>
<form class="updatepost" id="'.$postContentID.'" method="post">
<div class="editor">
<textarea name="muffin" id="'.$ckEID.'" class="ckeditor">'.$textFiltered.'</textarea>
</div>
</form>
</div>
</div>
Echoing the same diagnosis I have made in my comments, you lack context in your function call — your code basically submits the form data in all forms with the class .uploadFile regardless of which one is submitted:
var form = $('.uploadFile')[0]; // Problematic line
You should use $(this) to give it context upon the firing of the submit context, so that you only submit the form data from the form where the event originated from, and not all forms with the class instead. Therefore, you substitute:
var form = $('uploadFile')[0];
with:
// Alternative 1
var form = $(this)[0];
// Alternative 2
var form = this;
In other words:
$(document).ready(function(){
$('.uploadFile').submit(function(){
var form = this; // Fixed line
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "process/uploadBuildImages.php",
data: formData,
dataType: "json",
contentType: false,
processData: false,
success: function(response){
// actions
}
}
});
});
You can learn more what $(this) does in jQuery here and here.
I've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.
I'm passing form data to a PHP script for processing via JS(jQuery.ajax()).
Problem is - I can't figure out a way to access individual form control values inside PHP( e.g. $_POST['zipcode'] ).
Instead I can only access the data with $_POST['form'], which is an entire form represented as one long string( e.g. string(89)"color=red&color=blue&zipcode=12345..." ).
How can I access individual values of form data inside PHP script passed from a HTML form via JS?
index.php(form)
<form id="myform">
<select name="color" id="color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<input type="text" id="zipcode" name="zipcode" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
index.php(JS)
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'html',
url : 'PHPscript.php',
data: {form : $('#myform').serialize()}
}).done(function(data) {
var myJSONresult = data;
alert(myJSONresult);
});
});
PHPscript
<?php
if(isset($_POST["form"])){
$form = $_POST["form"];
$myzipcode = $_POST['zipcode']; // won't work; will be null or empty
echo json_encode($form);
}
?>
EDIT: The zipcode field:
$("#zipcode").focus(function(){
if(this.value == "zipcode"){
$(this).val("");
}
}).blur(function(){
if(this.value == ""){
$(this).val("zipcode");
}
});
You need to use serializeArray() on the form data instead of serialize. That will submit as an array.
data: $('#myform').serializeArray()
HTML
<input type="hidden" name="action" value="submit" />
PHP
if(isset($_POST["action"]))
{
//code
}
Add dataType: 'json' to your ajax handler and further modify your code like this:
$.ajax({
type: 'POST',
dataType: 'json', // changed to json
url : 'PHPscript.php',
data: {form : $('#myform').serialize()},
success : function(data){ // added success handler
var myJSONresult = data;
alert(myJSONresult.yourFieldName);
}
});
set traditional to true like
$.ajax({
traditional:true,
//your rest of the ajax code
});
on the php end you are getting the value fine the problem is at the form serialization end
I have got this html/php in my index.php
if (isset($_POST['UploadMSub'])) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)) {
if ($fileP_error===0) {
if ($fileP_size<=2097152) {
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
$_SESSION['fileP']=$fileP;
$_SESSION['fileP_name']=$fileP_name;
$_SESSION['fileP_tmp']=$fileP_tmp;
$_SESSION['fileP_size']=$fileP_size;
$_SESSION['fileP_error']=$fileP_error;
$_SESSION['fileP_extension']=$fileP_extension;
$_SESSION['fileP_new_name']=$fileP_new_name;
}
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" type="text" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
And this ajax
$(".UploadMSub").click(function() {
var text=$(".Text").val();
var file=$("#Nameupload").val();
$.ajax({
type: "GET",
url: '../connect.php',
data: "Text=" + text+"&&file="+file,
success: function(data)
{
alert(data);
}
});
return false;
});
connect.php
if (isset($_GET['Text'])) {
$Text=htmlspecialchars($_GET['Text'],ENT_QUOTES);
$file=htmlspecialchars($_GET['file'],ENT_QUOTES);
echo $Text." ".$_SESSION['fileP_new_name'];
}
But when i submit form it returns(alerts)
"Undefine index ''fileP_new_name'"
Is there any other way of getting all information about file in my connect.php?
The problem is,
When you hit the submit button, the form doesn't get submitted, which means none of your session variables are set when you hit the submit button. Instead jQuery script runs straight away when you hit the submit button, and that's why you're getting this error,
Undefine index: fileP_new_name
From your question,
Is there any other way of getting all information about file in my connect.php?
So the solution is as follows. You have to change few things in your code, such as:
Add a name attribute in your <textarea> element, like this:
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
Instead of returning false from your jQuery script, use preventDefault() method to prevent your form from being submitted in the first place, like this:
$(".UploadMSub").click(function(event){
event.preventDefault();
// your code
});
If you're uploading file through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object. FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.
Set the following options, processData: false and contentType: false in your AJAX request. Refer the documentation to know what these do.
So your code should be like this:
HTML:
<form method="post" enctype="multipart/form-data" class='SubmUploadFu'>
<textarea maxlength="400" name="new_post" class='Text' placeholder="New post"></textarea>
<input type="file" name="Upload_f" style="display:none;" id="Nameupload">
<label for="Nameupload" class='LabelCamerUp'>
<img src="../img/camera.png" class='CamerUp'>
</label>
<input type="submit" class="UploadMSub">
</form>
jQuery/AJAX:
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('form')[0]);
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data){
alert(data);
}
});
});
And on connect.php, process your form data like this:
<?php
if(is_uploaded_file($_FILES['Upload_f']['tmp_name']) && isset($_POST['new_post'])){
// both file and text input is submitted
$new_post = $_POST['new_post'];
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
}
// your code
//echo $fileP_new_name;
}
?>