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);
Related
<script type="text/javascript">
$(document).ready(function(){
//fill data to tree with AJAX call
$('#tree-container').jstree({
'plugins': ["wholerow", "checkbox"],
'core' : {
'data' : {
"url" : "response.php",
"dataType" : "json" // needed only if you do not supply JSON headers
}
}
})
});
</script>
<div id="tree-container"></div>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "defectsystem";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM `treeview_items` ";
$res = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn));
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_assoc($res) ) {
$data[] = $row;
}
$itemsByReference = array();
// Build array of item references:
foreach($data as $key => &$item) {
$itemsByReference[$item['id']] = &$item;
// Children array:
$itemsByReference[$item['id']]['children'] = array();
// Empty data class (so that json_encode adds "data: {}" )
$itemsByReference[$item['id']]['data'] = new StdClass();
}
// Set items as children of the relevant parent item.
foreach($data as $key => &$item)
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
$itemsByReference [$item['parent_id']]['children'][] = &$item;
// Remove items that were added to parents elsewhere:
foreach($data as $key => &$item) {
if($item['parent_id'] && isset($itemsByReference[$item['parent_id']]))
unset($data[$key]);
}
// Encode:
echo json_encode($data);
?>
I had successfully create a jstree with checkbox. However, how I can insert the checkbox value into the database when I click it and submit.
Thankss if anyone could help me!! If any question can ask me below comment.
Try some thing like this:
var array = [];
// create an array
$.each($("input[name='user_permission']:checked"), function(){
permissions.push($(this).val());
});
// Iterate over each checkbox which is checked and push its value in the array variable.
Ex:
......
var permissions = [];
$.each($("input[name='user_permission']:checked"), function(){
permissions.push($(this).val());
});
$.ajax({
url : 'add_permission.php',
method : 'post',
data :
{
permissions : JSON.stringify(permissions)
}
....
});
// After complete iteration you will get the value of each checked checkbox.
Now insert it in database using ajax call
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
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);
I am not sure if this is possible, but I am looking for a way to save the entire state of my webpage without explicitly saving each element to a database.
For example, I dynamically create buttons, checkboxes, text etc. until the webpage looks as it needs. Can I save the DOM as a string, or blob in a database, and parse it later the get the webpage back?
I have tried things like:
var doc = document.documentElement.outerHTML;
Then save the string to database but it doesn't work.
I am using an AJAX call to a PHP script to write to mysql:
jQuery.ajax({
type: "POST",
url: 'connect/database.php',
dataType: 'json',
data: {functionname: 'connect_to_database', arguments: [user_id, user, doc] },
success: function (obj, textstatus) {
if( !('error' in obj) ) {
}
else {
console.log(obj.error);
}
}
});
PHP looks like:
// connection script
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$user_id = $_POST['arguments'][0];
$user = $_POST['arguments'][1];
$string = $_POST['arguments'][2];
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table (user_id, user, string) VALUES ('$user_id', '$user', '$string')";
# $sql = "UPDATE crows_nest SET json_string='$configuration' WHERE user = '$user'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Use a prepared statement to prevent problems with special characters in the document string.
$stmt = $conn->prepare("INSERT INTO table (user_id, user, string) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $user, $string);
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
so I currently have this PHP script to get the Youtube IDS set in a mySQL database. This PHP script lists all the Youtube ID's in the database.
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "songrequests";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "song: " . $row["link"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Ok, and after that, I found this script that pushes Youtube IDs to a playlist, this is found here on jsFiddle (Full demo here)
So basically, what I am trying to achieve is to push the IDs from my database to the list. I created a json which lists all of the IDs here
With this ajax I'm trying to push the ID's from the json to the list, but it does not seem to work.
JS
$.ajax({
url: 'http://dj.aotikbot.tv/songlist.php',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data.songs.length);
if (data.songs.length != 0) {
for (var x = 0; x < data.songs.length; x++) {
ytplayer_playlist.push("'" + data.songs[x].link + "'");
}
}
},
error: function() { console.log('Uh Oh!'); },
});
If you need more info on what I'm trying to do, let me know. Thanks in advance.
So, based on our chat, JSONP is what you went after. The code below should work. Take a look.
var playlist = [];
$.ajax({
url: 'http://dj.aotikbot.tv/songlist.php?callback=?',
type: 'GET',
async: false, //evil, but you needed this!
dataType: 'json',
success: function(data) {
if (data.songs.length > 0) {
$.each(data.songs, function() {
playlist.push(this.link);
});
}
console.log("Here is your playlist");
console.log(playlist);
},
error: function() { console.log('Uh Oh!'); }
});