Json working for certain vars but not for others - javascript

I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't.
When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine.
This is the request script:
function getcolours() {
var hr = new XMLHttpRequest();
hr.open("GET", "camp_map_script.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
for (var obj in data) {
number = data[obj].number;
colour = data[obj].colour;
neighbour1 = data[obj].n1;
alert (neighbour1);
window["colour" + number] = colour;
var x = document.getElementsByClassName(number + ' ' + colour);
x[0].style.display = "block";
}
}
}
hr.send(null);
}
This is the php part:
<?php
include_once("../php_includes/check_login_status.php");
?><?php
$number = "";
$sql = "SELECT camp_id FROM users WHERE username='$log_username'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$campid = $row[0];
$sql = "SELECT players FROM campaigns WHERE id='$campid'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$players = $row[0];
$number = ($players*2)-1;
$sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number";
$query = $connect->query($sql);
$jsonData = '{';
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},';
}
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
$connect->close();
?>
Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit.
It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/

Related

Get JSON Array into another file via Ajax

I'm trying to add a JSON array from a separate file into another array in my main page via Ajax. For some reason my Ajax is not working, There are 4 arrays, I need to store each of them in separate arrays in my main page. This is what I got.
load file:
<?php
session_start();
if(!isset($_SESSION['usersId']))
{
header("Location: ../index.php");
exit();
}
else
{
include_once 'includes/dbh.inc.php';
}
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id`;";
$result = mysqli_query($conn, $sql);
$jsonsensor1 = array();
$jsonsensor2 = array();
$jsonsensor3 = array();
$jsonsensorsum = array();
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$jsonsensor1[] = intval($row['sensor1'] * ($p = pow(10, 2))) / $p;
$jsonsensor2[] = intval($row['sensor2'] * ($p = pow(10, 2))) / $p;
$jsonsensor3[] = intval($row['sensor3'] * ($p = pow(10, 2))) / $p;
$jsonsensorsum[] = intval(($row['sensor1'] + $row['sensor2'] + $row['sensor3']) * ($p = pow(10, 2))) / $p;
}
}
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
?>
Output from the load file:
[5,10,10.99,10.99,13,5,14.31,1,1,5,5,5,1,5,3,3,5,5,1,5,10.32,10.32,5,8,5,10,5,5,19,5,7.36,7.36,5,12.2,12.2,2.2,2.2,23.3,5,10.87,6.87,6.87,5,5,10,10,10,10,5,5,5,5,5,0,5,5]
[8,12.5,12.5,12.53,12.53,8,10.11,1,1,8,8,8,1,8,3,3,8,8,1,8,12.83,32.32,8,8,8,10,8.31,8,10,8,18.2,18.2,8,10.3,10.3,2.29,2.29,12.3,8,8.23,2.23,2.23,8,8,10,10,10,20,5,5,5,5,8,0,8,2]
[6,8.86,8.86,8.87,8.87,6,8.33,1,2,6,2,3,1,6,3,8,6,6,1,6,8.32,7.32,6,8,6,10,3.31,6,12,6,12.3,12.3,6,11.1,11.1,4.09,4.09,33.1,6,5.16,12.16,2.16,6,6,10,20,30,30,30,30,5,0,6,0,6,5]
[19,31.36,32.36,32.4,34.4,19,32.76,3,4,19,15,16,3,19,9,14,19,19,3,19,31.47,49.96,19,24,19,30,16.62,19,41,19,37.86,37.86,19,33.6,33.6,8.6,8.6,68.7,19,24.26,21.26,11.26,19,19,30,40,50,60,40,40,15,10,19,0,19,12]
What I tried in my main page:
$(document).ready(function(){
$.getJSON("loadchart.php", function(jsonsensor1){
var sensor1 = [$jsonsensor1];
var sensor2 = [$jsonsensor2];
var sensor3 = [$jsonsensor3];
var sensorsum = [$jsonsensorsum];
});
});
Don't use multiple encode/echo calls. This will just create invalid json. Instead put your data into a single container(an object or array) and encode echo that.
For instance using a normal array:
$data = [$jsonsensor1,$jsonsensor2,$jsonsensor3,$jsonsensorsum];
echo json_encode($data);
And on the front end access them accordingly
$.getJSON("loadchart.php", function(data){
//get the arrays based on what position you put them
//in the array in the backend
//change this if you end up using a different container,
//eg php associative array or object
var sensor1 = data[0];
var sensor2 = data[1];
//and so on
});
Replace this code :
echo json_encode($jsonsensor1);
echo json_encode($jsonsensor2);
echo json_encode($jsonsensor3);
echo json_encode($jsonsensorsum);
With this code :
$data=array("jsonsensor1"=>$jsonsensor1,"jsonsensor2"=>$jsonsensor2,"jsonsensor3"=>$jsonsensor3,"jsonsensorsum"=>$jsonsensorsum);
echo json_encode($data);

bad request error in angularjs

var successCallback=function(response) {
if(response.success) {
$log.log(response.data);
alert('fetched courses and percentages successfully');
} else {
}
};
var errorCallback = function(response) {
console.log(response.success);
alert( "failure message: " + JSON.stringify(response));
};
var data = { "mis": 111608059};
// data = JSON.stringify(data),
$http.post('api/stu_course_%.php', data).then(successCallback, errorCallback);
The above code gives the following error:
failure message: {"data":"\n\n400 Bad Request\n\nBad RequestYour browser sent a request that this server could not understand.Apache/2.4.18 (Ubuntu) Server at localhost Port 80\n\n","status":400,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api/stu_course_%.php","data":{"mis":111608059},"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request","xhrStatus":"complete"}
Server-side code in php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'config.php';
function array_push_assoc($array, $key, $value){
$array[$key] = $value;
return $array;
}
$json_request = file_get_contents('php://input');
$request = json_decode($json_request, true);
print_r( $request);
$MIS = $request["mis"];
//$MIS = 111608059;
$data = array();
$result1 = mysqli_query($conn, "select enrolled.course_id, course_code, course_name from enrolled LEFT OUTER JOIN courses ON enrolled.course_id=courses.course_id where MIS='$MIS'");
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)){
$query2 = "select count(course_id) as count from attendance_item group by course_id, MIS having (MIS='$MIS' and course_id='$row[course_id]') ";
$query3 = "select count(course_id) as total_count from lecture group by course_id having course_id='$row[course_id]'";
$result2 = mysqli_query($conn, $query2);
$result3 = mysqli_query($conn, $query3);
$count = mysqli_fetch_assoc($result2);
// print_r ($count);
$total_count = mysqli_fetch_assoc($result3);
// print_r ($total_count);
$percent = $count["count"]/$total_count["total_count"] *100;
// echo $percent;
$data = array_push_assoc($data, $row["course_name"], $percent);
}
// print_r($data);
$success = 1;
json_encode($data);
}
else{
$success = 0;
}
$response = array();
$response["success"] = $success;
$response["data"] = $data;
echo json_encode($response);
?>

Want to get the user info from database , and want to show on calendar

I have php code from this I got complete dates of room that are booked by one user like 12-15.
And 17-18, for second user 20-21, I got marked these dates on calendar.
Now I want to show user info on mouse hover:
<?php
include 'dbconfig.php';
$query_getaway = "SELECT * FROM getaway_table; ";
$result_getaway = $db->query($query_getaway);
$category = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'category')) .'<br>';
$resort = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'resorts')) .'<br>';
if( $category != 0 ){
$query = "SELECT * FROM booking_request where room_id = '$resort' '<br>' ";
$result = $db->query($query);
if( $result -> num_rows > 0 ) {
while( $row = $result-> fetch_assoc() )
{
$name = $row['getaway_name']." <br>";
$start = $row['check_in_date']." <br>";
$end = $row['check_out_date']." <br>";
$guest_n[]= $row['guest_name'];
$guest_number[]= $row['guest_phone'];
$arr1 = range(strtotime($row['check_in_date']),strtotime($row['check_out_date']), "86400");
array_walk_recursive($arr1, function(&$element) { $element = date("j-n-Y", $element); });
foreach ($arr1 as $value)
{
$arr2[]= $value;
}
$arrt= (array_merge($guest_n, $guest_number));
//print_r($arrt);
foreach($arrt as $val)
{
echo $arr_val[]=$val;
}
$arr[]= $value;
}
}
else { echo "select" ;}
?>
Then in js part I showed unavailable dates, bot on hover I'm unable to show user complete info:
<script type="text/javascript">
// Add New Dates and Block Out Booked Days Below
/*var unavailableDates1 = ["20-5-2016", "21-5-2016", "22-5-2016", "23-5-2016", "5-6-2016", "7-6-2016", "8-6-2016",
"15-6-2016", "16-6-2016", "25-6-2016", "26-6-2016", "27-6-2016", "28-6-2016", "14-2-2016",
"15-7-2016", "16-7-2016", "17-7-2016", "18-7-2016", "19-7-2016","20-7-2016","21-7-2016",
]; */
var unavailableDates = <?php echo json_encode($arr2); ?>;
document.write(unavailableDates);
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1 ) + "-" + date.getFullYear();
if($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}else {
this line is showing unavlaible on hover, i want from database user info
return [false, "","unavalible"];
<?php echo $val; ?>
}
}
$(function() {
$("#Datepicker1").datepicker({
numberOfMonths:3,
beforeShowDay: unavailable
});
});
</script>

Retrieving a JSON result

Hi I have used a code snippet from a tutorial for a chat application all of its scripts are working fine but after I tweak it to make the code work based on my requirements almost all of the scripts are working except for retrieving the conversation
The error I'm having is it doesn't retrieve the conversation from my database
here is the modified script
//Create the JSON response.
$json = '{"messages": {';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$json .= '"message":[ {';
$json .= '"id": "0",
"user": "Admin",
"text": "You are not currently in a chat session. <a href="">Enter a chat session here</a>",
"time": "' . date('h:i') . '"
}]';
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$json .= '"message":[ ';
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json .= '{';
$json .= '"id": "' . $message_array['msgid'] . '",
"user": "' . htmlspecialchars($message_array['username']) . '",
"text": "' . htmlspecialchars($message_array['message_content']) . '",
"time": "' . $message_array['message_time'] . '"
},';
}
$json .= ']';
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$json .= '"message":[]';
}
}
//Close our response
$json .= '}}';
echo $json;
Here is the code for calling this script
//Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
getChatText();
}
function handleReceiveChat() {
if (receiveReq.readyState == 4) {
//Get a reference to our chat container div for easy access
var chat_div = document.getElementById('clog');
var response = eval("(" + receiveReq.responseText + ")");
for(i=0;i < response.messages.message.length; i++) {
chat_div.innerHTML += response.messages.message[i].user;
chat_div.innerHTML += ' <font class="chat_time">' + response.messages.message[i].time + '</font><br />';
chat_div.innerHTML += response.messages.message[i].text + '<br />';
chat_div.scrollTop = chat_div.scrollHeight;
lastMessage = response.messages.message[i].id;
}
mTimer = setTimeout('getChatText();',20000); //Refresh our chat in 2 seconds
}
}
Am I missing something here or doing something wrong?
You should rewrite using json_encode:
$messages = array();
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
$message_object = (object) array(
"id"=>"0",
"user"=>"Admin",
"text"=>"You are not currently in a chat session. <a href=\"\">Enter a chat session here</a>",
"time"=>date('h:i')
);
$messages[] = (object) array("message"=>$message_object);
} else {
$con3 = new PDO("mysql:host=". db_host .";dbname=db", db_username , db_password);
$con3->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$con4 = new PDO("mysql:host=". db_host .";dbname=chat_db", db_username , db_password);
$con4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql5 = "SELECT * FROM users WHERE id = :rid LIMIT 1";
$stmt6=$con4->prepare($sql5);
$stmt6->bindValue( 'rid',$_POST['rid'], PDO::PARAM_STR);
$stmt6->execute();
foreach($stmt6->fetchAll()as $res)
{
$usern = $res['username'];
$user_lvl = $res['ulvl'];
}
$comb = $usern . $_POST['name'];
//Validation if msgid exists before creating a new table on the 2nd database
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd . "chat_conversation";
$sql7 = "SELECT msgid, message_content, username , message_time FROM $tblpre WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( ':chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
//Loop through each message and create an XML message node for each.
if(count($message_query) > 0) {
$message_object = (object) array(
"id"=>$message_array['msgid'],
"user"=>htmlspecialchars($message_array['username']),
"text"=>htmlspecialchars($message_array['message_content']),
"time"=>$message_array['message_time'
);
$messages[] = (object) array("message"=>$message_object);
} else {
//Send an empty message to avoid a Javascript error when we check for message lenght in the loop.
$messages[] = (object) array("message"=>array());
}
}
//Close our response
$result = (object) array('messages'=>$messages);
$json = json_encode($result);
echo $json;

XML not parsing in jQuery

When I try to parse my PHP-generated XML file using the jQuery Feeds plugin, it doesn't do what it's supposed to - loop through the template below and output the XML <title> tag in the place of <!=title!>. Instead, it returns just one instance of the template with nothing in place of <!=title!>.
Nothing is returned in the Chrome JavaScript console.
Strangely, I have a similar PHP-generated XML file that works just fine.
Here's the jQuery I'm using:
$('.feed').feeds({
feeds: {
feed1: 'http://www.comfyshoulderrest.com/scrape.php?id=1' // this one doesn't work
},
//max: 3,
loadingTemplate: '<h1 class="feeds-loader">Loading items...</h1>',
entryTemplate: '<div class="item"><div class="image"><img src="images/tie.jpg" style="width: 100%;"></div>' +
'<div class="text"><ul class="list-inline">' +
'<li><span class="price text-warning"><strong>£7.00</strong></span> <span class="text-muted"><strike>£14.00</strike></span></li>' +
'<li class="text-muted"><strong>Topman</strong></li></ul>' +
'<!=title!>' +
'</div></div>'
});
Here's the code that generates the XML file:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country) {
header("Content-Type: application/xml; charset=UTF-8");
$xml = new SimpleXMLElement('<rss/>');
$xml->addAttribute("version", "2.0");
$channel = $xml->addChild("channel");
$channel->addChild("product_url", $product_url);
$channel->addChild("shop_name", $shop_name);
$channel->addChild("photo_url", $photo_url);
$channel->addChild("was_price", $was_price);
$channel->addChild("now_price", $now_price);
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html)) {
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i]
);
$item = $channel->addChild("item");
$item->addChild("product_url", $result['product_url']);
$item->addChild("shop_name", $result['shop_name']);
$item->addChild("photo_url", $result['photo_url']);
}
//print_r($result);
}
else
{
echo "this is empty";
}
echo $xml->asXML();
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result)) {
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location - $row['was_price_location'];
$now_price_location - $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
}
mysqli_close($con);
?>

Categories

Resources