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);
Related
I have a page where I do different requests via AJAX, also I have the developer DB and the production DB but the JS is the same. In certain module, if I open it using the developer DB it shows me the response but if I use the production database it shows nothing but not error is displayed. If I use the production DB in any other module it works perfectly. I already checked in the network console and it says that in both cases the request is sent. Here is the JS code:
function consultaAdministradores(id, tipo, btn){
var datos = {
'id': id,
'tipo': tipo
}
console.log("DATOSSSS");
console.log(datos);
$.ajax({
url: '../send/get_AdminEmpresas.php',
type: 'POST',
data: datos,
dataType: 'JSON',
success: function(res) {
console.log(" res --------- ");
console.log(res);
imprimeAdmins(res);
}
});
console.log("Se pasó el AJAX");
And in the PHP file I have this:
$res = $con->consulta($sql);
if ($res->num_rows > 0 ) {
$i = 0;
while ($dato = $res->fetch_assoc()) {
$administradores[$i] = $dato;
$i++;
}
if ($tipo_page == 'prev') {
array_multisort($administradores);
}
$array = array('status' => "Success", 'administradores' => $administradores, 'id' => $id_page, 'tipo' => $tipo_page);
}
else
{
$array = array('status' => "Fail", 'message' => 'Sin resultados');
}
$json = json_encode($array);
echo $json;
The problem wasn't the JS or the PHP files, the problem was the codification of the DB, I inserted some data in UTF-8 codification and later I converted to UTF-8 codification giving me as a result some weird characters.
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';
});
});
}
Hopefully an easy question here. I actually used an example I found on SO but can't figure out why its not working. No errors in console or anything.
I have an ajax Post function I am using to pass data to a php script.
Its passing the data correct, but the response each time is coming back as an error alert. I can confirm that server side is getting the data and processing it correctly, just can't figure out why its never returning a success response.
Here is the Ajax:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
</script>
And in my php script I used this:
<?php
$success = true;
if($success == true) {
$output = json_encode(array('type'=>'success', 'message' => 'YAY'));
} else {
$output = json_encode(array('type'=>'error', 'message' => 'WHOOPS'));
}
die($output);
?>
The problem is that datatype: 'json' should be dataType: 'json'. Javascript is case-sensitive.
The error is because you received the returned data as json but the content type is a simple string (text/html) so you need to JSON.parse() the received data first like so:
$(function () {
$('#pseudoForm').on('click', '#submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "psu_output.php",
data: $('#pseudoForm').serialize(),
datatype: 'json',
success: function (response) {
response = JSON.parse(response);
if(response.type == 'success') {
$('#messages').addClass('alert alert-success').text(response.message);
} else {
$('#messages').addClass('alert alert-danger').text(response.message);
}
}
});
return false;
});
});
The second option is to send json headers from php itself thus removing the need of parsing JSON in javascript. You can do that by using the following line of code BEFORE ECHOING OR PRINTING ANYTHING ELSE FROM THE PHP SCRIPT:
header('Content-Type: application/json');
and then
echo $output;
If you are working with JSON responses, you need to set the header so your browser and your JavaScript could interpret it correctly:
<?php
$success = true;
if ($success == true) {
$output = json_encode(array(
'type' => 'success',
'message' => 'YAY'
));
} else {
$output = json_encode(array(
'type' => 'error',
'message' => 'WHOOPS'
));
}
header('Content-Type: application/json');
echo $output;
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};
drupal 6: here is the code:
http://pastebin.com/GGVFfAGS
//getcity.js:
$(document).ready(function() {
$("#edit-field-house-geo-area-value").bind('change', function(){
selected_loc=$("#edit-field-house-geo-area-value option:selected").val();
var myURL="http://whatever.com/getajax/citys/"+selected_loc+"/";
$.ajax({
type: "GET",
url: myURL,
dataType: "json",
success: function(data){
console.log(data);
}
});
});
});
drupal module:
function sf_menu()
{
cache_clear_all();
$items = array ();
$items ['getajax/citys/%'] = array ('title' => 'This is my custom page', 'page callback' => 'sf_get_cities_ajax', 'access arguments' => array ('access content' ), 'access callback' => 'user_access', // TRUE will give access to everyone
'page arguments' => array (2 ), 'type' => MENU_CALLBACK );
return $items;
}
function sf_get_cities_ajax($cityid)
{
$termsarray = array ();
$terms = array ();
$cityid_safe = (int)$cityid;
$cityid_safe = check_plain($cityid_safe);
if (is_number($cityid_safe)) {
$terms = taxonomy_get_children($cityid_safe, 143, 'tid');
if (count($terms)) {
foreach ($termsarray as $k => $v) {
$termsarray [check_plain($k)] = t($v [tid]);
}
$f= array('status' => 1, 'data' => $termsarray,'moo'=>'sadasdsd');
print drupal_json($f);
exit();
}
}
}
its not return me somthing even i print the 'moo' data
its my function its working fine i get array at the final but its dont pass it
That looks like it should work except one thing... PHP doesn't have a function 'is_number()' so unless you wrote your own you need to change your IF statement to use PHP built in 'is_numeric':
if (is_numeric($cityid_safe)) {
Its not a JS issue at all.