PHP image upload through Ajax serialize() - php

File upload through ajax serialize():
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
</div>
</form>
AJAX CODE using serialize():
$('#save11').click(function(){
$.ajax({
type : "POST",
url : "page/add-journal.php",
data :$('#addform').serialize(),
success : function(data)
{
alert(data);
window.location.href="home-page.php";
}
});
});
Here PHP code:
<?php
include '../dbConnection.php';
$tmp=$_FILES['file']['tmp_name'];
$serverpath="upload/".$_FILES['file']['name'];
$file=$_FILES['file']['name'];
move_uploaded_file($tmp,$serverpath);
$sql="insert into journal set file='".$file."'";
$query=mysql_query($sql);
?>
Only give me solution using serialize() only. If not so give me best solution.

I have made some changes in your code.. you can use below code for uploading images using ajax
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
<input type="submit" name="save" value="save" />
</div>
</form>
<script>
$('#addform').submit(function(e) {
e.preventDefault();
var data = new FormData(this); // <-- 'this' is your form element
$.ajax({
url: 'page/add-journal.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
alert(data);
window.location.href = "home-page.php";
}
});
});
</script>
Note:
you haven't provided that how you submit your form, so I have put a submit button
You are using mysql functions, but they are officially deprecated now from php, you should use mysqli or PDO.

Form id in HTML is addform and in ajax you are using #addformkey. You will have to change the id at one place. I doubt this will work though.
only give me solution using serialize () only
https://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>: $( "input, textarea, select" ).serialize();
I doubt it can serialize a file.

Related

handle posted formData object with files and other inputs in php

I need to handle inputs from form post and I have no idea, how to do it in php, because when I write for example $_POST["header"], it var_dumps null.
I am creating formData object and inserting all inputs from form. Then posting it with ajax.
Can you please help me? I need to handle "header", "content", "password" and files.
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>
$("#uploadFiles").submit(function(event){
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
console.log(Array.from(formDataObj));
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: {
formDataObj: formDataObj
},
dataType: 'json',
contentType: false,
processData: false,
success: function(results){
}, error: function(){
}
});
});
In uploadNews.php I have this:
exit(json_encode(var_dump($_POST["header"])));
It always returns "Undefined index: header", same as content or count($_FILES["file"]["name"])
All I want is to get somehow to posted values.. Thank you very much
You just to pass the actual formDataObj variable via your $.ajax. This is not the correct syntax to pass FormData via ajax => formDataObj: formDataObj
A FormData itself is an object which stores your data so what you are doing is making another object on top of it when you pass it via data
You can now var_dump(header) or var_dump($_FILES["file"]["name"]) to see everything coming to your PHP file.
Live Demo: (Change you jQuery code to this below and it will just work fine)
$("#uploadFiles").submit(function(event) {
event.preventDefault();
var formDataObj = new FormData(),
header = $("#newsHeader").val(),
content = $("#content").val(),
password = $("#password").val();
formDataObj.append("header", header);
formDataObj.append("content", content);
formDataObj.append("password", password);
$.each($("#files")[0].files, function(i, file) {
formDataObj.append('file', file);
});
$("#uploadFilesSubmit").html("<div class='buttonSubmitIcon'><i class='fas fa-sync'></i></div>");
$.ajax({
method: "POST",
url: "uploadNews.php",
data: formDataObj, //just pass the form Data object.
dataType: 'json',
contentType: false,
processData: false,
success: function(results) {
},
error: function() {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" enctype="multipart/form-data" id="uploadFiles">
<label for="newsHeader" id="headerLabel">Nadpis</label>
<input type="text" name="newsHeader" id="newsHeader">
<label for="content" id="contentLabel">Text novinky</label>
<textarea name="content" id="content"></textarea>
<label for="files" id="filesLabel">Fotky</label>
<input type="file" name="files" id="files" accept="image/jpeg" multiple>
<label for="password" id="passwordLabel">Heslo pro upload</label>
<input type="text" name="password" id="password">
<button type='submit' id='uploadFilesSubmit'>NAHRÁT</button>
</form>

Sending images from form with AJAX

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.

Using 'this' with formData to only post from current form

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.

To make html form run two actions

Is it possible to submit two forms using a single submit button?
like if a user clicks submit on a form, that form runs test.php and form.php with the variables still intact?
If not then is it possible when the user clicks submit on a form it runs only test.php then test.php runs form.php with the variables still intact.
I don't think this is possible on a normal form submission, but you can try to utilize an AJAX request on both forms on demand. (This is just an example, not tested, just a guide or an idea.).
<!-- forms -->
<fieldset><legend>Form #1</legend>
<form id="form_1" action="test.php">
<label>Username: <input type="text" name="username" /></label>
<label>Password: <input type="text" name="password" /></label>
</form>
</fieldset>
<br/>
<fieldset><legend>Form #2</legend>
<form id="form_2" action="form.php">
<label>Firstname: <input type="text" name="fname" /></label>
<label>Lastname: <input type="text" name="lname" /></label>
</form>
</fieldset>
<button id="submit" type="button">Submit</button>
<!-- the forms is just an example -->
<!-- it would be weird to separate such fields in to different forms -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').on('click', function(){
$.ajax({
url: $('#form_1').attr('action'),
data: $('#form_1').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
$.ajax({
url: $('#form_2').attr('action'),
data: $('#form_2').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
});
});
</script>
The form can have only one action, if you want to pass data to a different page then you can do that by calling an ajax function..

Send data to PHP with ajax using formdata

SOLUTION: I had to drop the sumbmit button and use a regular button. The rest of this code works. I also dropped the HTML form.
I'm trying to send an image + some text to my php script with ajax using formdata.
This is what i got:
$ajax_uploadImage = function (form)
{
var data = new FormData();
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);
$.ajax({
url: '../php/upload_image.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('something');
}
});
}
The form in the function parameters is a normal html form, here is the form in html:
<form enctype="multipart/form-data" id="upload_image">
<label for="title">Title:</label>
<input type="text" id="title" name="title" />
<br />
<label for="comment">Comment:</label>
<input type="text" id="comment" name="comment" />
<br />
<label for="image">Image:</label>
<input type="file" id="image" name="image" />
<br />
<input type="submit" value="Upload picture" name="submit">
<hr />
</form>
The alert in success never triggers, can anyone help?
EDIT: Adding the PHP, even though it doesn't do anything:
<?php echo 'something'; ?>
Right now you are storing a jQuery object in the FormData which cannot work. Use the values of those elements instead. In case of the file input you need to use the File object in the files property of the DOM element:
data.append('title', form.find('#title').val());
data.append('comment', form.find('#comment').val());
data.append('image', form.find('#image').prop('files')[0]);
Try adding form action like:
<form enctype="multipart/form-data" id="upload_image" action="upload_image.php">

Categories