Reputation: 1364
I am new to Ajax and I'm trying to pass multiple variables to my PHP file but it's not really working. Basically the problem is that when I pass multiple variables, it stops working. I explain it in detail below.
Here's the snippet of my ajax code. I'm using this to upload a file:
var mdata = new FormData();
mdata.append('image_data', $(this)[0].files[0]);
var id = $id //$id is passed inside my function. Just assigning it but not necessary
jQuery.ajax({
type: "POST", // HTTP POST
processData: false,
contentType: false,
url: "includes/ul.php", //Ajax Calls here
data: mdata, //Form variables
dataType: 'json',
The above code snippet works. As you can see I'm only passing mdata
.
Now, the problem occurs when I try to pass multiple data. The upload stops working. I tried to send an email of my $_POST
and I get an empty array. Below is the code that I tried which is not working:
data: {mdata: mdata, "prodID":id} //See how I pass multiple variables now
Here's my PHP Code. Basically everything works when I pass just mdata
as shown in the first code snippet. However with the multiple variables it doesn't work(i.e my $_POST) doesn't get the value and even the upload does not work then:
<?php
$fullSize = "../prod/full_size/";
$thumb = "../prod/thumb/";
$_thumb = "prod/thumb/";
$image_height = 520;
$image_width = 650;
$id = $_POST["prodID"];
//gets image size info from a valid image file
$image_size_info = getimagesize($_FILES['image_data']['tmp_name']);
//initiate ImageMagick
$image = new Imagick($_FILES['image_data']['tmp_name']);
//Upload Full size
$image->writeImages($fullSize. $_FILES['image_data']['name'], true);
//Resize for thumb
if($image_type=="image/gif") //determine image format
{
//if it's GIF file, resize each frame
$image = $image->coalesceImages();
foreach ($image as $frame) {
$frame->resizeImage( $image_height , $image_width , Imagick::FILTER_LANCZOS, 1, FALSE);
}
$image = $image->deconstructImages();
}else{
//otherwise just resize
$image->resizeImage( $image_height , $image_width , Imagick::FILTER_LANCZOS, 1, FALSE);
}
//write image to a file
$results = $image->writeImages($thumb. $_FILES['image_data']['name'], true);
//output success response
if($results){
$response = json_encode(array('type'=>'success', 'msg'=>'Success'));
die($response);
}
?>
Any help is appreciated. Thanks :)
Upvotes: 2
Views: 108
Reputation: 337560
The issue is because you need to pass the FormData
directly to the $.ajax
call, not wrapped in an object. You can use the append()
method of FormData
to add additional fields to it:
var mdata = new FormData();
mdata.append('image_data', $(this)[0].files[0]);
mdata.append('prodID', id); // < data appended here
jQuery.ajax({
type: "POST", // HTTP POST
processData: false,
contentType: false,
url: "includes/ul.php", //Ajax Calls here
data: mdata, //Form variables
dataType: 'json'
});
Upvotes: 5