I\'m trying to use jquery and PHP to upload an image like so:
HTML
Note that $.post and $.ajax are very similar (except by default $.ajax uses type=get, you have to change it to type=post). You have more control over stuff with $.ajax, but $.post is more stream-lined -- think of $.post as a short-hand way of doing an AJAX POST. However, because $.ajax is often more structured than $.post, it is a great way for those new to AJAX to experiment with adding modifiers, such dataType:JSON
, contentType
, or even async:false
.
Ajax code would like this:
$('#photo-img').change(function(){
var file = this.files[0];
//console.log(file);
name = file.name;
size = file.size;
type = file.type;
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'f_name=' +name+ '&f_size=' +size+ '&f_type=' +type,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that any data coming back from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv"
. To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot);
with this:
$('#myDiv').html(whatIgot);
Your DIV now contains the data echoed from the PHP file.
On the PHP side, it basically looks like this:
';
$r .= '
- File Name: ' .$file_name.'
- File Size: ' .$file_size.'
- File Type: ' .$file_type.'
';
echo $r;
See this example for ideas on how it works.
Note that the above examples use jQuery, and therefore require this reference in the tags of your page: