Upload file using jQuery and Ajax - php

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.

Related

Sending data from database using Jquery Ajax JSON

I restarted my old project and have a question regarding old code. 3 years ago I had this type of code to sent data from database to JavaScript arrays using php:
echo json_encode($result_array);
and JQuery:
$.ajax({
type : "POST",
url : "poli.php",
success : function(data) {
poli_owner = $.parseJSON(data);
},
async : false
});
to populate JavaScript array.
My question is - is it still good code or not recommended anymore. If the code is not OK what code is better to use to take data from database and populate JavaScript array using php and JQuery? Thank you.
Yes, it is still good. All the web is still using Ajax and JSON.
Depending on your use case, you can load your data via a separate Ajax request, or just make your server-side language generate data for JS and include it in the page source code.

Saving a Javascript Variable in a new file

I have a Javascript variable that is an object with keys and arrays (shortened version shown below). I scripted in HTML a form so that a users with access (after they login) can delete, add, or alter any of the Keys for their genealogy. What I need to know is how to take this new, altered variable and save it to the server as say, userNameGenealogy.js so that another page can use it. I have done some searching, but do not know if what I need is only PHP oriented, or if I will need to look into AJAX or JSON as well.
var genealogy = {};
genealogy["Johnson"] = {
"Ron": new Array(
{"nickname":"Ronny","dob":"06/20/88"},
{"nickname":"Ronald","dob":"03/15/54"}),
"Scott": new Array(
{"nickname":"Scotty","dob":"01/21/42"})
};
This is just a short snippet, but I'd prefer not to have to change the format of the Javascript, as the rest of the site is coded to work with it as is. Any help / point in the right direction would be greatly appreciated.
You need to use ajax for that. For example with ajax() and pass data parameter to it. Then you need to handle that in PHP script in which you have to read $_POST (in case below) parse it as you like it, save to file and echo response.
JavaScript code:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});

Chrome Issue - AJAX Inserted File Input not uploading file

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.

Getting a value from a variable , send to php to process and add that value to mysql database?

i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.

JQuery MySql update

im trying to adapt this little snippet:
$("#checkbox_id").change(function(){
/* CODE HERE */
});
I have a series of checkboxes that are dynamically generated and their id's are always like "hug3443" were "hug" is the column in the DB and "3443" is the unique id for each row.
My objective would be that every time the checkbox changes state to update it own state in the DB.
Can it be accomplished with jQuery?
Thank you.
I just found a script for this stuff and thought to post it here as I was checking this page a while ago until I finally came across to this script. Tested it and worked like a charm and I have inserted it in my coding library. Enjoy, folks.
http://www.jooria.com/Tutorials/ajax-20/jquery-live-checkbox-inputs-with-animation-effects-158/
Yes. Use live events to attach the change event handler to your checkboxes (so that dynamically added checkboxes will be handled also). Then simply do a AJAX request inside the event handler passing your script the new state and the name/id of the checkbox (you can then "parse" the id and column name in the script).
Not without a server side script that would deal with the data changes.
jQuery is a client side javascript framework and doesn't have direct access to mysql, which is a server side daemon.
Have a look into pairing jQuery with php and mysql.
Code in javascript you write with the use of jQuery is executed on the client-side in a browser. A solution is from your script to make a call to a server page that will execute a MySQL update . For example like this.
$("#checkbox_id").change(function(){
$.ajax({
type: "POST",
url: "/page-that/makes/update.php",
data: {param1:value1}
});
});
You should write some server-side code for managing database (php, ruby, whatever).
You should create something like API, which means, that server-side script needs to get some variables, which sended to it from clients (id's of rows, name and value of columns for example).
And after that you should write your jQuery frontend script, which will request server-side script for managing database tables. For requests you can use AJAX technology, something like this:
$.ajax({
url: 'http://somesite.com/path/to/server/side/script',
type : 'POST',
success: function (data, textStatus) {
alert('yahoo! we get some data from server!' + data);
}
});
You can get the value of the id of the checkbox using javascript you can then split the name into the field name and id value. For this example I've added a - into id to give a seperator
(I think you may need to use the click event rather than change, think change may only work for drop down menus)
$("#checkbox_id").click(function(){
var checkbox_id = $(this).attr("id");
var id_bits = checkbox_id.split("-");
// this would split hug-3443 into hug and 3443 setting id_bits[0] = hug and id_bits[1] = 3443
$.post("update,php",
{
row: id_bits[0],
id: id_bits[1]
}
);
});

Categories