Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Basically I want to query MySQL database using an external PHP script. I want this script to be called every 2 seconds. This 2 seconds interval are initiated with a javascript (jquery, flot), which is as follows:
<script type='text/javascript'>
var data = [];
var dataset;
var totalPoints = 50;
var updateInterval = 1000;
var now = new Date().getTime();
function GetData() {
data.shift();
while (data.length < totalPoints) {
var y;
$.ajax({
url: 'current_api.php',
success: function(currentValue){
y = currentValue;
console.log(y);
},
});
var temp = [now += updateInterval, y];
data.push(temp);
}
}
var options = {
...
}
$(document).ready(function () {
GetData();
dataset = [
{ label: "CURRENT READING", data: data }
];
$.plot($("#flot-line-chart"), dataset, options);
function update() {
GetData();
$.plot($("#flot-line-chart"), dataset, options)
setTimeout(update, updateInterval);
}
update();
});
</script>
Currently, Im getting a NULL value at console.log(y);. My PHP script (current_api.php) that handles MySQL queries is as simple as follows:
<?php
require "dbCon.php"; // database credentials
$databaseName = "MAIN";
$tableName = "day"
// OPEN MYSQL DATABASE CONNECTION IN PHP
$dbs = mysql_select_db($databaseName, $con);
// FETCH DATA FROM MYSQL DATABASE
$sql = "SELECT value FROM $tableName ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql);
header('Content-Type: application/json');
while ($row = mysql_fetch_assoc($result)) {
$currentValue = (int) round($row['value']);
}
echo json_encode($currentValue);
// CLOSE THE DB CONNECTION
mysql_close($con);
?>
I'm new with AJAX and does not know if what I'm trying to do is possible. Can someone help me to debug why i'm getting a NULL value? Thanks in advance.
You are calling current_api.php in your ajax script without any data. So there is no query string, no $_GET['dbSelect'] and no database. So your json contains only an undefined variable, NULL.
Apart from that this is not correct, you cannot use escaping functions to clean up a user-provided table name, you need to check it against a whitelist.
Got it!
the problem is the declaration of variable y and the url in $.ajax. All thanks to barmar and jeroen for the hints!
The javascript should be:
<script type='text/javascript'>
var data = [];
var dataset;
var totalPoints = 50;
var updateInterval = 1000;
var now = new Date().getTime();
var y;
function GetData() {
data.shift();
while (data.length < totalPoints) {
$.ajax({
url: 'current_api.php?dbSelect=R9640E5F1E2',
success: function(currentValue) {
y = currentValue;
console.log(currentValue);
},
});
var temp = [now += updateInterval, y];
data.push(temp);
}
}
var options = {
...
}
$(document).ready(function () {
GetData();
dataset = [
{ label: "CURRENT READING", data: data }
];
$.plot($("#flot-line-chart"), dataset, options);
function update() {
GetData();
$.plot($("#flot-line-chart"), dataset, options)
setTimeout(update, updateInterval);
}
update();
});
</script>
where R9640E5F1E2 is the database; and the PHP stays as is. :)
Now.. move on to another problem... Query strings inside javascripts.
$.ajax({
dataType: "json",//insert line: receive data from server to json
url: 'current_api.php?dbSelect=123', //a method
/* a method other
type:"GET",
data:{dbSelect:dbSelect},
url: 'current_api.php',
*/
success: function(currentValue){
y = currentValue[0];///edit code y = currentValue
console.log(y);
},
});
Related
<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have this small project, and I'm trying to get the variables to my js file using ajax.
This is my js file:
function get_sites() {
$.ajax({
method: "POST",
url: "server/newEmptyPHP1.php",
dataType: "json",
data: {type: "tasks"},
success: function (data) {
}
});
}
and this is my PHP file:
if (isset($_POST["type"])) {
$type = $type = $_POST["type"];
$returned_value = ""; //default value
switch ($type) {
case "tasks":
$returned_value = display_tasks($conn);
break;
}
$conn->close();
echo $returned_value;
}
function display_tasks($conn) {
$query = "SELECT * FROM `Site`;";
$result = mysqli_query($conn, $query);
$html = "";
$final_result = array();
if ($result) {
$row_count = mysqli_num_rows($result);
for ($i = 0; $i < $row_count; ++$i) {
$row = mysqli_fetch_array($result);
$task = array("id" => $row["ID"], "av" => $row["availability"], "lng" => $row["lng"], "lat" => $row["lat"]);
$final_result["Site"][] = $task;
}
}
print_r(json_encode($final_result));
return json_encode($final_result);
}
The output:
{"Site":[{"id":"1","av":"1","lng":"16.963777","lat":"42.548664"},{"id":"2","av":"0","lng":"16.96376","lat":"42.548685"}]}
As you can see, this is the array I get from that PHP file, but I can't handle it well, so how can I get a variable in my js file from the previous array?
You can try JSON decode. Or for getting data in response you have to something like below:
...
success: function (data) {
jQuery.each(data, function () {
console.log(this);
jQuery.each(this, function () {
console.log("av=" + this.av + " --> id=" + this.id + " --> lat=" + this.lat + " --> lng=" + this.lng);
});
});
}
...
One approach using direct reference
JavaScript doesn't compulsorily require decoding json data as it can access the json data using direct object reference.
var data = {"Site":[{"id":"1","av":"1","lng":"16.963777","lat":"42.548664"},{"id":"2","av":"0","lng":"16.96376","lat":"42.548685"}]};
console.log(data.Site);
console.log(data.Site[0]);
console.log(data.Site[1]);
console.log(data.Site[0].id);
console.log(data.Site[0].av);
console.log(data.Site[0].lng);
console.log(data.Site[0].lat);
var data = data.Site; // you can avoid use capitals as in your output `Site`
for ( var i = 0 ; i < data.length ; i++){
var d = data[i];
console.log('--------------------------');
console.log(d);
console.log(d.id);
console.log(d.av);
console.log(d.lng);
console.log(d.lat);
}
Its also supported without jQuery
This is my first post in stackoverflow. I have always got my answers from previously posted questions. This problem has been bugging me and all the solutions I tried have not worked.
I have a js function which makes an ajax request to get weather info of town passed:
var _getWeatherInfo = function(ntown){
var town = ntown;
var url = "PHP/weather.php?town=" + town;
request1.onreadystatechange = _refreshWeatherList();
request1.open("GET", url, true);
request1.send("");
}
I am using the following php code to return the sql results stored in array:
<?php
//Connection to the database
$mysql = mysql_connect("localhost","xuvaz","x");
//Selecting Database
$db = mysql_select_db("weather");
$town = $_GET['town'];
$tarray = array();
$sql1= mysql_query("SELECT * FROM weather WHERE town='$town'");
while($row = mysql_fetch_assoc($sql1)) {
$tarray = array('town' => $row['town'],'outlook' => $row['outlook']);
}
echo json_encode($tarray);
?>
Then I have a function that is called when the request is completed:
var _refreshWeatherList = function() {
var weather_info = request1.responseText;
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();
}
The problem is I cant access the array values.
I can see the values as {"town":"Christchurch","outlook":"fine"} in firebug under response.
Even when I use JSON parse it gives error in the firebug , JSON.parse: unexpected end of data. If
I can just access the data my whole project would be completed.
Your PHP code is returning an object (last row from your loop) rather than an array of objects, but your JavaScript is expecting an array.
Change your PHP to the following to appand to $tarray:
while($row = mysql_fetch_assoc($sql1)) {
$tarray[] = array('town' => $row['town'],'outlook' => $row['outlook']);
}
Your JavaScript needs to wait for readyState = Loaded and JSON-decode the responseText:
var _refreshWeatherList = function() {
if(request1.readyState == 4) {
var weather_info = JSON.parse(request1.responseText);
....
}
}
If the parse is failing, trying logging it to the console to make sure the PHP isn't returning extra characters.
var _refreshWeatherList = function() {
var weather_info = eval("("+request1.responseText+")");
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();}
'request1.responseText' must be 'object' use eval() --! my english not well
Thank you for all your help. I found the fault. I forgot to include these two lines.
if (request1.readyState == 4) {
if (request1.status == 200){
I know this question has already been asked a few times, but I'm trying to use javascript with php. I have a file called parsing.php that parses through a xml feed and converts the metadata into JSON Object called "data". The parsing is done using ajax calls with JavaScript and JQuery.
<script src="json2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
category.videos.push(video);
}
data.categories.push(category);
}
});
window.data = JSON.stringify(data);
<script>
"<?php
$dataVar = ?> <script type=text/javascript>window.data</script><?php;?>"
"<?php
print_r($dataVar,true);
?>"
The only reason why I need to use javascript and php is because I want to use the "print_r()" function from php which allows me to return the information rather than just printing it to the screen, but unfortunately I can't get it to work. If anybody knows of other alternative or could give some advice that would be greatly appreciated.
Here is what I believe you are trying to achieve, written in PHP:
$dom = new DOMDocument();
$dom->load("fakeFeed.xml");
$data = ["categories"=>[]]; // may need to use array() instead of [] depending on PHP version
foreach($dom->getElementsByTagName('item') as $item) {
$name = trim($item->getElementsByTagName('category')->item(0)->textContent);
if( !isset($data['categories'][$name])) {
$cat = ["name"=>$name,"videos"=>[]]; // again, adjust if you're on an older version
// I'm not entirely sure what you're trying to achieve on this part.
// you seem to be getting the same video five times...
// revise your approach, comment if needed, and I can try to help
// for now, "insert code here"
$data['categories'][$name] = $cat;
}
}
// we were using the name as a key for simplicity, now just take the values
$data['categories'] = array_values($data['categories']);
// done! $data now has your data.
var_dump($data);
If you really want to use this instead of using document.log for JS:
$.ajax({
type: "POST",
url: "some_php.php",
data: JSON.stringify(data);
})
.done(function( msg ) {
document.write(msg);
});
and the some_php.php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);