PHP array to seperate JavaScript file via AJAX - javascript

I made a simple php file, that saves data from MySQL db into 2 arrays. I am trying to send these two arrays to the js file (which is on seperate from the html file). I am trying to learn AJAX, but it seems i am not doing something correct.
Can you please explain what am i doing wrong?
My php file: get.php
<?php
define('DB_NAME', 'mouse');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_HOST', 'localhost');
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}else{
echo 'Successfuly connected to database :) <br/>';
}
$sql = "SELECT x, y FROM mousetest";
$result = mysqli_query($link, $sql);
$x_array = [];
$y_array = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "x: " . $row["x"]. " - y: " . $row["y"]. "<br>";
array_push($x_array, $row["x"]);
array_push($y_array, $row["y"]);
}
} else {
echo "0 results";
}
echo json_encode($x_array);
echo "<br>";
echo json_encode($y_array);
mysqli_close($link);
$cd_answer = json_encode($x_array);
echo ($cd_answer);
?>
And this is my JS file:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "get.php",
dataType: "json",
data : {anything : 1},
success:function(data){
var x = jQuery.parseJSON(data); // parse the answer
x = eval(x);
console.log(x.length);
}
});
});
I really hope you understand, what i am trying to do. Where is the problem? I really thought this should work, as i went through it quite a few times to say the least...

You can't use echo json_encode(...) twice. The client expects a single JSON object, not a series of them.
You should make each array an element of a containing array, which you then return as JSON.
$result = array('x' => $x_array, 'y' => $y_array);
echo json_encode($result);
Then in the jQuery code you would use:
var x = data.x;
var y = data.y;
Also, when you use dataType: 'json', jQuery automatically parses the JSON when it sets data. You shouldn't call jQuery.parseJSON() or eval().

Related

How to callback several variables from a page using jquery AJAX

I have spent hours(maybe days) on this problem. I know this question has been asked before but the answers are always so vague for my beginner experience level to understand. I would love some specific and simplified code exampes.
I am submitting an AJAX call to changeDate.php.
index.html
$(document).on("click", "#day-left", function(event){
changeDate = changeDate - 1;
$.ajax({
type: "POST",
url: "changeDate.php",
data: {
amount: changeDate,
loginName: "benjamin_lawson"
},
success: function(data) {
$("#date").html(data);
}
});
});
This page receives the ajax. Using the data it updates SQL and creates 24 variables ($hour1, $hour2, $hour3...) with data.
changeDate.php
<?php
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
$sql = "SELECT `$dateName` FROM `$user` WHERE hour='$x'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
${"hour" . $x} = $row[$dateName];
}
}
}
//this creates 24 variables with all my information I want sent
//through my call back. ($hour1, $hour2, $hour3,...)
How can I pass these variables back to my first page in a callback that keeps the variable name and variable data?
I see a related question to this and they answered with:
RELATED QUESTION AND ANSWER... potential solution
You can return arbitrarily many variables with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in > > your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within > result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
I would really appreciate if someone can show me in code what I need to do to make this work. Thank you so much!
Well every answer is telling to use JSON encode of php. And you required another answers, though theres is already existing a question on that.
Well from php, you can return any data you want. Either you can give a string, or directly HTML or some formatted data like xml or JSON.
Whatever echoed/printed from that request is a response. You can do that request directly from URL or by AJAX. If the request meets the prerequisites, it will show same response.
Now if you just echo any data, there JS no structure and probably you would have to format and parse it to extract meaningful data from it.
But JSON and XML are the know data transport languages. XML is good but needs structuring at server and element based retrieval at client side (there can be many efficient ways which I am unknown to; as I am not a fan of XML). For JSON, you have encode and decode methods at server end and JavaScript is like elder brother to it.
Now how do you form a JSON? You just pass array or object to json_encode and it will return the JSON string. echo that string and your response is ready.
So for I am going to use #Poonam's code; I am making few optimizations also:
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
}
// fill an array from 1 to 24 with steps of 1
// http://php.net/manual/en/function.range.php
$x = range(1, 24, 1);
$sql = "SELECT `$dateName`, hour FROM `$user` WHERE hour IN ('". implode( "', '", $x ) ."')";
$result = $conn->query($sql);
$response_arr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response_arr['hour' . $row->hour] = $row[$dateName];
}
}
echo json_encode($response_arr);
exit(0);
//this creates 24 variables with all my information I want sent
And in the success callback of AJAX, use either JSON.parse() if content type is not mentioned as application/json.
here i use json to encode data .
$.ajax({
type:"POST",
async: false,
url:"finance/getdataq",
dataType: "json",
data: data,
success: function(data){
// you can access your data variables like data['ukeydt'];
$("."+targetval).find('.qrwordfol').html(data['ukeydt']);
$("."+targetval).find('img').attr('src',data['ukeyqr']);
$("."+targetval).show();
return false;
},
error: function (data) {
getd="";
}
});
and in my php code
public function getdataq()
{
$data = array();
$data['ukeydt'] = "this is first";
$data['ukeyqr'] = "this is second";
echo json_encode($data);
exit();
}
You can use an array which will have all values for hours.
In changeDate.php
$amount = $_POST['amount'];
$user = $_POST['loginName'];
//server information variables
$dateName = date("mdY", strtotime("+" . $amount . " day"));
$conn = new mysqli($servername, $username, $password, $dbname);
for ($x = 1; $x <= 24; $x++) {
$sql = "SELECT `$dateName` FROM `$user` WHERE hour='$x'";
$result = $conn->query($sql);
$response_arr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response_arr['hour' . $x] = $row[$dateName];
}
}
}
echo json_encode($response_arr);
exit();
//this creates 24 variables with all my information I want sent
//through my call back. ($hour1, $hour2, $hour3,...)
This $response_arr will have $response_arr['hour1']...$response_arr['hour24'] and you can use this array in your success: function(data)
success: function(data) {
console.log(data);
}
You'll get your whole data in data

Decoding JSON Data from PHP Page Using Jquery

I want to take data from database and save it in an array.
Like this
 var locations = [ ['Current', 18.53515053, 73.87944794, 2],
['VimanNagar', 18.5670762, 73.9084194, 1]
];
First of all I have created a php page
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "citytrans";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM driver_location";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode($row);
}
} else {
echo "0 results";
}
$conn->close();
?>
which gives me below result
{"driver_id":"1","driver_lat":"18.53515053","driver_lng":"73.87944794","driver_code":"122"}{"driver_id":"2","driver_lat":"18.53640175","driver_lng":"73.88206482","driver_code":"133"}
Now I want to convert this into an array using Jquery (I want to decode it ), I just want drivers_lat and drivers_lng value from my jSON data fetched form the database show above.
I am using below code to parse the data form json
jQuery.ajax({
url: baseurl + "getdriverlocation.php",
type: "JSON",
async: false,
success: function(data){
var myArray = JSON.parse(data);
console.log(myArray.driver_lat)
}
});
but it is giving me error (shown below)
SyntaxError: JSON.parse: unexpected non-whitespace character after
JSON data at line 1 column 92 of the JSON data
I just want the two values from json data and save it in an array variable
Please help
Use this one..
jQuery.ajax({
url: baseurl + "getdriverlocation.php",
type: "JSON",
async: false,
success: function(data){
var myArray = jQuery.parseJSON(data);// instead of JSON.parse(data)
jQuery(myArray).each(function( index, element ) {
console.log(element.driver_lat)
});
}
});
In your php you should do :
if ($result->num_rows > 0) {
// output data of each row <- no, build your data, then make only 1 output
$output = array();
while($row = $result->fetch_assoc()) {
$output[] = $row;
}
echo json_encode($output);
}
Then in your jQuery, parse the whole json-decoded array...
Your json data is invalid.
You must put comma bettween two JSON Objects
Your respons must be
{"driver_id":"1","driver_lat":"18.53515053","driver_lng":"73.87944794","driver_code":"122"},
{"driver_id":"2","driver_lat":"18.53640175","driver_lng":"73.88206482","driver_code":"133"}
As i identified your Response JSON format is invalid, response JSON format should like this in order to parse into JSON via JSON.parse()
[{"driver_id":"1","driver_lat":"18.53515053","driver_lng":"73.87944794","driver_code":"122"},
{"driver_id":"2","driver_lat":"18.53640175","driver_lng":"73.88206482","driver_code":"133"}]
Try this
$arrTmp = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$arrTmp[] = $row;
}
}
echo json_encode($arrTmp);
And maybe the jQuery tools bellow for old browsers
$.parseJSON(data);

Using json_encode without displaying it on my webpage via echo or print

basically I'm trying to pass an array from PHP to JavaScript, so far it is all working the methods I'm using are:
PHP:
echo json_encode($arrayname);
JavaScript:
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
Obviously this echo's the text onto my webpage but I do not want this text to be displayed, I'm just wondering if there is anyway for me to use this without having a chunky array at the top of my webpage. (I tried it without the echo and it doesn't work, I've also gone through countless tutorials on this but no one seems to do it without using echo)
Thanks a lot in advance
---------- Edit -------------
index.js
$.getJSON( 'myphppage.php', {}, function(data){
// I loop through the data here
}
}).done(function() {});
myphppage.php
<?php
$servername = "name";
$username = "username";
$password = "";
$dbname = "dbname";
$connection = mysql_connect($servername,$username);
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
$result = mysql_query("select * FROM tablename");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$array= array();
while($row = mysql_fetch_array($result)) {
array_push($array, $row);
}
echo json_encode($array);
}
Minimal example:
index.html
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
myphpwebpage.php
echo json_encode($arrayname);

PHP populate drop box with jquery

I have a script which fetches options from a script php to populate a drop down list on the main page.
Here's the javascript
<script>
//# this script uses jquery and ajax it is used to set the values in
$(document).ready(function(){
//# the time field whenever a day is selected.
$("#day").change(function() {
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
dataType : 'json'
success: function(data) {
//# $("#time").html(data);
var option = '';
$.each(data.d, function(index, value) {
option += '<option>' + value.timing + '</option>';
});
$('#timing').html(option);
}
});
});
});
</script>
Here's the php script which gets data from a database.
<?php
$con = mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$doctor = $_POST['doctor'];
$day = $_POST['day'];
$query = "SELECT * FROM schedule WHERE doctor='" .$doctor."'AND day='" .$day. "'";
$result = mysqli_query($con, $query);
//$res = array();
echo "<select name='timing' id='timing'>";
//Initialize the variable which passes over the array key values
$i = 0;
//Fetches an associative array of the row
$row = mysqli_fetch_assoc($result);
// Fetches an array of keys for the row.
$index = array_keys($row);
while($row[$index[$i]] != NULL)
{
if($row[$index[$i]] == 1) {
//array_push($res, $index[$i]);
json_encode($index[$i]);
echo "<option value='" . $index[$i]."'>" . $index[$i] . "</option>";
}
$i++;
}
echo json_encode($res);
echo "</select>";
?>
It's not working. I get an error from console saying missing '}' in javasrcipt on line
$("#day").change(function(){
I can't seem to find an error either.
You need to add a comma on the line above the one triggering the error :
dataType : 'json',
It's because you don't have a comma on the line above it...
It's hard to say where is problem, because you mixed things together. On Javascript side you expect JSON but on PHP side you generate HTML.
Use JSON for sending data between server and browser. Ensure that you actually generate valid JSON and only JSON.
This line does nothing (function returns value, but not modifies it)
json_encode($index[$i]);
This line does not make sense - variable $res is not initialized;
echo json_encode($res);

Json Encode Issue

I have a PHP file using json_encode to make a single call, but it does not go to the javascript... I have been trying for over a week... Maybe it is right in front of my face and I don't see it, so I will post it here to have a second set of eyes to maybe see what I don't... Does anyone see a problem, as I really dont...
Here is the json_encode getting the 3 array to make 1 call to the javascript...
$outarr['dayPowerP'] = $dayPowerP;
$outarr['monthPowerP'] = $monthPowerP;
$outarr['yearPowerP'] = $yearPowerP;
echo json_encode($outarr);
Here is the output of the php file... The ID's and the values from the sql are right there....
{"dayPowerP":["13.2470"],"monthPowerP":["193.6810"],"yearPowerP":["989.6720"]}
Here is the ajax showing the post and Json...
$(document).ready(function () {
$('#datepicker').datepicker({maxDate: 0, dateFormat: 'yy-mm-dd', onSelect: function(dateText) {
var myDate = $(this).datepicker('getDate');
$('#apDiv1').html($.datepicker.formatDate('DD, d', myDate));
$('#apDiv5').html($.datepicker.formatDate('MM', myDate));
$('#apDiv7').html($.datepicker.formatDate('yy', myDate));
$.ajax({
type: "POST",
url: "clickdates.php",
data: {choice: dateText},
dataType: "json",
success: function(json_data) {
$('#apDiv2').html(json_data['dayPowerP']).show();
$('#apDiv6').html(json_data['monthPowerP']).show();
$('#apDiv8').html(json_data['yearPowerP']).show();
}
})
}});
});
To make it really clear... here is the full PHP file.
<?php
$choice = (isset($_POST['choice'])) ? date("Y-m-d",strtotime($_POST['choice'])) : date("Y-m-d");
$con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE date = '".$choice."' group by date"; $res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$dayPowerP = array( $row['choice']);
?>
<?php
$choice = (isset($_POST['choice'])) ? date("m",strtotime($_POST['choice'])) : date("m");
$con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE month(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$monthPowerP = array($row['choice']);
?>
<?php
$choice = (isset($_POST['choice'])) ? date("Y",strtotime($_POST['choice'])) : date("Y"); $con = mysql_connect("localhost","root","xxxxxx");
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("inverters", $con);
$sql = "SELECT sum(power/1000) AS choice FROM feed WHERE year(date) = '".$choice."'";
$res = mysql_query($sql) or die('sql='.$sql."\n".mysql_error());
$row = mysql_fetch_assoc($res);
$yearPowerP = array( $row['choice']);
?>
<?php
$outarr['dayPowerP'] = $dayPowerP;
$outarr['monthPowerP'] = $monthPowerP;
$outarr['yearPowerP'] = $yearPowerP;
echo json_encode($outarr);
?>
This is not complex code, so there has to be something minor I am not seeing or doing.
Thanks
Alan
Mate. Json_encode doesn't support associative arrays.
"json_data['dayPowerP']" won't work.
json_data.dayPowerP
should work, it looks like that will return an array, so you need to typecast that to a float.
Can you please post the result of this: (see the console)
** console.log(json_data);**
specifically
success: function(json_data) {
console.log(json_data)
$('#apDiv2').html(json_data['dayPowerP']).show();
$('#apDiv6').html(json_data['monthPowerP']).show();
$('#apDiv8').html(json_data['yearPowerP']).show();
}
If i'm right, then you should replace json_data['dayPowerP'] with json_data.dayPowerP[0]
in the success function and all should work correctly.
There's no need to put each individual element in its own array; just embed them directly.
Use this:
$('#apDiv2').html(json_data.dayPowerP[0]).show();

Categories