Caius
Caius

Reputation: 193

Upload image via Ajax

Well the thing is there is already a edited form with a lot of fields but all the save and validate goes trough ajax. They asked me now to put a file upload , i tough that just will be set a input and get it on back , but since all goes trough ajax i cant.

I don't want to change all the function and go trough a submit if it's not necessary. I looked for some uploaders of file trough ajax but all of them are type drag and drop and i don't like them because y only need a simple file. And the ones that i found that looked simple where in flash...

Is there any simple script that allows me to upload a simple file trough ajax without need of change the type of submitting the fields.

Thank's in advance mates ;)

//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();

$.ajax({
    url: "/save_changes",
    dataType: "json",
    data: data,
    method:"POST",
    success: function (response) {
        if(!response.status){
            toastr_error(response.desc);
            $( "#submit_confirm" ).prop( "disabled", false );
            $("#"+response.camp).focus();
        }else{
            toastr_success(response.desc);

        }
    }
});

}

Upvotes: 0

Views: 166

Answers (2)

vartika
vartika

Reputation: 494

You can achieve this in simpler way using "ajaxSubmit". Include jquery.form.js on your page and submit your form.

 $(form).ajaxSubmit({
            url: url,
            type: "POST",           
            success: function (response) {
              // do what you need with response
        });

It sends all form data including file on server then you can handle these data in regular manner.

Upvotes: 1

B.Kevin
B.Kevin

Reputation: 250

client side

$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST",             // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false,       // The content type used when sending data to the server.
cache: false,             // To unable request pages to be cached
processData:false,        // To send DOMDocument or non processed data file it is set to false
success: function(data)   // A function to be called if request succeeds
{

});

server side

$sourcePath = $_FILES['file']['tmp_name'];       // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ;    // Moving Uploaded file

Upvotes: 1

Related Questions