Hello I have the following AJAX code:
var formData = new FormData($('form')[0]);
$.ajax({
url: 'saveImage.php', //Server script to process data
type: 'POST',
data: formData,
processData: false,
success: function(data){
console.log(data);
}
});
It works great and it loads up the PHP page it the background like it should:
<?php
include_once "mysql_connect.php";
$imageName = mysql_real_escape_string($_FILES["Image1"]["name"]);
$imageData = '';
$imageext = '';
if($imageName != null){
$imageData = mysql_real_escape_string(file_get_contents($_FILES["Image1"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$imageSize = getimagesize($_FILES["Image1"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["Image1"]["type"]);
$FileSize = FileSize($_FILES["Image1"]["tmp_name"]);
$imageext = mysql_real_escape_string($imageSize['mime']);
}
$query=mysql_query("INSERT INTO pictures (`id`, `imagedata`, `imageext`) VALUES ('', '$imageData', '$imageext');");
echo $imageext;
?>
The only problem is that the PHP page cant find the variable Image1 which is the name of the input in the form. Have I done something wrong. I was thinking that maybe in the data parameter in the Ajax it would be something like this but correct:
data: "Image1"=formData,
Is that a thing, if not why cant my PHP see that input field?
You forgot cache and contentType properties in your Ajax function. Try that it should work :
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "saveImage.php",
processData: false,
contentType: false,
cache:false,
data: formData,
success: function(data){
console.log(data);
}
});
Related
First of all, I have already read through many other posts and tried different things, but no solution approach has worked so far.
My problem: ajax does not send the POST data.
fillTable.js
function fillTableWithData(htmlID, tableSQL, colsSQL, orderSQL){
var jsondata = new FormData();
jsondata.append("action", htmlID);
jsondata.append("table", tableSQL);
jsondata.append("cols", colsSQL);
jsondata.append("order", orderSQL);
$.ajax({
url:"table.php",
method: "POST",
dataType: 'json',
contentType:false,
processData:false,
data: jsondata,
success:function(result){
// $(htmlID).html(result);
alert("test");
}
});
}
table.php
<?php
require('db.php');
echo (count($_POST)); // result is 0
if(isset($_POST['action'])){ // not set
if($_POST['action'] == "getDataAsRows"){
getDataAsRows($_POST['table'], $_POST['cols'], $_POST['order']);
}
}
function getDataAsRows($table, $cols, $order) {
...
}
?>
Both files are inside the same folder:
/scripts/fillTable.js
/scripts/table.php
The url should not be a problem, since the php code prints out the length of $_POST.
Ive searched on Stack overflow all over the place and could not find a solution or a post that is close to my problem.
So if this has been posted before I do apologies.
I am posting some information using a different method rather than posting a form which I will explain after I show you the code :)
Jquery:
$("#submit-add-cpos").on('click',function(){
var checkHowManyInstallments = $('#installment-ammount').val();
var checkCpoNumber = $('#addcponumber').val();
var checkCpoTotalPrice = $('#addcpoprice').val();
var checkCpoContactName = $('#addcpocontactname').val();
var form_data = new FormData();
form_data.append("type", 'addcpo');
form_data.append("quoteid", '<?php echo $_GET['id']; ?>');
form_data.append("installmentamount", checkHowManyInstallments);
form_data.append("cponumber", checkCpoNumber);
form_data.append("costcode", '<?php echo $quotecostcode; ?>');
form_data.append("cpocontactname", checkCpoContactName);
form_data.append("cpotitle", '<?php echo $quotetitle; ?>');
var checkDynamicValues = '';
var checkDynamicValue1 = '';
var checkDynamicValue2 = '';
var checkmakename1 = '';
var checkmakename2 = '';
if(checkHowManyInstallments != 'undefined' && checkHowManyInstallments != '' && checkHowManyInstallments != 0){
for(var makingi = 1; makingi <= checkHowManyInstallments; makingi++){
checkDynamicValue1 = $('#cpo-adddate-' + makingi).val();
checkDynamicValue2 = $('#cpo-addprice-' + makingi).val();
form_data.append('cposadddate' + makingi, checkDynamicValue1);
form_data.append('cposaddvalue' + makingi, checkDynamicValue2);
}
}
$.ajax({
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
$('body').html(data);
}
});
});
So from this script I get all the fields from within the form, including some dynamic ones.
The reason why I am doing it like this instead of the easier way of:
$("#formname").on('submit',function(){
$.ajax({
url: "xxxxxxxxxx/xxxxx/xxxx/xxxx.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
});
Is because for some reason it will not find the posted information no matter what I tried, so the only way I could do it is to find each id and get the value from it.
Now the issue is, uploading a file, you can not simply upload a file this way because nothing is posted.
How would I go about uploading a file if not posting a form?
Thanks
The reason why it was not posting the file is simply because I did not give it a file to post...
18 hours straight of work has not agreed with me here.
Basically I need to add the following code
var checkCpoFiles = $("#addcpofile").prop("files")[0];
form_data.append("cpofile", checkCpoFiles);
Now all works
:)
Please go through this page Ajax Upload image
Here's sample code, it might help
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form enctype="multipart/form-data" action="uploadfile.php" method="POST" id="imageUploadForm">
<input type="file" name="upload" />
<input type="submit"/>
</form>
</body>
<script>
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
</script>
uploadfile.php
<?php
if(move_uploaded_file($_FILES['upload']['tmp_name'],$_FILES['upload']['name'])) {
echo "File uploaded successfully";
} else {
echo "Unable to upload the file";
}
?>
Hope it helps! All the best!
Hi I have a wordpress php class that receives my ajax and works good.
Now i have to upload a file in the same POST request i use to pass parameters to the PHP class ( i have a switch in the class that sends me to the proper function based on the parameters in the POST data ).
this is the code:
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <?php echo get_current_user_id(); ?>;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var data = {
'action': 'romme_call',
'whatever': 1234,
'userID': userID,
'function_call': 'upload_profile_photo',
**'form_data' : formData**
};
console.log(data);
jQuery.post(ajaxurl, data, function(response) {
console.log("done");
console.log(data);
});
this code will of course return a "Uncaught TypeError: Illegal invocation"
because it does not accept formData as parameter in data.
how can i handle this?
It returns Illegal invocation because jQuery is trying to parse the form data with $.param.
When submitting files with jQuery's ajax processing must be turned off
$('#imageUploadForm').on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
var userID = <? php echo get_current_user_id(); ?> ;
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
formData.append('action', 'romme_call');
formData.append('whatever', '1234');
formData.append('userID', userID);
formData.append('function_call', 'upload_profile_photo');
$.ajax({
url : ajaxurl,
type : 'POST',
data : formData,
contentType: false,
processData: false
}).done(function(response) {
console.log("done");
console.log(data);
});
});
I'm trying to get my results from a SQL query into an array in javascript. I'm trying the following:
PHP:
$query = mysqli_query($connection, "select a, b, c from table");
$result_a = array();
$result_b = array();
$result_c = array();
while($row = mysqli_fetch_array($query)) {
$result_a[] = $row['a'];
$result_b[] = $row['b'];
$result_c[] = $row['c'];
}
echo json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
javascript:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
},
});
return false;
The PHP arrays have the data I'm looking for but the alerts in javascript are undefined. Any help would be appreciated.
In PHP you echo data in json format json_encode(array('a'=>$result_a,'b'=>$result_b, 'c'=>$result_c ));
So if you want to use the json as an object directly in the ajax success function, you need tell the ajax call "You are expecting a json object coming bakc!";
So you should modified js code to this:
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false,
dataType : "json", // <------here, auto parse json for you
error: function(){},
success: function(data){
alert (data.a);
alert (data.b);
alert (data.c);
}
});
Or in the success function, manually parse json before use;
$.ajax({
type: "POST",
url: "http://mywebsite.com/data.php",
data: dataString3,
cache: false
error: function(){},
success: function(data){
var obj = jQuery.parseJSON(data); // <---- here, manual parse
alert (obj.a);
alert (obj.b);
alert (obj.c);
}
});
I have the following ajax function:
reader.onload = function(event){
var fd = new FormData();
var Name = encodeURIComponent('audio_recording_' + new Date().getMinutes() + '.wav');
console.log("name = " + Name);
fd.append('fname', Name);
fd.append('data', event.target.result);
$.ajax({
type: 'POST',
url: 'upload.php',
data: fd,
processData: false,
contentType: false,
success: function(data){
//console.log(data);
$.ajax({
type: 'POST',
url: 'readFile.php',
data: {"fileName":fileName},
success: function(data){
console.log(data);
}
});
}
});
};
first question: I want to retrieve the data from the second success function to use it later in the code.how could that happen?
second question: the data is an audio file.Is there is a special way to get audio data, or we can get it the same way as any data?In my php server side of the second ajax, I'm reading an audio file and want to use its data.I did simple file open and get contents.does that work for audio files?
server-side code:
<?php
$fileName=$_POST["fileName"];
$dh = opendir('upload/');
$contents = file_get_contents('C:/wamp/www/JSSoundRecorder/upload/'.$fileName);
// echo $contents;
echo $fileName;
This is a bad practice in general, but what you could do is specify a global variable at the start, and then assign data to that variable inside the success. The issue with this is that you can't be certain that the ajax has completed and your variable has been set, before you need to use it.
var mySuccessVar = null;
...
success: function(data) {
mySuccessVar = data;
}
... // later in the code:
if (mySuccessVar != null) {
yourFunction(mySuccessVar);
}