I have been using this to process a form via AJAX and jQuery
$("#uploadBtn").click(function()
{
var formData = new FormData($('form')[0]); //--FormData here, problem line
$.ajax({
url: 'resources/ajax/ajax_upload_video.php',
type: 'POST',
xhr: function()
{
xhr = $.ajaxSettings.xhr();
if (xhr.upload)
{
xhr.upload.addEventListener('progress', progressHandlingFunction, false);
}
return xhr;
},
success: function(msg)
{
log(msg);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
});
It has been working fine. I added a second form on the page (Search on top, uploader on bottom)
I understand the $('form')[0] will grab the first form on the page, so naturally I changed my javascript to $('form')[1]. When I do a console.log on it, it is the correct form.
When I hit the upload button, but my php file says nothing was posted. For simplicity sake, my php file is this:
<?php
var_dump($_POST);
?>
I get just an empty array. I even gave the form I want an ID and called it this way $('#uploadForm').
I have 1 multi-select FILE input, a hidden field and a text input field.
What am I doing wrong with the FormData object?
One side not, I've been developing this page locally using WAMP and just moved it to our CentOS server that is online. Could this be a PHP setting that isn't the same as my local environment? I can't think of what PHP setting would have to do with POST
Upload Form
<form id="videoUploadForm" method="post" enctype="multipart/form-data" class="upload-form modal-edit-form">
<div class="modal-body">
<p>
<div align="center" id="fileSelect">
<input type="hidden" value="video" name="mediaType" id="mediaType" />
<input type="hidden" value="<?php echo $_GET['reelId']; ?>" name="reelId" id="reelId" />
<input type="file" name="videos[]" id="videos" accept="video/mp4" multiple />
</div>
<br>
</p>
<p>
<div id="dropbox">
<ul class="hide" id="filelist">
</ul>
<div align="center" id="nofiles">Select some file to begin</div>
</div><br>
</p>
<p>
<hr>
<label>Search Tags <small>[at least two tags separate by comma]</small></label>
<input type="text" class="span5" name="searchTags" id="searchTags" disabled />
</p>
<hr>
<p align="center">
<img src="resources/img/loader.gif" class="hide" id="loader" />
<button type="button" class="btn btn-info" name="uploadBtn" id="uploadBtn" disabled><i class="icon-circle-arrow-up icon-white"></i> Begin Upload</button>
<div id="successfulUpload" class="alert alert-success hide">
<b>The videos have been successfully uploaded.</b><br/>
</div>
</p>
</div>
</form>
Try accessing it this way:
var form = document.getElementById('form-id');
var formData = new FormData(form);
From this page on FormData.
Related
I have a module where a user can upload a profile picture. I want to do several things when a user uploads a picture to there profile, but I am trying to take it in steps, the first step being getting the picture saved and uploaded to the server. Right now, the user can select there picture just fine, after the user has chosen there picture, it gives a little notice that the picture is uploading. I don't know if something is supposed to show after uploading or if it is just supposed to go away (I joined a friend in getting this site done, the module was already here; I'm trying to get the functionality finished up and working).
This is what it looks like:
I have noticed though, that if you click save nothing seems to happen. Like the save button is not set up correctly or something.
I suspect that the the issue of the pictures not being uploaded is either because of the "Uploading..." text or the save button not working. I have tried to debug by echoing out if $_FILES is getting the picture that I am trying to upload, but the module does not reload to allow me to see if $_FILES is getting anything (it's not making it to the if loop of what happens after the save button has been clicked.
Here is the code for the module itself:
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
</div>
<div class="modal-body">
<center>
<h3>Edit Profile Picture</h3>
<img src="images/default.png" name="aboutme" width="140" height="140" border="0" class="img-circle"></a></br></br></br></br></br></br></br>
</center>
<div class="modal-body">
<form id="cropimage" method="post" enctype="multipart/form-data" action="upload_pic/change_pic.php">
<strong>Upload Image:</strong> <br><br>
<input type="file" name="profile-pic" id="profile-pic" />
<input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1" />
<input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="" />
<input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="" />
<input type="hidden" name="hdn-x2-axis" value="" id="hdn-x2-axis" />
<input type="hidden" name="hdn-y2-axis" value="" id="hdn-y2-axis" />
<input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="" />
<input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="" />
<input type="hidden" name="action" value="" id="action" />
<input type="hidden" name="image_name" value="" id="image_name" />
<div id='preview-profile-pic'></div>
<div id="thumbs" style="padding:5px; width:600p"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_crop" class="btn btn-primary">Save</button>
</div>
</div></br>
<div class="container">
<div id="profile_pic_modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Upload Profile Picture</h3>
</div>
<div class="modal-body">
<form id="cropimage" method="post" enctype="multipart/form-data" action="upload_and_change.php">
<strong>Upload Image:</strong> <br><br>
<input type="file" name="profile-pic" id="profile-pic" />
<input type="hidden" name="hdn-profile-id" id="hdn-profile-id" value="1" />
<input type="hidden" name="hdn-x1-axis" id="hdn-x1-axis" value="" />
<input type="hidden" name="hdn-y1-axis" id="hdn-y1-axis" value="" />
<input type="hidden" name="hdn-x2-axis" value="" id="hdn-y2-axis" />
<input type="hidden" name="hdn-thumb-width" id="hdn-thumb-width" value="" />
<input type="hidden" name="hdn-thumb-height" id="hdn-thumb-height" value="" />
<input type="hidden" name="action" value="" id="action" />
<input type="hidden" name="image_name" value="" id="image_name" />
<div id='preview-profile-pic'></div>
<div id="thumbs" style="padding:5px; width:600p"></div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="save_crop" class="btn btn-primary" name="save">Save</button>
</div>
</div>
</div>
</div>
</div>
</br></br></br></br></br>
</div>
</div>
</div>
This is the function.js where I think the "Uploading..." is coming from:
jQuery(document).ready(function(){
/* When click on change profile pic */
jQuery('#change-profile-pic').on('click', function(e){
jQuery('#profile_pic_modal').modal({show:true});
});
jQuery('#profile-pic').on('change', function() {
jQuery("#preview-profile-pic").html('');
jQuery("#preview-profile-pic").html('Uploading....');
jQuery("#cropimage").ajaxForm(
{
target: '#preview-profile-pic',
success: function() {
jQuery('img#photo').imgAreaSelect({
aspectRatio: '1:1',
onSelectEnd: getSizes,
});
jQuery('#image_name').val(jQuery('#photo').attr('file-name'));
}
}).submit();
});
/* handle functionality when click crop button */
jQuery('#save_crop').on('click', function(e){
e.preventDefault();
params = {
targetUrl: '/upload_pic/change_pic.php?action=save',
action: 'save',
x_axis: jQuery('#hdn-x1-axis').val(),
y_axis : jQuery('#hdn-y1-axis').val(),
x2_axis: jQuery('#hdn-x2-axis').val(),
y2_axis : jQuery('#hdn-y2-axis').val(),
thumb_width : jQuery('#hdn-thumb-width').val(),
thumb_height:jQuery('#hdn-thumb-height').val()
};
saveCropImage(params);
});
/* Function to get images size */
function getSizes(img, obj){
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
if(thumb_width > 0) {
jQuery('#hdn-x1-axis').val(x_axis);
jQuery('#hdn-y1-axis').val(y_axis);
jQuery('#hdn-x2-axis').val(x2_axis);
jQuery('#hdn-y2-axis').val(y2_axis);
jQuery('#hdn-thumb-width').val(thumb_width);
jQuery('#hdn-thumb-height').val(thumb_height);
} else {
alert("Please select portion..!");
}
}
/* Function to save crop images */
function saveCropImage(params) {
jQuery.ajax({
url: params['targetUrl'],
cache: false,
dataType: "html",
data: {
action: params['action'],
id: jQuery('#hdn-profile-id').val(),
t: 'ajax',
w1:params['thumb_width'],
x1:params['x_axis'],
h1:params['thumb_height'],
y1:params['y_axis'],
x2:params['x2_axis'],
y2:params['y2_axis'],
image_name :jQuery('#image_name').val()
},
type: 'Post',
success: function (response) {
jQuery('#profile_pic_modal').modal('hide');
jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
jQuery("#profile_picture").attr('src', response);
jQuery("#preview-profile-pic").html('');
jQuery("#profile-pic").val();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
}
});
}
});
I have attempted to comment out the line jQuery("#preview-profile-pic").html('Uploading....'); but that does not seem to remove the "Uploading..." text and the picture still does not upload.
If someone could help me figure out why the module is not working correctly, I would greatly appreciate it. If there is an easier way to get the functionality I am looking for, please let me know.
From my analysis, I did ran the code and found lots of more errors but the following are the key issues to address first.
Your code uses an assigned header file, as seen here ,that carries all the snippets for CDN jquery files. if you would have opened your console while its 'Uploading...' you would have noticed an error like one in this pic
First impression is that no jQuery.form.js file was found which is responsible for this function. If you go further and confirm that it is correctly loaded, Use this function here to check its loading:
(function() {
var startingTime = new Date().getTime();
// Load the script
var script = document.createElement("SCRIPT");
script.src = 'dist_files/jquery.form.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
// Poll for jQuery to come into existance
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 20);
}
};
// Start polling...
checkReady(function($) {
$(function() {
var endingTime = new Date().getTime();
var tookTime = endingTime - startingTime;
window.alert("jQuery.form is loaded, after " + tookTime + " milliseconds!");
});
});
})();
if you would use this function to check if its correctly loaded, after then, if it loads, your next victim is your jQuery, this is because of compatibility issues, the jQuery.form.js version used requires a jQuery of 1.5.x or higher.
Secondly,you have to check that you don't have any conflict with your imports, if in your project you used a version like
Assuming you had used jQuery in your other functions before the profile thing came in, which in this case came with its imports.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
then definitely you'll not have jQuery functioning, meaning, jQuery will no work, and also, the same guy needs to call jQuery.form.js, now you see you'll come back to the same error. so harmonize your imports and delete any duplicates in .js imports and also .css files(although there is no css conflict currently but just for your info)
Once you clean the imports(I advise you use CDN if you are developing with good network connection) clear your browser caches and redo the upload with 'inspect element option in your browser' Do this:
Right click an empty space on browser
select 'inspect element'
switch in the inspector to 'Console' and you'll be able to see the errors if any.
your end result should work and get something of this sort:
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.
I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>
I have some HTML and Ajax set up so that if you click a certain image (the reply-quote class below), it initiates some Ajax to echo HTML elsewhere on the page.
As shown below, the HTML file contains the same block of divs multiple times. My problem is that, if a user clicks the image, how can I make Ajax show the HTML (within show-reply div) for that specific block and not all of them?
<!-- BLOCK ONE -->
<div class="style1">
<div class="style2">
<img src="image.png" class="reply-quote" />
<div class="style3">
<div class="style4">
<div id="show-reply"></div>
<div class="reply-box">
<form class="reply-container no-margin" method="POST" action="">
<textarea class="reply-field" name="new_comment" placeholder="Write a reply..."></textarea>
<button name="submit" class="btn" type="submit">Post</button>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- BLOCK TWO -->
<div class="style1">
<div class="style2">
<img src="image.png" class="reply-quote" />
<div class="style3">
<div class="style4">
<div id="show-reply"></div>
<div class="reply-box">
<form class="reply-container no-margin" method="POST" action="">
<textarea class="reply-field" name="new_comment" placeholder="Write a reply..."></textarea>
<button name="submit" class="btn" type="submit">Post</button>
</form>
</div>
</div>
</div>
</div>
</div>
Here's the JQuery I have right now:
$(document).ready(function() {
$(".reply-quote").click(function() {
$.ajax({
url: 'assets/misc/show_reply.php', // this file simply echoes back the HTML to the `show-reply` div
type: "POST",
data: {post_id: $(this).attr('id')},
success: function(data) {
$("#show-reply").append(data); // this is where the problem lies
}
});
});
});
To my understanding, I have to somehow implement $(this), parent(), find(), etc. instead of the current line I'm using ($("#show-reply").append(data);). The question is, what should that line be so that if I click the image, it only shows the HTML for that specific block?
Please help!
First: ID should be unique in a document, use class attribute instead for show-reply and other elements where id is repeated
<div class="show-reply"></div>
then you need to find the show-reply next to the clicked reply-quote image
$(document).ready(function() {
$(".reply-quote").click(function() {
var $reply = $(this);
$.ajax({
url: 'assets/misc/show_reply.php', // this file simply echoes back the HTML to the `show-reply` div
type: "POST",
data: {post_id: $(this).attr('id')},
success: function(data) {
$reply.closest('.comment-container').find(".show-reply").append(data);
}
});
});
});
try this
$("div").click(function(e) {
if($(e.target).is('.reply-quote')){
e.preventDefault();
return;
}
alert("work ");
});
You should change the id="show-reply" to class="show-reply" in html, and then in JS change $("#show-reply").append(data); to $(this).parent(".show-reply").append(data);
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">