Sending a form with a jQuery file by ajax [duplicate] - javascript

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 3 years ago.
My goal is to create a form to send an image to the server through Ajax via jQuery.
I already asked the question here (Problem sending a form with a jquery file component by ajax), but it's been closed and it still doesn't work. From my question, I changed the sending function like this (according to this post: jQuery AJAX file upload PHP):
$( "#sendProfileImg").on('submit', function(e) {
e.preventDefault();
var file_data = $('#profileImgFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadImage.php',
data: form_data,
type: 'POST',
dataType: 'text',
contentType: false,
cache: false,
processData:false,
success: function( data ) {
console.log(data);
}
});
});
But the answer I get from my uploadImage.php file (which consist of just var_dump($_POST);) is the following:
array(0) {
}
Any advice?

Since your request only has the file you might want want to use the $_FILES variable instead of $_POST. Uploaded files can only accessed through the $_FILES variable.

Thank you very much everbody, the problem is solved.
I discovered 2 issues:
I have to use form_data.append. I didn't know this function and it wasn't on the tutorials I followed. Furthermore, I had to use this funtion for every field of the formular, not just the one with the file
$_POST return no information about the posted files. That's why I didn't get any return about the posted information.
Thanks again everybody

three things
use $_FILES instead $_POST please check this url
check if you have an updated browser(not all browsers are compatible with FormData)
check the browser compatibility here

Related

How to store a js value in php variable? [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I want to store the value of x in js variable into php variable on the same page.
Short answer is: you can not.
The reason for this: PHP is executed on the server side, and the response is sent to the browser, and (usually) generated as HTML. The javascript is rendered after this, so at this point, the PHP code no longer exists.
Long answer:
You can send a javascript variable to PHP using an XHR request (or more commonly known as an AJAX call). This will be a different request from the one that loads your initial page though. For more information see this: https://www.w3schools.com/Php/php_ajax_php.asp
you can use ajax or
add input hidden with this value and when submit form sent a value
i think in most cast ajax in best.
$.ajax({
url: 'url',
method: 'POST',
data: 'data',
cache: false,
success:function(data){
},
error: function(data){
}
}); // end ajax

Passing JQuery var to PHP using AJAX [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
I'm trying to pass 3 variables that look like this
var location = document.location.pathname;
var search = document.location.search;
var referrer = document.referrer;
Into a PHP file that I can eventually use to send emails, I have never used AJAX before but know that you could use it to achieve this.
Can anyone help me out? Thanks in advance.
A simple Ajax POST method can help you here. Here's an example.
$.ajax({
type: "POST",
url: "ajax.php",
data: {location: location, search: search, referrer: referrer},
success: function(response){
//do something
}
})//ajax end
Now in ajax.php, you can receive the values via $_POST.
PHP Receiving(ajax.php).
var_dump($_POST['location']);
You could do like this:
$.ajax({
type: "POST",
data: {'location': location,
'search': search,
'referrer': referrer
},
url: "Here the path to your php-file",
success: function (data) {
Here you could react on any
}
});
In the php file you receive those data by Post and can handle them.

.ajaxSubmit from the jquery.form.js not working with data option

I am using the plugin jquery.form.js and I want to programmatically submit a form and include a file with it. The code and options I have set up with work with $.ajax but not .ajaxSubmit. According to the jquery.form.js documentation you can pass any standard $.ajax options to .ajaxSubmit but I can't seem to get it to work. I'd like to use .ajaxSubmit if possible so I can utilize some of the other features it offers.
$(document).ready(function() {
$('#file-form').submit(function(event) {
event.preventDefault();
var form = $("<form style='display:none;' method='post' action='video_upload.php' enctype='multipart/form-data'></form>");
var fd = new FormData();
fd.append('uploadedfile', $('#file')[0].files[0]);
var options = {
url: 'video_upload.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
beforeSend: function(xhr){
alert('start');
},
success: function(data){
alert(data);
}
};
$.ajax(options);
//form.ajaxSubmit(options);
return false;
});
});
Running $.ajax(options) works but form.ajaxSubmit(options) doesn't. What am I missing?
Thanks!
If you check the source code of the method ajaxSubmit - http://malsup.github.io/jquery.form.js you can see that the property data of the options is serialised/deserialised and converted several times. So most likely the content really submitted will be quite different from what happens in .ajax call. Later on the ajaxSubmit collects the files from form and submits them differently.
Basically, for me the specifying data while submitting with ajaxSubmit goes against the concept of this plugin, which is described as "The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process." Idiomatic way of using ajaxSubmit would be applying this method for the form with controls.

Ajax form submit set enctype [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 9 years ago.
I have this Js/Ajax code:
<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#addsliderimage").submit(function(e){
e.preventDefault();
dataString=$("#addsliderimage").serialize();
$.ajax({
type: "POST",
url: "addsliderimage_go.php",
cache: false,
data: dataString,
success: function(res){
//$("#message").show();
$("#message").html(res);
$('#message').fadeIn('slow');
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
when the form is submitted, the page with the form on doesn't change the page is just submits the data to the URL in the ajax code.
i know this works as im using it on other forms however on this particular form im uploading images/files so i need a way to set the enctype to multipart/form-data
If you want to upload the files using AJAX you propably should use the well-known "hack", a simple iframe with a simple form that is submitted not by AJAX and catch the load event of that iframe so you can get the result of the upload.
For the part you have doubt in, well, since you prevent the default event when the "presubmit" (to name it some way) function ends nothing happens (you know, the default event return "true" after the submission), so you need to tell before the closure you're passing to submit function that it is needed to be submitted, but you gotta handle whether it is being submitted twice or not.

Unable to upload file using AJAX

I am trying to upload a file through AJAX. I have searched over a lot but found examples using form submit only, but I can not use form submit. I have tried several examples but nothing reaches my server. When I tried this link, it worked but again it was through a form submission.
Here is the piece of code relevant to the context
JS Code
function _upload(filedata) {
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
}
$("#cpc-uploadBtn").click(function (evt) {
var data;
data = new FormData();
data.append('file', $('#cpc-upload')[0].files[0]);
_upload(data);
});
HTML Part
<input id="cpc-upload" name="file" type="file" />
<button id="cpc-uploadBtn" type="button">Upload</button>
Edit
Is there any other way to do this without using form submit and formdata?
Assuming that you are using Safari/FireFox (only those support FormData), you need to modify your $.ajax call:
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
Seeting contentType option to false will force jQuery not to add a Content-Type header for you (otherwise the boundary string will be missing from it). Also the processData flag must be set to false so jQuery will not try to convert your FormData into a string.
Now if you know that your clients are using HTML5 you should try using new JavaScript File API - check following articles:
Working with files in JavaScript, Part 1: The Basics
Working with files in JavaScript, Part 2: FileReader
Working with files in JavaScript, Part 3: Progress events and errors
Working with files in JavaScript, Part 4: Object URLs
Working with files in JavaScript, Part 5: Blobs
In all other cases you are forced to use custom plugins, for example:
Uploadify
jQuery Form Plugin
I suppose currently FormData objects are only supported in Safari/Firefox, it has not been adopted by most of the browsers yet.
I recently struggled a lot finding ajax file uploader for asp.net and I am currently using this one in my project:
https://github.com/valums/file-uploader
there is a small alternative if you want to use
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here

Categories