How to callback several variables from a page using jquery AJAX - javascript

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

Related

Json dynamic display vs server ressources

I'm aiming to display dots with javascript by their coordinates. Each person click on an image, (X,Y) will be stored in the database. On the same image will be displayed all dots, when a person is visualing the image with dots and another person will submit new dot, this last will appears because array_x and array_y tabs will be refreshed every 1s.
The question is : is it the best way in terms of using server ressources of doing that ? suppose i've 1000 persons that will participate to this study, that signify that for one person there is at least one request every 1s. Suppose that one person will spend 30s, that will be a huge amount of requests.
I am afraid to have a server breakdown due to multiple requests. Is it a way more guaranteed than this one ?
My js :
window.setInterval(loadNewPosts, 1000); //load simultaneous choice in 1 second
function loadNewPosts(){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "latest.php",
data: "current_id=" + current_id +"&nextType=" + nextType,
success: function(data) {
for (var i = 0; i < data['array_x'].length; i++) {
array_x.push(data['array_x'][i]);
array_y.push(data['array_y'][i]);
}
}
});
}
my php latest.php :
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$current_id = intval($_GET['current_id']);
$Type = (string)$_GET['nextType'];
$sql = "SELECT * FROM `table` WHERE id > $current_id and Type='".$Type."'";
$result = mysqli_query($conn, $sql);
$array_x= [];
$array_y= [];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($array_x,$row["X"]);
array_push($array_y,$row["Y"]);
}
} else {
echo "";
}
mysqli_close($conn);
// return the posts as a JSON object
header('Content-Type: application/json');
$data=array(
'array_x' => $array_x,
'array_y' => $array_y
);
echo json_encode($data);

PHP array to seperate JavaScript file via AJAX

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().

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

my ajax call is returning html with json data

I am having a weird problem, I am trying to populate the datatable using ajax call to my php program which internally gets data from database.
php:
<?php
require_once('config.php');
$query = mysql_query("select * from productdetails");
while($fetch = mysql_fetch_array($query))
{
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5]);
}
echo json_encode($output, JSON_FORCE_OBJECT);
?>
Html(ajax call):
$.ajax({
url: 'process.php?method=fetchdata',
data: "json",
success: function(s){
console.log($(s).text());
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
This generates the output as
( ! ) Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in C:\wamp\www\datatableone\process.php on line 2
Call Stack
#TimeMemoryFunctionLocation
10.0010242552{main}( )..\process.php:0
20.0010242840http://www.php.net/function.mysql-connect' target='_new'>mysql_connect
( )..\process.php:2
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
But my required output should be: (only json)
{"0":{"0":"1","1":"Iron","2":"AX12","3":"Google","4":"21.95","5":"HW"},"1":{"0":"2","1":"DartBoard","2":"AZ52","3":"Apple","4":"12.95","5":"SG"},"2":{"0":"3","1":"BasketBall","2":"BA74","3":"Microsoft","4":"29.95","5":"SG"},"3":{"0":"4","1":"Compopper","2":"BH22","3":"Google","4":"24.95","5":"HW"},"4":{"0":"5","1":"Gas
Grill","2":"BT04","3":"Apple","4":"149.95","5":"AP"},"5":{"0":"6","1":"Washer","2":"BZ66","3":"Google","4":"399.99","5":"AP"}}
any suggestions please.
Thanks
Sai
Solution:
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
try {
$conn = new PDO("mysql:host=$servername;dbname=holt", $username, $password);
$statement=$conn->prepare("SELECT * FROM productdetails");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);
echo $json;
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Thanks for suggestions.
As noted in the comments, you should turn off warnings, or better yet, write your code in a manner that doesn't produce warnings.
On turning off warnings:
Turn off warnings and errors on php/mysql
You can suppress errors inline with the # symbol, which is the error control operator in php. Putting # at the beginning of your mysql_connect() line should get rid of it, but you should switch to PDO!
On PDO (which I recommend and use):
http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
PDO protects you against SQL injection and allows queries to be sent to the database and constructed beforehand, and you send the inputs afterwards via "placeholders".

Access DB from html file via custom PHP file

Right now I have working a DB connection to mysql. The html -> PHP -> query -> data reception works. I show the relevant code:
From the html file matters:
d3.json("http://path/file.php", function(error, data) {
console.log (data);
});
file.php:
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "select * from `mytable`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
What I want is to have only 1 .php file instead of 1 php file for every query. That means I need to send from the html a variable inputquery to the php file. I've tried several things such as changing:
`$myquery = "select * from `mytable`; into `$myquery = inputquery`;
And I think that the wrong point is the definition of the function that requests the data from the DB. What I tried (wrong, the following code does not work as expected):
var inputquery = "select * from `mytable`"
d3.json("http://serverhost/path/file.php", function(error, data) {
console.log (data);
});
Maybe this is not working because I am not telling the function I want as an input to the .php file the variable inputquery. I tried to put it inside the function, but got "data is not defined" errors, so I think it is not worth it to show the wrong code.
How can I input that var inputquery to the .php file? It could not be the way I planned it.
Thank you
You have to send the inputquery variable with the http request as POST data,
then in you php file you can do :
$myquery = $_POST['inputquery'];
You surely will find some documentation about sending post data with the request you're sending.
The simplest way is using get parameter in d3.json:
var yourparam = 'mytable';
d3.json("http://path/file.php?query=" + yourparam, function (error, json) {
...
});
You can retrieve the variable from the $_GET array.
Finally don't put mysql commmands into your js, and don't use mysql library. It's very dangerous.
This is a very bad idea, since you become very vulnerable to SQL Injection, even so I will try to help you
I assume you have JQuery if you have so
you can do the following
html.file
var inputquery = "select * from `mytable`";
$.post("relative/path/to/file.php",
{query : inputquery},
function (data) {
alert(data); // See output
},'json);
file.php
<?php
$username = "myusername";
$password = "mypassword";
$host = "myhost";
$database="myDB";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = $_POST['query'];
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>

Categories