Naming PHP object and SQL issue. - javascript

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 :)

Related

Mysqli(or PDO) and PHP to Javascritpt array through JSON

I have researched this question thoroughly. I know there are similar posts but there is simply something wrong with the code. I am fetching all rows from my database through PHP/PDO script (have also tried the similiar MYSQLI version). I then use json_encode to send the results back to the javascript/jquery.
What ever it is, i can send any other type of data through the json and print it through the javascript. But I can't seem to get the array stored in $arr stored in the javascript allArray.
I have tried JSON.parse(allArray) with no luck.
getAllData.php
<?php
header('Content-Type: application/json;');
$a = "bob";
$b = "george";
$arr = [];
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysql:dbname=guessthe_bob;host=localhost';
$user = 'guessthe';
$password = '***';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sth = $dbh->prepare("SELECT id,title FROM questions2 ORDER BY id");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
//print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
$arr = $result;
echo json_encode($arr);
// Free result set
$sth = null;
$dbh = null;
?>
.js
$.getJSON("functions/getAllData.php", function(data) {
var allArray = data;
$.each(allArray, function(index, value){
$('.testSpot').append(index + ": " + value + '<br>');
});
}
null

Rewrite a JSON array in PHP so that jQuery can read it?

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!

Php, Sql query won't let me pass in a variable, i keep getting an empty Array

So i am trying to run a Select query to my database but the query won't work when i pass in a pre defined variable. but it work only when i explicitly type it in For Example 'username', but won't let me pass in variable for example '$username'
So i have a a function in my angular file that is posting information to my php file.
Here is my php file:
<?php
require "loginConnect.php";
if($conn)
{
$gotIt = json_decode(file_get_contents('php://input'));
$username = mysqli_real_escape_string($conn, $gotIt->{"username"});
$password = mysqli_real_escape_string($conn, $gotIt->{"password"});
$myquery = "SELECT Email, Firstname, Lastname, Username, Password, ConfirmPassword FROM Myusers WHERE Username = '$username'";
// creating var to store the server's results
// passing in $conn for connection and $myQuery
$request = mysqli_query($conn, $myquery);
if ($request)
{
echo "the request was made successfully";
}
else
{
echo "the request failed";
}
// declaring an array to store the results objects in
$data = array();
// using the foreach loop to loop thu object in results
foreach ($request as $i) {
$data[] = $i;
}
// closing the connection and display the data
mysqli_close($conn);
echo json_encode($data);
}
else //otherwise connection failed come here
{
echo "sorry bad connection";
}
?>
so when i pass in the $username variable in my query i get nothing even thought i should be getting something, but when i type the username like 'theblackmamba' get what i want. even though the variable containers the same string, the variable is just not working. Please help i am super STUCK!

Javascript will not access json object

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)

Javascript and PHP Data Feed Usage

I am trying to grab data from php
This is my function in php
function getEvent($eventId){
$ret = array();
$ret['events'] = array();
try{
$db = new DBConnection();
$db->getConnection();
$sql = "select a.contact_name,a.userid from `contact` a where a.Id='$eventId'";
$handle = mysql_query($sql);
while ($row = mysql_fetch_object($handle)) {
//$ret['events'][] = $row;
$ret['events'][] = array(
$row->contact_name,
$row->userid
);
}
}catch(Exception $e){
$ret['error'] = $e->getMessage();
}
return $ret;
}
So I did the following at my javascript
var eventId = '2';
var DATA_FEED_URL = "datafetcher.php";
var param = [{ "name": "eventId", value: 9}];
$.post(DATA_FEED_URL + "?method=getEvent",
param,
function(data){
if (data.IsSuccess) {
alert(data.Msg);
//CloseModelWindow(null,true);
}
else {
alert("Error occurs.\r\n" + data.Msg);
}
}
,"json");
The problem is that nothing happens when I run it.
I want to able get the return result of my php, and then set
var contactName = Return Result contact name element under the $ret array from the datafeed
var contactId = Return result contact id element under the $ret array from the datafeed
Is there anything that I am doing wrong?
Have you tested your PHP if you get in function getEvent($eventId) at all?
Also double check that you are passing the $_POST['value'] to $eventId
Your javascript are expecting a json back from the PHP, so in your PHP you need to print the return result as a json, are you doing that somewhere?
ex echo json_encode($ret);

Categories

Resources