I am trying to send some data from JS to PHP and make a DB request, which goes back into my JS.
Problem is, I only get "null" as result.
I checked and double checked my Query which is perfectly fine.
Here the JS:
var selectedEngin = getSelectedText(enginID);
selectedEngin = selectedEngin.slice(0, -1);
var roleNameList = new Array();
$.ajax({
url: '/getRoleNames.php',
type: "POST",
dataType:'json',
data: { engin : selectedEngin },
success: function(data){
console.info(data);
}
});
And the PHP:
include_once ("config.php");
$userAnswer = $_POST['engin'];
$row = array();
$query="select ROLE_NAME from type_vehicule_role WHERE TV_CODE
='".$userAnswer."' ORDER BY ROLE_ID" ;
$result=mysqli_query($dbc,$query);
$row=mysqli_fetch_array($result);
echo json_encode($row);
If I give back "test" instead of $row, it works perfectly as well.
Hope you can help me! Thank you!
Have a nice day!
$dbc has to contain the info with the parameters to connect to the DB. In your case the $result is null as your connection cause an error.
Try using this to get all of the data properly encoded prior to feeding it to the json_encode() call.
include_once ("config.php");
$userAnswer = $_POST['engin'];
$row = array();
$query="select ROLE_NAME from type_vehicule_role WHERE TV_CODE
='".$userAnswer."' ORDER BY ROLE_ID" ;
$result=mysqli_query($dbc,$query);
$row=mysqli_fetch_array($result);
// Walk the array and encode everything in UTF8
$utf8Row = array_map(utf8_encode, $row);
// JSONify the encoded array
echo json_encode($utf8Row);
Thanks to BA_Webimax I found the problem and got an answer:
The problem was the charset. I solved it using mysqli_set_charset($dbc,"utf8"); in the PHP.
Thank you for your help guys!
Have a nice day!
Related
So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support
First, I realize there are a lot of other similar posts. I have read through many, and I have still not been able to this it to work. That being said.....I have a 2 dimensional javascript object that is created dynamically. I am trying to pass it to PHP so I can save insert it into a MySQL table. It looks like the easiest way to do this is with an Ajax post.
Here is my javascript:
var jsonString = JSON.stringify(TableData);
$.ajax({
type: 'POST',
url: 'submit.php',
data: jsonString,
success: function(){
alert("OK");
}
});
I always get the success alert so I don't think the problem is there.
Here is my PHP file.
<?php
$servername = "localhost";
$username = "SME";
$password = "mypass";
$db = "p3";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $db);
if (!$conn) {
die("Could not connect to database");
} else echo "hey hey";
$data = json_decode("jsonString");
print $data;
?>
I am not really sure what I am doing wrong. Both of the files are in the same folder so I don't think it's a URL problem. Any help would be appreciated.
I see the problem. In order to access the what you're passing on, you need to get it from the $_POST variable which is an array. You can iterate over that array to get what you need and insert it in to your database after doing '$data = json_decode($_POST);`
Notice that your type in AJAX is post this is the same as the form method. It might also help in your ajax if you added `dataType: "json" to your parameters.
$.ajax({
type: 'POST',
url: 'submit.php',
data: jsonString,
dataType: 'json'
success: function(){
alert("OK");
}
So it looks like in your PHP you're not actually grabbing the posted data.
This is how I would recommend getting the data:
<?php
// Check if the posted value is not empty
if (!empty($_POST('jsonString')) {
$jsonData = json_decode($_POST('jsonString'));
}
?>
Then you can do what you need to do with the $jsonData.
The main problem was in my PHP code. Here's the answer.
$data = json_decode($_POST['denied'], true);
I was then able to insert into my MySQL table like this:
foreach($data as $user) {
$sql = "INSERT INTO deniedusers (firstname, lastname, username, email, password) values ('".$user['fname']."', '".$user['lname']."', '".$user['uname']."', '".$user['email']."', '".$user['password']."')";
I appreciate everyone's answers. Thanks!
So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)
Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.
So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.
function selectChar(uname, cname)
{
var data = {
username : uname,
charname : cname
};
$.ajax({
data : data,
type : 'Get',
url : 'start.php',
dataType:"json",
success : function (result) {
var data_character = JSON.parse(result);
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
}
});
}
The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.
function selectChar(uname, cname)
{
$.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
});
}
and finally the PHP code that queries the database and echos the data back.
<?php
$conn = new mysqli($hostname,$username,$dbpassword, $dbname);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_GET['username'];
$charname = $_GET['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
//Send the array back as a JSON object
echo json_encode($result);
?>
I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!
P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.
try this:
php get post and return json_encode
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$charname = $_POST['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
//Send the array back as a JSON object
echo json_encode($rows);
?>
JS ajax response and request
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
processData: false,
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
I would also try echo json_encode($_POST) to see if the you get the following response back :
{username: "hello", charname: "hl"}
i am trying to fetch JavaScript variable "i" in my PHP Code within a JavaScript function in the below code, I find problem in retrieving records, either first record or the last record repeats instead of all records in database.. can you guys help me out ?
Thanks
<?php
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
?>
<script language="javascript" type="text/javascript">
var intervalID = 0;
var time = 10;
MsgPop.displaySmall = true;
MsgPop.position = "bottom-right";
$(document).ready(function(){
var test = MsgPop.open({
Type: "success",
AutoClose: true,
Content: "Welcome to MsgPop!"});
MsgPop.live();
});
function showMessages(){
var n = '<?php
echo $nr;
?>';
var i = 0;
while (i < n){
var name = '<?php
echo $results[i]['name'];
?>';
MsgPop.open({
Type: "success",
Content: name,
AutoClose: false});
i++;
}
</script>
First you have to create a php file which return same array. File contain
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
echo json_encode($results);
exit;
Now you have to call this file using ajax from your javascript code.
$.ajax({
type: "POST",
url: "sql.php", //your file url
})
.done(function (data) {
//you get your array data(json format)
});
now you get that array in ajax response in json format and you can do anything with this data.
Impossible: PHP is a server side language that runs only at server. but javascript is a client side script it only run at your browser only. Php only gives response depends on your requests. The roll of php is end at server. But the javascript work with your response only, that is javascript can work at browser only.
You could try using AJAX, or else it isn't happening. Like said PHP is server-side only... Good luck!
PHP cannot fetch javascript variables. You should try another strategy.
At the server side (PHP), try to store $resuts in a javascript variable.
var results = '<?php echo json_encode($results); ?>';
Then at the browser side, try to access the data with javascript functions.
var name = results[i]['name'];
Well i have this php for get the value of mysql.
I get two rows in this query.
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT
accion_inmediata.accion,
accion_inmediata.responsable,
accion_inmediata.peligro,
accion_inmediata.ambiente,
DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion
FROM
accion_inmediata
WHERE
accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = mysql_fetch_array($result);
echo json_encode($array);
and this is my Jquery code
function traerAcciones(pnc){
$.ajax({
url: 'php_ajax/select_acciones.php?pnc='+pnc,
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
alert(this.accion);
});
}
});
}
when i execute this code the alert show me "undefined".
The $.each loop works fine but the value is the problem.
Please help and sorry for my bad English
Try to pass the value and the Index as parameters, this is how it works:
$.each(data, function(index, value) {
alert( value.accion );
});
Might also be a problem with the data object not containing what you think it does, do a
console.log(index, value);
inside your loop and a
console.log(data);
before the loop and you will see what you have and how to handle it.
Hope it helps!
Currently you are returning the array of your first row only. So to retrieve both you might want to do this:
include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT accion_inmediata.accion, accion_inmediata.responsable, accion_inmediata.peligro, accion_inmediata.ambiente, DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion FROM accion_inmediata WHERE accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = array();
while($row = mysql_fetch_array()):
$array[] = $row;
endwhile;
echo json_encode($array);
Now your jquery should be able to retrieve the data. Also, please avoid using MYSQL_QUERY it's deprecated.