For some reason when I do my AJAX request in my main.js file, I get an error:
Undefined index: id in sqlinfo.php on line 13
And I'm not sure why because I feel that I am filling out the request object correctly. What's also strange is that this works:
$requestType = filter_input(INPUT_POST, 'requestType', FILTER_SANITIZE_STRING);
So why doesn't $_POST['id'] work?
If anyone could tell me what error I'm making that would be great!
Note: I know albumId has a value because I already used console.log() to verify that it has a value.
Code
main.js
$(document).ready(function () {
$(".grid").on("click", ".edit", function (){
var albumId = $(this).siblings(".grid-info").attr("id");
var imageId = $(this).siblings("img").attr("id");
var request = (albumId == '') ? {requestType: 'Album', id: albumId} : {requestType: 'Image', id: imageId};
var getSQLInfo = $.ajax({
url: '../P3_M2/ajax/sqlinfo.php',
method: 'post',
data: request,
dataType: 'json',
error: function(error) {
console.log(error);
}
});
});
sqlinfo.php
<?php
require_once('../configsql.php');
$queryFor = array(
'Album' => 'SELECT * FROM Album WHERE id = ?',
'Image' => 'SELECT * FROM Image WHERE id = ?');
$requestType = filter_input(INPUT_POST, 'requestType', FILTER_SANITIZE_STRING);
if (empty($requestType)) {
echo 'Missing requestType.';
die();
}
$id = $mysqli->real_escape_string($_POST['id']); //getting undefined index id
?>
Thanks to #v Sugumar I realized I had the wrong boolean (==) when I assigned request. Changing it to != fixed it:
var request = (albumId != '') ? {requestType: 'Album', id: albumId} : {requestType: 'Image', id: imageId};
Related
I'm using a $.post() to push data to a php file. But the $_POST is empty when I make a var_dump of it.
JS script :
$('#Notes').on("click", function (e) {
e.preventDefault();
let $id = $(document).getUrlParam("varname");
let $text = $(this).attr('data');
let $notes = prompt("Modifier la note", $text);
console.log($text, $id, $notes);
if ($notes !== null || $notes !== "") {
$.post(
'../buckets/update_note.buckets.php',
{
id: $id,
notes: $notes,
},
function (data) {
console.log('Data Id : ',data.id);
console.log('Data Name : ',data.name);
})
.then(r =>{
location.replace('../buckets/update_note.buckets.php');
})
}
in php file :
<?php
var_dump($_POST);
var_dump($_GET);
The 1st console.log in js show me the values of the 3 variables but the console.log in the callback show me undefined. But I see in the network debugger :
Form Data
id: xxxx
notes: xxxx
Any idea ?
I believe, data will be text in your case. You need to use json_encode() in you php to print complex objects. Then in your JS you can use JSON.parse() to restore object or define application/json content type in your POST query. Something like:
// php
$json = json_encode([
'post' => $_POST,
'get' => $_GET
]);
// js
function (response) {
const data = JSON.parse(response);
}
You can try in this way.
JQuery CODE
$('#Notes').on("click", function (e) {
e.preventDefault();
let $id = $(document).getUrlParam("varname");
let $text = $(this).attr('data');
let $notes = prompt("Modifier la note", $text);
console.log($text, $id, $notes);
if ($notes !== null || $notes !== "") {
$.post(
'../buckets/update_note.buckets.php',
{
id: $id,
notes: $notes,
},
function (data) {
var data=$.parseJSON(data);
console.log('Data Id : ',data.id);
console.log('Data Name : ',data.notes);
})
.then(r =>{
//location.replace('../buckets/update_note.buckets.php');
})
}
PHP CODE
echo json_encode($_POST);
I have an AJAX call that makes my JSON look this in my JSON file:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
But I would like to have it like this (and this was before I changed my AJAX call with: id: getUrlParameter('id'):
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
The only thing I want to add is the "id": "new", but when I do so (with id: getUrlParameter('id') it gets the id, but it messes up my code.
This is my AJAX call (my JSON starts looking like the first piece of code when I use this)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: $('#my_form').serialize()
},
dataType: 'json',
}).done(function(response) {
});
});
}
How could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my AJAX call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id').
edit: Since someone said it could be my php code.. here is my php code:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>
you can use parse_str($str, $output); it will help you achieve what you need.
Note that parse_str takes two parameters, the first one is the string (get Parameters), second one is the array to return the result on. you can use the below code
parse_str($str, $output);
echo json_encode($output);
The issue is how you process formData parameter. serialize() is building url encoded string, however you want key-value pairs. Try this:
$("#my_form").on("submit", function(event) {
event.preventDefault();
var myData = {id: getUrlParameter('id')};
for (var pair of formData.entries()) {
myData[pair[0]] = pair[1];
}
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: myData,
dataType: 'json',
}).done(function(response) {
window.location = 'index.php';
});
});
}
I am using ng-file-upload from Github. I have successfully uploaded and added image on both target folder and database. However, I need a specific data from my client side that will be needed for my query.
Controller.js ---- sample snippet of my upload function.
$scope.upload = function (dataUrl, name) {
Upload.upload({
url: 'php/profile-pic.php',
method: 'POST',
transformRequest: angular.identity,
headers: {
'Content-Type': undefined,
'Process-Data' : false
},
data: {
file: Upload.dataUrltoBlob(dataUrl, name),
id: user[0].id
},
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
console.log(response);
}, function (response) {
if (response.status > 0) $scope.errorMsg = response.status
+ ': ' + response.data;
console.log(response);
}, function (evt) {
$scope.progress = parseInt(100.0 * evt.loaded / evt.total);
});
}
PHP ---- relative code on my server side
$postdata = file_get_contents("php://input");
$data = json_decode($postdata);
// $id = $data->id;
echo json_encode($data) // returns null
if(!empty($_FILES))
{
$filename = $_FILES['file']['name'];
$destination = '/../images/' . $filename;
if(move_uploaded_file( $_FILES['file']['tmp_name'] , PATH . $destination ))
{
$insertQuery = "UPDATE tblusers SET image = ".$_FILES['file']['name']." WHERE id='???'"; // ??? = the specific data that I need
Image ---- from console.log response
The id is what I need to get for my query.
How can I get that? file_get_contents not working for this one, it returns null.
I got the answer I am looking for.
In my upload function in my controller, I changed the key id into 'id' with apostrophe:
data: {
file: Upload.dataUrltoBlob(dataUrl, name),
'id': user[0].id
}
In my php code, I did this:
$id = $_POST['id'];
I got the idea from Github Repo Issues at the last part of the page.
I tried to send post value to OrderController (I use ZF2). I have javascript code in view folder.These are the code:
function submitHandler(form) {
var urls = '<?php echo $this->baseurl; ?>/order/saveOrder';
var pack= $("#pack").val(),
name= $("#name").val(),
instit= $("#instit").val(),
telp= $("#telp").val(),
email= $("#email").val(),
address= $("#address").val(),
orderno = "test",
order_stat ="phone",
pack_type = "recurring",
rec_period ="monthly";
$.ajax({
type: 'POST',
url: urls,
data: {
pack: pack,
name: name,
instit:instit,
telp: telp,
email: email,
address: address,
orderno : orderno,
order_stat :order_stat,
pack_type : pack_type,
rec_period :rec_period
},
success: function(msg) {
var result = JSON.parse(msg);
if (result.success) {
alert("SUccESSSS");
} else {
alert(result.msg);
}
},
error: function(xhr, status, error){
alert("Failed");
}
});
}
And these are code from controller:
public function saveOrderAction() {
$post = $this->getRequest()->getPost();
$response = $this->getResponse();
/*
$storage = Order\Storage::factory($this->getDb());
$attd = new Order($storage);
$success = false;
$msg = '';
$attd->orderno = $post['orderno'];
$attd->order_stat = $post['order_stat'];
$attd->pack = $post['pack'];
$attd->pack_type = $post['pack_type'];
$attd->rec_period = $post['rec_period'];
$attd->name = $post['name'];
$attd->instit = $post['instit'];
$attd->telp = $post['telp'];
$attd->email = $post['email'];
$attd->address = $post['address'];
//$save = $attd->saveOrder();
if ($attd->saveOrder(true)) { */
$success = true;
$msg = 'Saved Success';
echo "<script type='text/javascript'>alert($msg);</script>";
print_r('test');
printf('test2');
$response->setContent(json_encode(array("success" => $success, "msg" => $msg)));
return $response;
}
But it doesn't show anything. So I have commented and just want to show alert, but it doesn't show. Help me,thanks.
Probably you need to change your URL to:
var urls = '<?php echo $this->baseurl; ?>/order/save-order';
URL's in zend are lowercase. Multiple words are seperated by dashes. When the request is processed the action is camelCased so your action methods are proper PSR-2.
I try to use x-editable but i can't find a way to update my database with new data.
In my index.php i have :
superuser
and in main.js i have :
$('#username').editable({
type: 'text',
pk: 1,
url: 'post.php',
title: 'Enter username'
and in post.php :
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
and after :
$result = mysql_query('update users set '.mysql_escape_string($name).'="'.mysql_escape_string($value).'" where user_id = "'.mysql_escape_string($pk).'"');
When i try, nothing happen, no change in DB, no message, just nothing. If i change $value = $_POST['value']; and others with real values and i launch post.php directly, sql works.
JS
(function(){
$('a#editlang').editable({
url: 'post.php',
escape: false,
"mode": 'inline',
"rows": '5',
"inputclass": 'input-xxlarge',
validate: function(value) {
if($.trim(value) == '') {
return 'This field is required';
}
},
});
});
HTML
<a name="editlang" id="editlang" data-type="textarea" data-pk="1" title="Edit">superuser</a>
in php
$pk = $_POST['pk']; // register id
$value = $_POST['value']; // new name
query:
$result = mysql_query('update users set name = "'.mysql_escape_string($value).'" where user_id = "'.mysql_escape_string($pk).'"');