PHP wont receive POST data from AJAX using FormData - php

I am trying to pass some basic data using JavaScript and PHP.
The PHP is not receiving any data.
I have the following JavaScript code:
var formData = new FormData();
formData.append("action", "save-game");
formData.append("title", title);
formData.append("players", players);
formData.append("noTables", noTables);
formData.append("maxPPT", maxPPT);
formData.append("rounds", roundChart);
$.ajax({
url: "/static/apps/games.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response){
if (response.success) {
alert("Saved Game Setup");
} else {
alert("Failed to save game setup, "+response.reason);
console.log(response.reason);
}
}
})
And I have stripped the PHP down to the bare minimum but it is still not receiving the data
header("Content-Type: application/json");
$action = $_POST["action"];
echo json_encode(array(
'success' => false,
'reason' => $action,
));
The $action variable in PHP is returning null

try to build data like here
var buildData = function( _action, _title, _players, _noTables, _maxPPT, _rounds){
var data = {};
data.action = _action;
data.title = _title;
data.players = _players;
data.noTables = _noTables;
data.maxPPT = _maxPPT;
data.rounds = _rounds;
return JSON.stringify(data);
}
var _json = buildData("save-game", title, players, noTables, maxPPT, roundChart);

Related

ajax upload file response with extra data

I'm trying to add a file upload option to my page.
And I use Ajax for this purpose that sends the file to the server (where it is saved)
And should get back the file name
Everything works well except that when I print what comes back instead of just getting the array I send from the server I also get extra information.
Does anyone know where this supplement comes from? and how I can get rid of it?
here is my ajax:
$("#upload_file").change(function(input){
console.log(" in upload_file");
var file_data = $('#upload_file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>organizer/save_event_file',
// dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
beforeSend: function(){
$('#progress_spinner').show();
$('body').addClass('disable_body');
},
success: function(response,status){
console.log(response);
},
complete: function(){
$('#progress_spinner').hide();
$('body').removeClass('disable_body');
}
}).fail(function (xhr, status, error) {
alert("error");
});//fail;
});
this is my server function:
enter code here
public function save_event_file(){ // to add check and prommision
$filePath = $_FILES['file']['tmp_name'];
$type=$_FILES['file']['type'];
//adding to the name with the current date in the end
$date = new DateTime();
$name = substr($_FILES['file']['name'],0,strpos($_FILES['file']['name'],'.')). '__' .$date>format('d.m.y').substr($_FILES['file']['name'],strpos($_FILES['file']['name'],'.'));
$data = array('file' => curl_file_create($filePath, $type, $name));
$response = $this->organizer_model->save_file($data); // save the file with the new name
$result = array('alertcode'=>1,'response'=>$response,'name'=>$name);
echo json_encode($result);
}
this is what I expect to be the response:
{"alertcode":1,"response":true,"name":"old db function__21.03.21.txt"}
this is the real response (The other part is the " {"alertcode":1}" in the beginning):
{"alertcode":1}{"alertcode":1,"response":true,"name":"old db function__21.03.21.txt"}
I have no problem cutting this information and then making a parse as follows:
var ans = JSON.parse(response.substring(response.indexOf('{"alertcode',10),response.length));
But I want to understand where this is coming from - in case this addition changes - and then it will cut the string badly.

send a dataForm with a file in jquery ajax to php page

I built a back-end of a web application. I want the client to use drag and drop to insert folders and photos in the server.
This is a snippet of the drag & drop function:
else if(item.isFile) {
var element = new FormData();
element.append('foto', item);
element.append('idMadre', id);
$.ajax({
url: '../php/model.php?az=dragDropElementoFoto',
data:element,
async:false,
processData:false,
contentType:false,
type: 'POST',
dataType: 'json'
})
.done(function(data){
let elem = document.createElement("li");
elem.innerHTML = "<div class='row'><div class='col'><i class='fas fa-image'></i> "+item.name+"</div><div class='col-2'><i style='color:red' class='far fa-times-circle'></i></div></div>";
container.appendChild(elem);
})
In the PHP page, called "model.php," I have the code to make the typical C.R.U.D. operation with DB. How can I use the item of the FormData on the PHP page?
This is the PHP code of model.php:
if($_REQUEST['az']=="dragDropElementoFoto") {
$id=$_POST['idMadre'];
$ogg=$_POST['foto'];
var_dump($ogg);
$uploaddir = "../img/catalogo/";
$userfile_tmp = $_FILES['foto']['tmp_name'];
$userfile_name = $_POST['foto']['name'];
$urlfoto=$uploaddir.$userfile_name;
if (move_uploaded_file($userfile_tmp, $uploaddir.$userfile_name)) {
$sql="insert into documento (doc_url,doc_nome_file,doc_titolo,doc_cartella,doc_pub)"
. "VALUES(:doc_url,:doc_nome_file,:doc_titolo,:doc_cartella,:doc_pub)";
$dbo->query($sql);
$dbo->bind(":doc_url", $urlfoto);
$dbo->bind(":doc_nome_file", $userfile_name);
$dbo->bind(":doc_titolo", $userfile_name);
$dbo->bind(":doc_cartella", $id);
$dbo->bind(":doc_pub",0);
$dbo->execute();
$sql="select * from documento where doc_id IN (select MAX(doc_id) as doc_id from documento)";
$dbo->query($sql);
$risposta=$dbo->single();
echo json_encode($risposta);
}
}
Thank you very much.
in your html do you have input foto/idmadre? and second you can decode json like
$data = json_encode( $_POST );
if( json_last_error() != JSON_ERROR_NONE ){
exit;
}
if (!isset($_FILES['image']) || !is_uploaded_file($_FILES['image']['tmp_name'])) {
echo 'No file send...';
exit;
}
Next you can use like simple post.
Another example:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});

Upate table with AJAX in Laravel 5.3 not working

I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}
You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.
OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});

How to send form string data and image data in a single Ajax call

How do you merge two Ajax calls so that they pass form input data as well as form image data using the formData API?
View Ajax Calls:
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var radioValue;
$('#radio1, #radio2, #radio3, #radio4').each(function(){
if($(this).is(':checked')){
radioValue = $(this).val();
}
});
console.log(radioValue +
$("#bmdate").val() +
$("#bmtime").val() +
$("#bmscale").val() +
$("#bmpainlevel").val() +
$("#bmobs").val()
);
$.ajax({
url:'urllocation',
method: 'POST',
data:{
bmdate_data : $("#bmdate").val(),
bmtime_data : $("#bmtime").val(),
bmscale_data : $("#bmscale").val(),
bmcontents_data : radioValue,
bmpainlevel_data : $("#bmpainlevel").val(),
bmobs_data : $("#bmobs").val(),
},
}
).done(function(regresult){
});
})
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var pooPicture = $('input[name=poopic]');
var fileUpload = pooPicture[0].files[0];
var formData = new FormData();
formData.append("file", fileUpload);
$.ajax({
url:'urllocation',
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function() {
alert("File uploaded");
}
});
})
Controller Method that receives data, saves the file to server and then inserts the string data and file name into a database using an associative array:
function bowelmovements(){
$bmuserid = $this->session->userdata('id');
$bmsymptomdate = $this->input->post('bmdate_data');
$bmsymptomtime = $this->input->post('bmtime_data');
$bmsymptomtype = $this->input->post('bmscale_data');
$bmsymptomlocation = $this->input->post('bmcontents_data');
$bmsymptompainlevel = $this->input->post('bmpainlevel_data');
$bmsymptomobs = $this->input->post('bmobs_data');
$config['upload_path'] = APPPATH.'/assets/uploads/';
$config['allowed_types'] = "gif|jpg|png|mp4";
$this->load->library('upload', $config);
if($this->upload->do_upload("file")){
$imageData = $this->upload->data();
$fileName = $imageData[file_name];
$bmdata = array(
'userid' => $bmuserid,
'bmdate' => $bmsymptomdate ,
'bmtime' => $bmsymptomtime,
'bmscale' => $bmsymptomtype,
'bmcontents' => $bmsymptomlocation ,
'bmpainlevel' => $bmsymptompainlevel,
'bmobs' => $bmsymptomobs,
'bmimage' => $fileName
);
$insertBM = $this->poomonitormodel->insertBM($bmdata);
}
else{
echo "File not uploaded";
}
}
Currently this only submits the second Ajax call, and inserts only the file name into the database however I require both sets of data to submit into the table.
Thanks.
Here, I condensed your 2 ajax calls into a single one:
$("#submitbmsymptom").click(function(h){
h.preventDefault();
var radioValue;
$('#radio1, #radio2, #radio3, #radio4').each(function(){
if($(this).is(':checked')){
radioValue = $(this).val();
}
});
var pooPicture = $('input[name=poopic]');
var fileUpload = pooPicture[0].files[0];
var formData = new FormData();
formData.append("file", fileUpload);
formData.append("bmdate_data", $("#bmdate").val());
formData.append("bmtime_data", $("#bmtime").val());
formData.append("bmscale_data", $("#bmscale").val());
formData.append("bmcontents_data", radioValue);
formData.append("bmpainlevel_data", $("#bmpainlevel").val());
formData.append("bmobs_data", $("#bmobs").val());
$.ajax({
url:'urllocation',
method: 'POST',
processData: false,
contentType: false,
data: formData,
}).done(function(regresult){
});
});

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

Categories