Problem Sending FormData to PHP together with string data - javascript

I want to send the file data together with string data. I am able to send it from ajax to PHP. But in PHP I can not get correct string data from $_POST[] This doesn´t work. I don´t know how to get the correct string.
I got only initial alphabet from a string. No specific product that I want.
Here is ajax
var action = "product1="+myProduct1+"&product2="+product2;
var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', action);
$.ajax({
type: "POST",
url: "URL TO PHP",
data:form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
//Do something
},
});
PHP
$data=$_POST['data'];
$action=$_POST['action'];
$mydata = array("myStatus"=>"ok", "myMsg"=>$action['product1']);
echo json_encode($mydata);
UPDATE
I found one solution :
javascript script:
var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('product1',my_product1);
form_data.append('product2',my_product2);
PHP code :
$data=$_POST['data'];
$mydata = array("myStatus"=>"ok", "myMsg"=>$_POST['product2']);
echo json_encode($mydata);
I am a bit satisfy with this. If someone has another solution would be nice. Because I have lots of string data in this code. If I do manual like this....will look stupid. Unless this is the only solution I can do.

you may try like this,
var action = [
{
product : "product1",
},
{
product : "product2"
}];
var file_data = $('#myfile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('action', JSON.stringify(action));
$.ajax({
type: "POST",
url: "URL TO PHP",
data:form_data,
dataType: 'json',
contentType: false,
processData: false,
success: function(response){
//Do something
},
});
and in php side,
$data = json_decode($post,true);
//print_r($data);
foreach ($data as $key => $value) {
echo $value['product'];echo "<br>";
}

Related

Store Audio from Blob url to server in Laravel

I've a portal in which I'm recording user audio and I am getting a blob URL and now I want to store this blob url as a file in my database. Can anyone help me with this.
This is my js code
$('#upload-read-aloud').on('submit',function(e){
e.preventDefault();
$.ajax({
type : 'GET',
cache : false,
data : {audioUrl:audioUrl},
url : '../upload-read-aloud-test',
success:function(response){
alert(response)
}
})
})
And this is my controller code
$url = $req->audioUrl;
$upload_dir = public_path()."/assets/";
$audio= $url;
$audio= str_replace('data:audio/wav;base64,', '', $audio);
$audio = str_replace(' ', '+', $audio);
$data = base64_decode($audio);
$file = $upload_dir . time() . ".wav";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
audioUrl is the Blob url which I'm passing in my route. The file is saving into the database but the file is empty.
As I see you use jQuery.
So, first of all DO NOT use GET request to upload data to server, use POST request instead. And send your blob as a file. Look at - https://stackoverflow.com/a/34340245/2585154
var s = 'some string data';
var filename = 'foobar.txt';
var formData = new FormData();
formData.append('file', new File([new Blob([s])], filename));
formData.append('another-form-field', 'some value');
$.ajax({
url: '/upload',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function () {
console.log('ok');
},
error: function () {
console.log('err'); // replace with proper error handling
}
});
Replace /upload with path to your API method, e.g.: ../upload-read-aloud-test, replace var s = 'some string data'; with your blob data and replace var filename = 'foobar.txt'; with any meaningful filename.
Or if you want to upload file from input, look at - jQuery AJAX file upload PHP
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
Replace upload.php with path to your API method, e.g.: ../upload-read-aloud-test, replace #sortpicture with your input id.
And then access your uploaded file in Laravel:
$file = $req->file('file');
dump($file);

Ajax request does not send blob data

I want to send data using an Ajax request to PHP.
I have the following data in my formData variable:
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
Printing the form entries gives me this:
I do the request like this:
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
In post.php I print the recieved data:
print_r("First name: " . $_POST["fname"] . PHP_EOL);
print_r("Last name: " . $_POST["lname"] . PHP_EOL);
print_r("Email: " . $_POST["email"] . PHP_EOL);
print_r("Data: " . $_POST["data"] . PHP_EOL);
For some reason it does not receive the 'data' entry in the $_POST variable. I get the following notice: "Notice: Undefined index: data"
Why does that happen? Could I somehow send the blob information?
As requested, the whole code. (inputFname, inputLname and inputEmail are not null. The code is situated inside a button onclick event method.
let evtTgt = e.target;
const container = evtTgt.parentNode;
const audioElement = container.getElementsByTagName("audio")[0];
const audioURL = audioElement.src;
let newBlob = await fetch(audioURL).then(result => result.blob());
var formData = new FormData();
formData.append('fname', inputFname.value);
formData.append('lname', inputLname.value);
formData.append('email', inputEmail.value);
formData.append('data', newBlob);
for (var key of formData.entries()) {
console.log(key[1]);
}
$.ajax({
type: 'POST',
url: 'post.php',
data: formData,
crossDomain: true,
processData: false,
contentType: false,
success: function(data) {
console.log("success!")
},
error: function() {
console.log("error!")
}
})
All this time I was looking for the blob contents inside the $_POST variable. I should have looked in the $_FILES variable instead!
I managed to get the file contents by calling this inside the php script:
$fileinfo = file_get_contents($_FILES['data']['tmp_name']);

Jquery Ajax returns 400 BAD request

I'm trying to send data to my local DB server but I keep getting 400 Bad request error when I try to send it.
var studentEmail = "ali#gmail.com";
var dataString = '&questionNumber='+ temp + '&answer='+ value + '&email='+ studentEmail;
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(dataString),
processData: false,
contentType: "application/json; charset=utf-8"
});
and this is the php file
<?php
$connection = mysql_connect("127.0.0.1", "root", "root"); // Establishing Connection with Server..
$db = mysql_select_db("db", $connection); // Selecting Database
//Fetching Values from URL
$questionNumber=$_POST['questionNumber'];
$answer=$_POST['answer'];
$email=$_POST['email'];
//Insert query
$query = mysql_query("INSERT INTO answers (questionNumber,studentAnswer,studentEmail) VALUES ($questionNumber,$answer,$email)");
echo "succesfully posted";
mysql_close($connection); // Connection Closed
?>
can anyone see what I'm doing wrong?
Thanks in advance!
JSON.stringify() method is used to turn a javascript object into json string.
So dataString variable must be a javascript object:
var data ={questionNumber:temp ,answer: value ,email:studentEmail};
AJAX
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8"
});
if you change the post to get you have to replace $_POST with $_GET into your php file.
There is an easier way to pass data that will work correctly for both POST and GET requests
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: {questionNumber:temp, answer:value, email: studentEmail},
processData: false,
});
Now jQuery does all the hard work and converts the object full of data to whatever format is required for a POST or GET request
You can send the ajax request this way:
var studentEmail = "ali#gmail.com";
$.ajax({
type: "POST",
dataType:'json',
url: "js/dbcon.php",
data: ({'questionNumber':temp,'answer':value, 'email':studentEmail }),
processData: false,
contentType: "application/json; charset=utf-8"
});
Also the PHP file needs to return a json string as well.
echo "succesfully posted";
is no valid json answer.
Return something like this:
$arr = array('success' => true, 'answer' => "succesfully posted");
echo json_encode($arr);
See also here: http://php.net/manual/de/function.json-encode.php
You should validate the input data, before inserting into the database.

Ajax send array and Image in same request

I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})

jQuery - DataTables upload file using ajax

I am using the plugin datatable to show a list of users. In this list I need to be able to upload new files.
I am trying to use ajax to try to send data to php. If I send value there is not problem my php script works however, I cannot get the data from the files.
In order to upload the files I am using the same script that I have written for another project which is working fine, so I think here the problem is DataTable that do not recognise my form data.
Anyone knows how to achieve this?
FIDDLE
JS
$('#example .fileinput-upload-button').on('click', function(event) {
var td = $(this).closest("td");
var parentTD = td.parent();
var form = $(this).closest("form");
var url = "example/upload.php?type=photo"
var data = new FormData(form);
alert(form);
$.ajax({
type: "POST",
url: url,
data: data,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType: "html",
processData: false,
success: function(data) {
alert(data);
}
});
PHP
$type = filter_input(INPUT_GET, "type");
$target_dir_header = $includesDir . "dashboard/resources/header_pic/";
$dataHeader = $_FILES['input7'];
$dataHeader_ext = explode('/', $dataHeader['type']);
$imageFileType_header = $dataHeader_ext[1];
$target_file_header = $target_dir_header . basename("header" . $imageFileType_header);
echo $type . " - " . $imageFileType_header;
Change your JQuery code to:
var td = $(this).closest("td");
var parentTD = td.parent();
var url = "example/upload.php?type=photo"
var form = $(this).closest("form").get(0);
$.ajax({
type: "POST",
url: url,
data: new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType: "html",
processData: false,
success: function(data) {
alert(data);
}
});
Your question explains here

Categories

Resources