Chrome Issue - AJAX Inserted File Input not uploading file - php

I have a form where a file input field is being dynamically inserted via AJAX. Essentially what I'm doing is displaying a form, the user picks which template they want, and I pull in some extra form fields depending on the template they chose. One of them has a file input. The problem is when I go to submit the form with the added file input, the PHP $_FILES array is giving me an error code of 4, meaning there wasn't a file uploaded. Does anyone know what I need to do to get these files uploading?
I'm guessing I have to do something on the JS side to re-evaluate which form fields I'm sending, but I haven't been able to find anything. (and yes I'm using proper enctype on the form.)
Update : This is only happening on Safari/Chrome. I read elsewhere that they think this is a security feature of webkit browsers. I don't know if there is a fix for this..
Thanks all

It's not clear if you are using a $.post or form.submit(). If you are using form.submit() there might be something else going wrong.
Otherwise, in order to send files to the server via AJAX you need to use the Form Data object.
This MDN Page Using FormDataObjects has good examples on how to use it. Note that if you use jQuery you need to set processData and contentType to false. See Below (taken from the MDN page).
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "stash.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
});

if you send the form via a form.submit() method, there should be no problem sending files. Are you trying to send your files via ajax ? if so you cant directy. use an iframe, flash or read the file datas with a FileReader and send raw datas in your ajax request.

Related

Send Data From my website to an external page of another website using PHP

all my problem is that I wanna send data from my website to this website's page :
http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw
how I can do this ? and is it possible ? cuz as I have seen this website forms validation's all in javascript and dunno how to handle it ?
thanks.
This is how you can do that, just make a testPosting.html file,
Create your form using all the inputs that are required to send.
See the screenshot for the posted fields.
This data is posted when i submitted the form after filling it.
Now as you can see 14 fields are posted, so you need to make 13 inputs and 1 textarea.
use click function for the button of submit e.g
$('#buttonID').click(function(e){
e.PreventDefault();
//store values of inputs in a variable
var data = {
FirstName = $('#FirstName').val(); // you can more better then that if you know how
//Add the rest of the data
};
});
then you can use jQuery Ajax to send data.
$.ajax({
url: "http://www.womo.com.au/external-review.php?id=MDAxMTcyNjcw",
data:data, //this data will be the variable that you create in which all the forms inputs datas are stored.
type: "POST"
}).done(function(result) {
//do stuff if some result has returned
});
i just gave the rough idea.
Oh you must use this line in script on top of you JS scrips
jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
My code is not perfect but you get the idea what i am trying to say, you might can start from here, and do stuff of your own..

Use $_FILES on a page called by .ajax

I have two .php pages that I'm working with. Index.php has a file upload form that posts back to index.php. I can access the $_FILES no problem on index.php after submitting the form.
My issue is that I want (after the form submit and the page loads) to use .ajax (jQuery) to call another .php file so that file can open and process some of the rows and return the results to ajax. The ajax then displays the results and recursively calls itself to process the next batch of rows.
Basically I want to process (put in the DB etc) the csv in chunks and display it for the user in between chunks. Im doing it this way because the files are 400,000+ rows and the user doesnt want to wait the 10+ min for them all to be processed.
I dont want to move this file (save it) because I just need to process it and throw it away and if a user closes the page while its processing the file wont be thrown away. I could cron script it but I dont want to.
What I would really like to do is pass the (single) $_FILES through .ajax OR Save it in a $_POST or $_SESSION to use on the second page.
Is there any hope for my cause?
Heres the ajax code if that helps:
function processCSV(startIndex, length)
{
$.ajax({
url: "ajax-targets/process-csv.php",
dataType: "json",
type: "POST",
data: { startIndex: startIndex, length: length },
timeout: 60000, // 1000 = 1 sec
success: function(data) {
// JQuery to display the rows from the CSV
var newStart = startIndex+length;
if(newStart <= data['csvNumRows']) {
processCSV(newStart, length);
}
}
});
}
processCSV(1, 2);
});
P.S. I did try this Passing $_FILES or $_POST to a new page with PHP but its not working for me :( SOS.
To clarify: My problem is that I want to access a $_FILE on a page that is called by ajax. The file is uploaded on index.php, the form as action="#" so it posts to index.php. After the post index.php sends an ajax call to process-csv.php and I need the file to be accessible on process-csv.php. I do not want to move the file because I don't want to have to clean up old files.
So I don't think you ever say your problem, but I'm guessing your problem is you are not able to ajax a file. The reason for this is because you can't actually get the file information in javascript because it's a security risk. There is a bunch of ways you can do this though. You can either use flash or an iframe to fake a ajax like file upload.
jQuery iframe file upload
I actually like the flash version though cause it gives you the ability to upload multiple files at once and still offers everything the iframe does as well as many more events.
http://code.google.com/p/swfupload/
With uploadComplete you can use to then put your processing code you have and uploadStart to use to pass a marker to say to link this session up with the file added to the database.
Also in your processing make sure you are always passing how far you have gotten, so it doesn't keep returning back the same rows each time.
I hope that helps.
Just construct the data rows in JavaScript then:
data: {
startIndex: startIndex,
length: length,
rows: variableWithRows.slice(startIndex, startIndex + length)
},
Inside PHP, all rows would be in $_POST['rows'] as array data.

Upload file using jQuery and Ajax

I have a form that I am sending to the server using jQuery $.post method. I am sending several fields with something like:
var myName = "Pedro";
var myDescription = "Description of Pedro";
$.post("~/insert_user", { name: myName, description: myDescription }, function(data){
alert("Successfully inserted " + data.name + " in DB");
}, "json");
This works great, as I take the values in insert_user.php and treat and insert the in the data base.
What if I need to add a field to my form to let the user upload an image?
How would I do that in my $.post call and how would I get it in the PHP?
I am using Symfony2.0, by the way, just in case it changes something. But the important part is how to add a file typed field to the ajax call.
Thanks in advance.
Pedro
You will find it would be a lot easier to use a pre built jquery plugin. My favourite is uploadify http://uploadify.com.
Its simple and easy to use and it will save you a lot of time trying to figure out a method of your own <>
$.post is the same as the code block bellow. In order for you to do what you need to you need to change it to use this atleast and then things will become simpler. So start by changing the $.post to this
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Then add a parameter in the ajax block contentType : "multipart/form-data" or try mimeType (cant remember so clearly) and in the data : $("#form").serialize(), that should work.
please tell me if it didn't work
--NEW EDIT LOL-- Excuse my blind coding, you may need to test this
I did a bit more research and came across this. You need to build this array and add it to the data in your ajax block
var files = new FormData($('#fileinputid'));
jQuery.each($('#fileinputid')[0].files, function(i, file) {
files.append(i, file);
});
If what i read was accurate you should be able to pass that array with the rest of the ajax data. Although i am not completely sure how to add it to the serialized data.
Please test this and let me know. if it doesn't work ill do a full javascript script test for you and then post it here
This tutorial might help: Nettuts+: Uploading Files With AJAX
Make iframe and put form in it, submit the form and voila. Or you can use one of these AJAX File upload scripts
I finally used this:
http://malsup.com/jquery/form/#faq
It just works great for what I need.
Thank you guys for your help.

How to send data from javascript to php

$('myBtn').on("click",function(){
var parent= $(this).parent();// will give you the Parent Object of the button, that has been clicked
});
I need to send var parent to php so it knows where to display the html data (in the correct are div/class, how would i do this.
The short answer is that "You can't".
Communication between the browser (where your JS is running) and the server (where the PHP is running) is handled via HTTP. If you want to send a JavaScript object then you have to serialise it to a string and deserialise it at the other end. There is no sane way to represent an HTMLElementNode (or a jQuery object that wraps on) in that process (not least because PHP doesn't usually represent HTML in a DOM and when it does it won't be the same DOM instance as the browser is using).
Usually in this type of situation, you would request some data from PHP (possibly using one of jQuery's ajax methods) and then use JavaScript to turn it into DOM elements and insert it into the document.
Try JSON and Ajax (XMLHttpRequest) as the "client to server" mechanism
JavaScript is evaluated on client-side, when PHP is server side. You don't have trivial way to do it.
If the html data is not already generated, you would have to make a new request to the server, preferrably by the jQuery $.get function, then pass the output (again via jQuery) to the parent element.
Please use Jquery and use $.ajax for this purpose
$.ajax({
type: "POST",
url: "yourPHPPage.php",
data: "parentvar="+parent,
//parent is a javascript variable
success: function(msg){
//Message received from server,
// if you would write some code in echo there, like echo "hello";
// you would get that in msg.
}
});
to access this variable on php, use $_POST["parentvar"];
You can also send multiple values by concatinating them with & operator.
Like data:"parentVar="+parent+"&name=atif&age=23"; etc
Please let me know if further help needed.
Further help on
http://api.jquery.com/jQuery.ajax/
As far as I know, you can't pass a DOM object directly to the server -- there's too much information stored for it to be practical. You could send the HTML of the object though.
Here's an example that sends the HTML to the server. You would process it, but we just echo it back.
http://jsfiddle.net/hLD4F/
Try clicking on any of the buttons, and it will send a request. In PHP you could access this information via $_POST['html'].

Update form fields after form submitted

I have no problem with submitting form data through AJAX, and display all that data in a separate div.
But how do I update the form itself with some new info based on server response?
In my case I have:
a form with many inputs, including a group of checkboxes
data from form is collected (with JQuery serialize) and sent to php script through Ajax.
I need to set a specific color for text near a selected checkbox.
I need to set that color not on client side, but based on server side script.
Please explain the correct logical process when need to update a form based on initial form data.
Server side, you can send back a json encoded variable like so.
echo json_encode( array('text_color', 'green') );
Then, on the client side, you can access this variable in the callback function.
$.ajax({
url: 'ajax/test.html',
dataType: 'json',
data: $('yourform').serialize(),
success: function(data) {
var color = data.text_color;
$('yourElement').css('color', color);
}
});
Alternatively you could send back a class and add that class to the element.
If you are using jQuery, you would send the data via AJAX (post/get) and then you would get the response from server script in plain text / json / xml format (your choice). In this case, if you need to return only color code, you can use plain text format. When you get the response, you can manipulate the data.
$.post("test.php", $('#form').serialize(),
function(returned_data_from_server_script) {
$('some dom for color').css('color', returned_data_from_server_script);
});

Categories