When I run the following javascript/php, I keep getting "undefined" when alerting the 'userid' property of the json object. However, if I stringify the json object, it returns "[{'userid':'1'}] which is the correct value.
Why am I getting undefined if I am trying to access the correct name of the json object?
Here is the ajax I am using to access the object:
$.ajax({
type: 'POST',
url: 'WebPHP/check_login.php',
contentType: "application/json; charset=utf-8",
data: finalObject,
async: false,
dataType: 'json',
success: function(data) {
if (data["result"] === false) {
alert("Invalid Email or Password");
} else {
var userID = data["result"];
alert(userID["userid"]);
var url = "AMessage.html";
alert(JSON.stringify(data["result"]));
}
}
});
And the php that connects to the db:
$json = file_get_contents('php://input');
$jsondata = json_decode($json);
$email = $jsondata - > email;
$password = $jsondata - > password;
$sql1 = " SELECT user_id as userid
FROM users
WHERE email = '$email'
AND password = '$password';
";
$result = mysqli_query($Thesisdb, $sql1) or die(mysqli_error($Thesisdb));
$rows = $result - > num_rows;
while ($row = $result - > fetch_assoc()) {
$response[] = $row;
}
$post_data = array();
if ($rows == 1) {
$post_data = array('result' => $response);
} else {
$post_data = array('result' => false);
}
echo json_encode($post_data);
mysqli_close($Thesisdb);
You can't access the userid property because your userID variable contains an array - that's what the [] brackets mean in the json response: [{'userid':'1'}]. Try accessing it this way: alert(userID[0]["userid"]);.
Better yet, don't return an array, since you're checkng that $rows == 1 anyway.
Yes, as said by #Jack you can not access userid property, your json response:[{'userid':'1'}] is in array form, so you need to go for the syntax: alert(userId[0].userid)
Related
Ran into an issue with simply querying and returning the suggestID value.
I keep getting Array to string conversion, so i'm a bit lost. I'm
Javascript
$('#autocomplete').on('typeahead:selected', function (e, data) {
console.log(data);
var dataID = data;
$.ajax({
type: "POST",
url: "get.php",
data: $.param({itemID: dataID }),
success: function(data) {
console.log(data)
}
});
})
Get PHP FILE
<?php
require 'db.php';
if(isset($_POST['itemID'])) {
$db = new DbConnect;
$conn = $db->connect();
$str = $_POST['itemID'];
$stmt = $conn->prepare("SELECT * FROM mytable WHERE id = '$str'");
$stmt->execute();
$result= $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}
?>
The itemID parameter is being treated as an array by PHP:
$str = $_POST['itemID'];
If you were to var_dump that you might see that $str is an array.
When the data passed to ajax is an object and one of the property values is an array, param will serialize it using the array bracket syntax, which PHP automatically treats as an array. For example:
$.param({key: [1, 2, 3]}); // "key[]=1&key[]=2&key[]=3"
This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.
In a php file called: loadPosts.php
I am connecting to a database and retrieving a VARCHAR, VARCHAR, TEXT, TEXT, and VARCHAR. Each of them have an undefined length and I am trying to put the data into an object. Here is my php code.
<?php
//Creates an array to keep track of all information being past back to java script
$info = array();
$i = 0;
$j = 0;
//If server sends a post method then execute script
if ($_SERVER["REQUEST_METHOD"] == "POST"){
requestPosts($info);
//Encode the array to be sent to the java script with all the return messages and the state
echo json_encode($info);
}
function requestPosts(&$info){
//Set name of server, username, password, and database to access
$servername = "";
$username = "";
$passwordSQL = '';
$dbname = "";
//Create database connection
$con = new mysqli($servername, $username, $passwordSQL, $dbname);
//Check connection
if ($con->connect_error)
{
die("Connection failed: " . $con->connect_error);
$info["message"] = "failed";
}else{
$info["message"]= "You're Connected!";
}
//Create a query for account name
$sqlQuery = "SELECT * FROM posts;";
//Send query and assign to result
$result = $con->query($sqlQuery);
//If result is set
if($result){
//If result has rows found
if ($result->num_rows > 0)
{
//Loop through result
while($row = $result->fetch_assoc())
{
$info[$i][$j] = $row;
$j += 1;
}
$i += 1;
}
}
}
?>
Here is my javascript for calling and retrieving the data:
$(function(){
$.ajax({
type: 'POST',
url: 'assets/php/loadPosts.php',
success: function (msg) {
//Console log the message
console.log('msg', msg);
//Create an object from the message
var obj = JSON.parse(msg);
console.log('obj', obj);
},
error: function (msg) {
alert('Form Error' + msg);
}
});
});
When I retrieve the data from my java script I get this:
Return Code in Console
I would like to know if it is possible to name the object element in the array that contains all the children objects, as well as having the first object inside the parent object having the name of 0 instead of "".
Thanks in advance for any help or thoughts! I'm sure it's simple and I am just being dumb, but I would love the help! Thanks :)
I'm trying to create a JSON array in PHP that jQuery can use and access but for some reason It doesn't work. I get no error messages on the client side nor in the server logs and if I access enc.php directly, it does work, but I'm not sure if the output is correct (the array format).
What I want:
I would like to access the data with jQuery using data[i][0] for the ID ([i] because it's in a loop), and data[i][1] for the message and so on.
Maybe I'm trying to do this the wrong way, if so please help me by pointing me in the right direction or provide an example.
My code:
The current PHP code:
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$fetchedid = $row['id'];
$fetchedkey = $row['chat_key'];
$fetchednonce = $row['chat_nonce'];
$fetcheduser = $row['chat_user'];
$fetchedmsg = $row['chat_msg'];
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
$out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($out);
}
Result:
{"id":297,"msg":"test message","user":"john"}
My jQuery (Ajax) code:
$.ajax({
type: "GET",
url: "enc.php",
dataType: "json",
success: function(data) {
console.log('Update success called');
if (data == 2) {
// No messages to fetch
} else if (data == 3) {
// Cookie Tampering detected
} else if (data == 5) {
$("#chat").remove();
alert("Den här chatten är stängd (tiden har gått ut).");
window.location.href = "/?logout=safe";
}
else {
for (i = 0; i < data.length; ++i) {
var mid = data[i][0];
$.cookie("cmid", mid);
var from = data[i][1];
var msg = data[i][2];
$("#chat").append('<div class="left spotmsg"><div class="chat-avatar pull-left"><img src="/img/them.png" alt="avatar" width="48" height="48"></div><div class="message"><div class="arrow-left"></div><p><strong>#'+from+'</strong></p><p class="txt">'+msg+'</p></div></div>');
}
$('textarea').focus();
$(".chat_area").animate({ scrollTop: $(".chat_area")[0].scrollHeight}, 1000);
}
}
});
You can access object using . notation. To access values use key. for example to access id use data.id. If you have object you can't loop using length.
var mid = data.id; //specify key to access id
$.cookie("cmid", mid);
var from = data.user;
var msg = data.msg;
$("#chat").append('<div class="left spotmsg"><div class="chat-avatar pull-left"><img src="/img/them.png" alt="avatar" width="48" height="48"></div><div class="message"><div class="arrow-left"></div><p><strong>#'+from+'</strong></p><p class="txt">'+msg+'</p></div></div>');
The issue is you are outputting individual JSON strings in your while loop which is not correct because the combined output is invalid JSON. The solution is to build an array and then output the array at the end.
$arr = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$fetchedid = $row['id'];
$fetchedkey = $row['chat_key'];
$fetchednonce = $row['chat_nonce'];
$fetcheduser = $row['chat_user'];
$fetchedmsg = $row['chat_msg'];
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
$out = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
$arr[] = $out;
}
header('Content-Type: application/json');
ob_end_clean();
echo json_encode($arr); // encode the final array
Now, your output can contain multiple chat messages and is valid JSON, such as:
[{"id":297,"msg":"test message","user":"john"}, {"id":300,"msg2":"test2 message","user":"john"}]
In the JavaScript, refer to the property names instead of [0], [1] etc:
var mid = data[i].id;
$.cookie("cmid", mid);
var from = data[i].user;
var msg = data[i].message;
the problem stems from the fact that your result is not the json for an array of objects but a simple object, so the line
for (i = 0; i < data.length; ++i) {
never iterates as data does not have a length. you want your result to look like
Result :
[
{"id":297,"msg":"test message","user":"john"}
]
that way it will also hold more than one john ;)
suggestion
so I believe your php should be :
$result = $stmt->get_result();
$out = array();
while ($row = $result->fetch_assoc()) {
//... your code doesn't change here
$plainmsg = \Sodium\crypto_secretbox_open($fetchedmsg, $fetchednonce, $fetchedkey);
//here we append to $out
$out[] = array('id' => $fetchedid, 'msg' => $plainmsg, 'user' => $fetcheduser);
header('Content-Type: application/json');
ob_end_clean();
//echo json_encode($out);// not yet...
}
echo json_encode($out);//but now!
I'm devoloping a site that retrieve information about user location (name,lat,lng,address..) from a database with an ajax request performed with jQuery. I have fetched all the results into an associative arrays
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$conn = mysql_connect($servername,$username,$password);
if(!$conn){
die('Could not connect' .mysql_error());
}
mysql_select_db($dbname);
$query = " SELECT * FROM userevent ";
$result = mysql_query($query);
$a = array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($a,$row);
}
echo json_encode($a);
mysql_close($conn);
After fetching i get this type of array :
Array
(
[0] => Array
(
[ID] => 3823
[name] => Erik
[lat] => 63.2994
[lng] => 23.7497
[title] => b
)
[1] => Array
(
[ID] => 3824
[name] => George
[lat] => 43.2994
[lng] => 13.4494
[title] => a
)
)
in my .js file i have this :
function loadmap(){
$.ajax ({
url:'loaddata.php',
dataType:'json',
success: function(data){
alert(""+data[0]); //DOESN'T WORK ???????
},
})
}
How can I read my array now ?
data is likely coming back as a string, you can use JSON.parse to turn it into JSON.
function loadmap(){
$.ajax ({
url:'loaddata.php',
dataType:'json',
success: function(data){
data = JSON.parse(data);
alert(""+data[0]);
},
})
}
Heads up : Use print_r() function for printing out the output of
json_encode() php predefined function instead of the native echo.
PHP updated code
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$conn = mysql_connect($servername,$username,$password);
if(!$conn){
die('Could not connect' .mysql_error());
}
mysql_select_db($dbname);
$query = " SELECT * FROM userevent ";
$result = mysql_query($query);
$a = array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($a,$row);
}
print_r(json_encode($a));
mysql_close($conn);
You don't need to parse the array in the clientside if you are already using json_encode function. You can Access the array values as a normal javascript
object using the dot(.) operator.
Javascript Updated code snippet
function loadmap(){
$.ajax ({
url:'loaddata.php',
dataType:'json',
success: function(data){
alert(data.ID); //this one will print the value of ID key in the array
},
})
}