upload.php not being called in AJAX request - php

I select an image, write something and then click submit. Once I click submit it posts to the DB, shows progress bar of upload successfully BUT the upload.php file is never called.
Question: What is wrong with my code, that is preventing the upload.php file from being called in the action="".
It was working at one point in time but I can't remember what changes I made for it.
UPDATED SCRIPT:
$('#feed_form').submit(function(e) {
var data = new FormData(this);
var url = $(this).attr("action");
if($('#file12').val()) {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
type: "POST",
url: "scripts/universal/upload.php",
data: data,
processData: false,
contentType: false,
success: function() {
$("#success_post").slideDown();
setTimeout(function() {
$('#success_post').slideUp();
}, 3000);
},
uploadProgress: function (event, position, total, percentComplete){
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete +' %</div>')
},
resetForm: true
});
return false;
}
});
<form name="feed_form" id="feed_form" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function() {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick">Post</button>
</form>
PHP:
if(!empty($_FILES)) {
if(is_uploaded_file($_FILES['file12']['tmp_name'])) {
$sourcePath = $_FILES['file12']['tmp_name'];
$targetPath = "images/uploads/".$_FILES['file12']['name'];
move_uploaded_file($sourcePath,$targetPath);
shell_exec("ffmpeg -f mp4 -i images/uploads/".$_FILES['file12']['name']." -ss 00:00:5.000 -vframes 1 images/uploads/".basename($_FILES['file12']['name'], ".mp4").".png");
//This line does not affect the code, it works perfectly fine when I try it with some different JS
}
}

You've not specified the url in $.ajax(). Maybe that's the only problem
Below is the corrected code, try it and let me know if it worked or not
<script type="text/javascript">
$(document).ready(function () {
$('#feed_form').submit(function (e) {
var url = $(this).attr("action");
var data = new FormData(this);
if ($('#file12').val()) {
if (!$("#btnSubmitFormClick").val()) {
$("#show_error_message").innerHTML = "Please write something before clicking submit";
} else {
$("#progress-div").show("slow");
e.preventDefault();
$.ajax({
url: url,
data: data,
cache: false,
processData: false,
contentType: false,
success: function () {
$("#success_post").show();
},
uploadProgress: function (event, position, total, percentComplete) {
$("#progress-bar").width(percentComplete + '%');
$("#progress-bar").html('<div id="progress-status">' + percentComplete + ' %</div>')
},
resetForm: true
});
return false;
}
}
});
$("#btnSubmitFormClick").click(function () {
document.getElementById("close_status_modal").click();
});
$("#feed_form").submit(function (e) {
$.ajax({
type: "POST",
url: "scripts/universal/post.php",
data: $("#feed_form").serialize(), // serializes the form's elements.
success: function (data) {
$('#textarea_writing').val('');
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
</script>
<form name="feed_form" id="feed_form" action="upload.php" method="post" enctype="multipart/form-data">
<textarea class="list-group-item p-x-md" id="textarea_writing" name="textarea_writing" style="resize:none;padding:5px;width:100%;" placeholder="What's going on....."></textarea>
<script type="text/javascript">
var textarea = document.getElementById("textarea_writing");
textarea.oninput = function () {
textarea.style.height = "";
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
};
</script>
<span id="show_error_message"></span>
<br>
<label class="custom-file" style="width:100%;">
<input type="file" name="file12" id="file12" class="custom-file-input" onchange="setfilename(this.value);" accept=".jpg, .jpeg, .gif, .png, .mp4" required>
<span class="custom-file-control">Select photo, video or gif...</span>
</label>
<br><br>
<button type="submit" id="btnSubmitFormClick" style="display:none;">Post</button>
</form>

I ended up using the following code to solve my problem:
function _(el) {
return document.getElementById(el);
}
function uploadFile() {
var file = _("file12").files[0];
var formdata = new FormData();
formdata.append("file12", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.open("POST", "scripts/universal/upload.php");
ajax.send(formdata);
}
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$("#progress-div").show();
_("progressBar").value = Math.round(percent);
}
function completeHandler(event) {
_("progressBar").value = 0;
$("#progress-div").hide();
}

Related

Send php variable with jQuery AJAX

I´m using an image uploading jQuery script and a short php script. They´re both included inside of the mainsite.php file.
Everything is working fine expect the transfer of the php variable $usr_id.
How can I send the php variable $usr_id via AJAX to my server sided script correctly?
php code
$user = JFactory::getUser();
$usr_id = $user->get('id');
This is my try:
jQuery(function ($) {
$(document).ready(function () {
$("#but_upload").click(function () {
var fd = new FormData();
var files = $('#file')[0].files;
var userid = <?php echo $usr_id ?>;
if (files.length > 0) {
fd.append('file', files[0]);
fd.append('userid', userid);
$.ajax({
url: 'imageupload/upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function (response) {
if (response != 0) {
$("#img").attr("src", response);
} else {
alert('file not uploaded');
}
},
});
} else {
alert("Please select a file.");
}
});
});
})
Edit: this is the form field code
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>

Run AJAX on every foreach php [duplicate]

I am trying to send data from a form to a database. Here is the form I am using:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.php)?
Basic usage of .ajax would look something like this:
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
jQuery:
// Variable to hold request
var request;
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
Note: Since jQuery 1.8, .success(), .error() and .complete() are deprecated in favor of .done(), .fail() and .always().
Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready() handler (or use the $() shorthand).
Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();
PHP (that is, form.php):
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;
Note: Always sanitize posted data, to prevent injections and other malicious code.
You could also use the shorthand .post in place of .ajax in the above JavaScript code:
$.post('/form.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.
To make an Ajax request using jQuery you can do this by the following code.
HTML:
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>
JavaScript:
Method 1
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "test.php",
type: "post",
data: values ,
success: function (response) {
// You will get response from your PHP page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
Method 2
/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
var ajaxRequest;
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get from elements values */
var values = $(this).serialize();
/* Send the data using post and put the results in a div. */
/* I am not aborting the previous request, because it's an
asynchronous request, meaning once it's sent it's out
there. But in case you want to abort it you can do it
by abort(). jQuery Ajax methods return an XMLHttpRequest
object, so you can just use abort(). */
ajaxRequest= $.ajax({
url: "test.php",
type: "post",
data: values
});
/* Request can be aborted by ajaxRequest.abort() */
ajaxRequest.done(function (response, textStatus, jqXHR){
// Show successfully for submit message
$("#result").html('Submitted successfully');
});
/* On failure of request this function will be called */
ajaxRequest.fail(function (){
// Show error
$("#result").html('There is error while submit');
});
The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.
MDN: abort() . If the request has been sent already, this method will abort the request.
So we have successfully send an Ajax request, and now it's time to grab data to server.
PHP
As we make a POST request in an Ajax call (type: "post"), we can now grab data using either $_REQUEST or $_POST:
$bar = $_POST['bar']
You can also see what you get in the POST request by simply either. BTW, make sure that $_POST is set. Otherwise you will get an error.
var_dump($_POST);
// Or
print_r($_POST);
And you are inserting a value into the database. Make sure you are sensitizing or escaping All requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.
And if you want to return any data back to the page, you can do it by just echoing that data like below.
// 1. Without JSON
echo "Hello, this is one"
// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));
And then you can get it like:
ajaxRequest.done(function (response){
alert(response);
});
There are a couple of shorthand methods. You can use the below code. It does the same work.
var ajaxRequest= $.post("test.php", values, function(data) {
alert(data);
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.
First of all, create two files, for example form.php and process.php.
We will first create a form which will be then submitted using the jQuery .ajax() method. The rest will be explained in the comments.
form.php
<form method="post" name="postForm">
<ul>
<li>
<label>Name</label>
<input type="text" name="name" id="name" placeholder="Bruce Wayne">
<span class="throw_error"></span>
<span id="success"></span>
</li>
</ul>
<input type="submit" value="Send" />
</form>
Validate the form using jQuery client-side validation and pass the data to process.php.
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
//Validate fields if required using jQuery
var postForm = { //Fetch form data
'name' : $('input[name=name]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php', //Your form processing file URL
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
}
else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
Now we will take a look at process.php
$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`
/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
$errors['name'] = 'Name cannot be blank';
}
if (!empty($errors)) { //If errors in validation
$form_data['success'] = false;
$form_data['errors'] = $errors;
}
else { //If not, process the form, and return true on success
$form_data['success'] = true;
$form_data['posted'] = 'Data Was Posted Successfully';
}
//Return the data back to form.php
echo json_encode($form_data);
The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip.
You can use serialize. Below is an example.
$("#submit_btn").click(function(){
$('.error_status').html();
if($("form#frm_message_board").valid())
{
$.ajax({
type: "POST",
url: "<?php echo site_url('message_board/add');?>",
data: $('#frm_message_board').serialize(),
success: function(msg) {
var msg = $.parseJSON(msg);
if(msg.success=='yes')
{
return true;
}
else
{
alert('Server error');
return false;
}
}
});
}
return false;
});
HTML:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" class="inputs" name="bar" type="text" value="" />
<input type="submit" value="Send" onclick="submitform(); return false;" />
</form>
JavaScript:
function submitform()
{
var inputs = document.getElementsByClassName("inputs");
var formdata = new FormData();
for(var i=0; i<inputs.length; i++)
{
formdata.append(inputs[i].name, inputs[i].value);
}
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest;
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
}
xmlhttp.open("POST", "insert.php");
xmlhttp.send(formdata);
}
I use the way shown below. It submits everything like files.
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url = $(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
If you want to send data using jQuery Ajax then there is no need of form tag and submit button
Example:
<script>
$(document).ready(function () {
$("#btnSend").click(function () {
$.ajax({
url: 'process.php',
type: 'POST',
data: {bar: $("#bar").val()},
success: function (result) {
alert('success');
}
});
});
});
</script>
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
<button id="desc" name="desc" value="desc" style="display:none;">desc</button>
<button id="asc" name="asc" value="asc">asc</button>
<input type='hidden' id='check' value=''/>
</form>
<div id="demoajax"></div>
<script>
numbers = '';
$('#form_content button').click(function(){
$('#form_content button').toggle();
numbers = this.id;
function_two(numbers);
});
function function_two(numbers){
if (numbers === '')
{
$('#check').val("asc");
}
else
{
$('#check').val(numbers);
}
//alert(sort_var);
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#form_content').serialize(),
success: function(data){
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
$(document).ready(function_two());
</script>
In your php file enter:
$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";
and in your js file send an ajax with the data object
var data = {
bar : 'bar value',
time: calculatedTimeStamp,
hash: calculatedHash,
uid: userID,
sid: sessionID,
iid: itemID
};
$.ajax({
method: 'POST',
crossDomain: true,
dataType: 'json',
crossOrigin: true,
async: true,
contentType: 'application/json',
data: data,
headers: {
'Access-Control-Allow-Methods': '*',
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
"Access-Control-Allow-Origin": "*",
"Control-Allow-Origin": "*",
"cache-control": "no-cache",
'Content-Type': 'application/json'
},
url: 'https://yoururl.com/somephpfile.php',
success: function(response){
console.log("Respond was: ", response);
},
error: function (request, status, error) {
console.log("There was an error: ", request.responseText);
}
})
or keep it as is with the form-submit. You need this only, if you want to send a modified request with calculated additional content and not only some form-data, which is entered by the client. For example a hash, a timestamp, a userid, a sessionid and the like.
Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:
var formData = formData;
$.ajax({
type: "POST",
url: url,
async: false,
data: formData, // Only input
processData: false,
contentType: false,
xhr: function ()
{
$("#load_consulting").show();
var xhr = new window.XMLHttpRequest();
// Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100;
$('#addLoad .progress-bar').css('width', percentComplete + '%');
}
}, false);
// Download progress
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
beforeSend: function (xhr) {
qyuraLoader.startLoader();
},
success: function (response, textStatus, jqXHR) {
qyuraLoader.stopLoader();
try {
$("#load_consulting").hide();
var data = $.parseJSON(response);
if (data.status == 0)
{
if (data.isAlive)
{
$('#addLoad .progress-bar').css('width', '00%');
console.log(data.errors);
$.each(data.errors, function (index, value) {
if (typeof data.custom == 'undefined') {
$('#err_' + index).html(value);
}
else
{
$('#err_' + index).addClass('error');
if (index == 'TopError')
{
$('#er_' + index).html(value);
}
else {
$('#er_TopError').append('<p>' + value + '</p>');
}
}
});
if (data.errors.TopError) {
$('#er_TopError').show();
$('#er_TopError').html(data.errors.TopError);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
else
{
$('#headLogin').html(data.loginMod);
}
} else {
//document.getElementById("setData").reset();
$('#myModal').modal('hide');
$('#successTop').show();
$('#successTop').html(data.msg);
if (data.msg != '' && data.msg != "undefined") {
bootbox.alert({closeButton: false, message: data.msg, callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
} else {
bootbox.alert({closeButton: false, message: "Success", callback: function () {
if (data.url) {
window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
} else {
location.reload(true);
}
}});
}
}
}
catch (e) {
if (e) {
$('#er_TopError').show();
$('#er_TopError').html(e);
setTimeout(function () {
$('#er_TopError').hide(5000);
$('#er_TopError').html('');
}, 5000);
}
}
}
});
I am using this simple one line code for years without a problem (it requires jQuery):
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>
Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.
<form id="form_id">
...
<input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>
Since the introduction of the Fetch API there really is no reason any more to do this with jQuery Ajax or XMLHttpRequests. To POST form data to a PHP-script in vanilla JavaScript you can do the following:
async function postData() {
try {
const res = await fetch('../php/contact.php', {
method: 'POST',
body: new FormData(document.getElementById('form'))
})
if (!res.ok) throw new Error('Network response was not ok.');
} catch (err) {
console.log(err)
}
}
<form id="form" action="javascript:postData()">
<input id="name" name="name" placeholder="Name" type="text" required>
<input type="submit" value="Submit">
</form>
Here is a very basic example of a PHP-script that takes the data and sends an email:
<?php
header('Content-type: text/html; charset=utf-8');
if (isset($_POST['name'])) {
$name = $_POST['name'];
}
$to = "test#example.com";
$subject = "New name submitted";
$body = "You received the following name: $name";
mail($to, $subject, $body);
Please check this. It is the complete Ajax request code.
$('#foo').submit(function(event) {
// Get the form data
// There are many ways to get this data using jQuery (you
// can use the class or id also)
var formData = $('#foo').serialize();
var url = 'URL of the request';
// Process the form.
$.ajax({
type : 'POST', // Define the type of HTTP verb we want to use
url : 'url/', // The URL where we want to POST
data : formData, // Our data object
dataType : 'json', // What type of data do we expect back.
beforeSend : function() {
// This will run before sending an Ajax request.
// Do whatever activity you want, like show loaded.
},
success:function(response){
var obj = eval(response);
if(obj)
{
if(obj.error==0){
alert('success');
}
else{
alert('error');
}
}
},
complete : function() {
// This will run after sending an Ajax complete
},
error:function (xhr, ajaxOptions, thrownError){
alert('error occured');
// If any error occurs in request
}
});
// Stop the form from submitting the normal way
// and refreshing the page
event.preventDefault();
});
Pure JS
In pure JS it will be much simpler
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
foo.onsubmit = e=> {
e.preventDefault();
fetch(foo.action,{method:'post', body: new FormData(foo)});
}
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
This is a very good article that contains everything that you need to know about jQuery form submission.
Article summary:
Simple HTML Form Submit
HTML:
<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>
JavaScript:
$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get the form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = $(this).serialize(); // Encode form elements for submission
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){ //
$("#server-results").html(response);
});
});
HTML Multipart/form-data Form Submit
To upload files to the server, we can use FormData interface available to XMLHttpRequest2, which constructs a FormData object and can be sent to server easily using the jQuery Ajax.
HTML:
<form action="path/to/server/script" method="post" id="my_form">
<label>Name</label>
<input type="text" name="name" />
<label>Email</label>
<input type="email" name="email" />
<label>Website</label>
<input type="url" name="website" />
<input type="file" name="my_file[]" /> <!-- File Field Added -->
<input type="submit" name="submit" value="Submit Form" />
<div id="server-results"><!-- For server results --></div>
</form>
JavaScript:
$("#my_form").submit(function(event){
event.preventDefault(); // Prevent default action
var post_url = $(this).attr("action"); // Get form action URL
var request_method = $(this).attr("method"); // Get form GET/POST method
var form_data = new FormData(this); // Creates new FormData object
$.ajax({
url : post_url,
type: request_method,
data : form_data,
contentType: false,
cache: false,
processData: false
}).done(function(response){ //
$("#server-results").html(response);
});
});
I hope this helps.
That's the code that fills a select option tag in HTML using ajax and XMLHttpRequest with the API is written in PHP and PDO
conn.php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$database = "db_event";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
category.php
<?php
include 'conn.php';
try {
$data = json_decode(file_get_contents("php://input"));
$stmt = $conn->prepare("SELECT * FROM events ");
http_response_code(200);
$stmt->execute();
header('Content-Type: application/json');
$arr=[];
while($value=$stmt->fetch(PDO::FETCH_ASSOC)){
array_push($arr,$value);
}
echo json_encode($arr);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
script.js
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
for (let i in data) {
$("#cars").append(
'<option value="' + data[i].category + '">' + data[i].category + '</option>'
)
}
}
};
xhttp.open("GET", "http://127.0.0.1:8000/category.php", true);
xhttp.send();
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<title>Document</title>
</head>
<body>
<label for="cars">Choose a Category:</label>
<select name="option" id="option">
</select>
<script src="script.js"></script>
</body>
</html>
I have one other idea.
Which the URL that of PHP files which provided the download file.
Then you have to fire the same URL via ajax and I checked this second request only gives the response after your first request complete the download file. So you can get the event of it.
It is working via ajax with the same second request.}

Can't upload multiple files with different extension?

Multiple file upload is not working if all files are not the same extension !! If I chose two png files , it works . But choosing two different file extensions (png,pdf) got empty array in $_FILES !
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > </script>
</head>
<body>
<form>
<input name="file[]" type="file" multiple/>
<input type="button" value="Upload" />
</form>
<progress></progress>
<script>
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
</script>
</body>
</html>
upload.php
<?php var_dump($_FILES); ?>
Result image
Hope to help you.
demo.php
<?php
if(isset($_FILES)&&!empty($_FILES)){
for($i=0;$i<count($_FILES);$i++){
echo "File ".($i+1)." is ".$_FILES["file-".$i]['name']."\n";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'demo.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
<body>
</html>
I think you can use following code :-
<button id="upload">Upload</button>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploads.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>

file upload and form data on single form using ajax

I have a html form with 2 input filed and a file upload form and i want to send these data to some index.php file using ajax what i did so far is
<form class="col-md-3" id="form" name="reg" method="post" action="index.php" enctype="multipart/form-data">
<label>Name</label>
<input type="text" name="name" class="form-control" id="name">
<label>Address</label>
<input type="text" name="address" class="form-control">
<div id="sugg">
</div>
<input type="file" name="file">
<input type="button" name="submit" class="btn-default" id="btn" value="submit">
</form>
jquery for send data using ajax is
$("#btn").click(function() {
$.ajax({
url: "index.php",
type: "POST",
data: new FormData($('form')[0]),
cache: false,
conentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
php file has just this
echo $_POST["name"];
but in my browser window i am undefined index
I found similar questions but all that doesn't solved my problem that's why i asking your help please help me to find my error
I am create below code according to my need and you can make changes according to your requirement:
when you click upload/select file button use this function :
$('input[type=file]').on('change', function(e){
e.preventDefault();
$this = $(this);
if($this.prop("files")){
if(setImagestoUpload(e, $this.prop("files"), $this.attr("name"))){
var reader = new FileReader();
reader.onload = function(e){
$('.brandLogo img').attr("src", e.target.result);
$this.parent().prev("img.imageSelection").attr("src", e.target.result);
};
reader.readAsDataURL(this.files[0]);
}
}
});
function setImagestoUpload(e, $file, name){
e.preventDefault();
var type = [];
var isSize = [];
$($file).each(function(i, v){
type[i] = isImage(v);
isSize[i] = isValidSize(2, v.size);
});
if($.inArray(false, type) === -1){
if($.inArray(false, isSize) === -1){
/*if(checkTotalFileInputs() > 1 && files.length>0){
$.each($file, function(ind, val){
files[name] = val;
});
files[name] = $file[0];
}else{
files = $file;
}*/
formData.append(name, $file[0]);
console.log(files);
return true;
}else{
alert("Error: Upload max size limit 2MB");
}
}else{
alert("Please select only image file format to upload !");
return false;
}
}
function isImage(file){
var type = file.type.split("/");
if(type[0] === "image"){
return true;
}else{
return false;
}
}
and when you submit form then use below function:
function fileAndFormSubmit(ev, $this, get, options){
var defaults = {
redirect : false,
redirectTo : "#",
redirectAfter : 5000
};
var settings = $.extend({}, defaults, options);
removeErrorAndSuccess();
var $form = $($this).parent('form');
/*var formData = new FormData();
if(files.length > 0){
$.each(files, function(key, val){
formData.append(key, val);
});
}*/
var doc = {
data : $form.serialize()
};
formData.append("doc", doc.data);
/*Call to ajax here*/
}

Ajax Upload image

Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something.
On submit doesn't do anything at all.
Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.
Here is JS.
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault()
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:$(this).serialize(),
cache:false
});
}));
and the HTMl with php.
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/>
<input type="submit" name="upload" value="Upload" />
<img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/>
</form>
first in your ajax call include success & error function and then check if it gives you error or what?
your code should be like this
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
HTML Code
<div class="rCol">
<div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
</div>
<div class="rCol" style="clear:both;">
<label > Upload Photo : </label>
<input type="file" id="file" name='file' onChange=" return submitForm();">
<input type="hidden" id="filecount" value='0'>
Here is Ajax Code:
function submitForm() {
var fcnt = $('#filecount').val();
var fname = $('#filename').val();
var imgclean = $('#file');
if(fcnt<=5)
{
data = new FormData();
data.append('file', $('#file')[0].files[0]);
var imgname = $('input[type=file]').val();
var size = $('#file')[0].files[0].size;
var ext = imgname.substr( (imgname.lastIndexOf('.') +1) );
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
{
if(size<=1000000)
{
$.ajax({
url: "<?php echo base_url() ?>/upload.php",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
{
fcnt = parseInt(fcnt)+1;
$('#filecount').val(fcnt);
var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
$('#prv').append(img);
if(fname!=='')
{
fname = fname+','+data;
}else
{
fname = data;
}
$('#filename').val(fname);
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
}
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('SORRY SIZE AND TYPE ISSUE');
}
});
return false;
}//end size
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
alert('Sorry File size exceeding from 1 Mb');
}
}//end FILETYPE
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
}
}//end filecount
else
{ imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('You Can not Upload more than 6 Photos');
}
}
Here is PHP code :
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
foreach ($_FILES as $key )
{
$name =time().$key['name'];
$path='local_cdn/'.$name;
$file_ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array(strtolower($file_ext), $filetype))
{
if($key['name']<1000000)
{
#move_uploaded_file($key['tmp_name'],$path);
echo $name;
}
else
{
echo "FILE_SIZE_ERROR";
}
}
else
{
echo "FILE_TYPE_ERROR";
}// Its simple code.Its not with proper validation.
Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion.
Ajax Part:
function removeit (arg) {
var id = arg;
// GET FILE VALUE
var fname = $('#filename').val();
var fcnt = $('#filecount').val();
// GET FILE VALUE
$('#img_'+id).remove();
$('#rmv_'+id).remove();
$('#img_'+id).css('display','none');
var dname = $('#name_'+id).val();
fcnt = parseInt(fcnt)-1;
$('#filecount').val(fcnt);
var fname = fname.replace(dname, "");
var fname = fname.replace(",,", "");
$('#filename').val(fname);
$.ajax({
url: 'delete.php',
type: 'POST',
data:{'name':dname},
success:function(a){
console.log(a);
}
});
}
Here is PHP part(delete.php):
$path='local_cdn/'.$_POST['name'];
if(#unlink($path))
{
echo "Success";
}
else
{
echo "Failed";
}
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
Image upload using ajax and check image format and upload max size
<form class='form-horizontal' method="POST" id='document_form' enctype="multipart/form-data">
<div class='optionBox1'>
<div class='row inviteInputWrap1 block1'>
<div class='col-3'>
<label class='col-form-label'>Name</label>
<input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
</div>
<div class='col-3'>
<label class='col-form-label'>File</label>
<input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
</div>
<div class='col-3'>
<span class='deleteInviteWrap1 remove1 d-none'>
<i class='fas fa-trash'></i>
</span>
</div>
</div>
<div class='row'>
<div class='col-8 pl-3 pb-4 mt-4'>
<span class='btn btn-info add1 pr-3'>+ Add More</span>
<button class='btn btn-primary'>Submit</button>
</div>
</div>
</div>
</form>
</div>
$.validator.setDefaults({
submitHandler: function (form)
{
$.ajax({
url : "action1.php",
type : "POST",
data : new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType:'json',
processData: false,
success: function(data)
{
if(data.status =='success')
{
swal("Document has been successfully uploaded!", {
icon: "success",
});
setTimeout(function(){
window.location.reload();
},1200);
}
else
{
swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
}
},
error:function(data)
{
swal ( "Ops!" , "error in document upload." , "error" );
}
});
}
});
$('#document_form').validate({
rules: {
"name[]": {
required: true
},
"file[]": {
required: true,
extension: "jpg,jpeg,png,pdf,doc",
filesize :2000000
}
},
messages: {
"name[]": {
required: "Please enter name"
},
"file[]": {
required: "Please enter file",
extension :'Please upload only jpg,jpeg,png,pdf,doc'
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.col-3').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than 2 MB');
$(document).on('change', '#photo', function() {
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
var url = './services/userProfile.php';
if (jQuery.inArray(image_extension, ['jpg', 'jpeg', 'png']) == -1) {
$('#msg').html('Invalid image file');
return false;
}
var form_data = new FormData();
form_data.append("file", property);
$.ajax({
url: url,
method: 'POST',
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$('#msg').html('Loading......');
},
success: function(data) {
const obj = JSON.parse(data);
$('.image').attr('src', 'upload/' + obj['data']);
$('#msg').html(obj['msg']);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" action="" method="post" enctype="multipart/form-data">
<img src="upload/imag.jpg" class="mx-auto img-fluid img-circle d-block image" alt="avatar">
<h6 class="mt-2">Upload a different photo</h6>
<label class="custom-file">
<input type="file" id="photo" name="profilePicture" class="custom-file-input">
<span class="custom-file-control">Choose file</span>
</label>
<span id="msg" style="color:red"></span>
</form>
Here is simple way using HTML5 and jQuery:
1) include two JS file
<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2) include CSS to have cool buttons
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3) create DIV or SPAN
<div class="demo" > </div>
4) write this code in your HTML page
$('.demo').ajaxupload({
url:'upload.php'
});
5) create you upload.php file to have PHP code to upload data.
You can download required JS file from here
Here is Example
Its too cool and too fast And easy too! :)

Categories