PHP - Javascript result inside MySQL - javascript

I don't understand why every column has good results but the screen column has code inside and not the actual SCREEN SIZE (result of the code).
<?php
#$data = $_SERVER['HTTP_USER_AGENT']."|";
#$data.= $_SERVER['HTTP_CF_CONNECTING_IP']."|";
$width = " <script>document.write(screen.width); </script>";
$height = " <script>document.write(screen.height); </script>";
$data.=$width;
$data.=$height;
$finz = explode("|",$data);
$ag = $finz[0];
$ip = $finz[1];
$sc = $finz[2];
$query1 = $db->prepare("INSERT INTO `checks` (user,type,ip,screen,agent) values (:user,:type,:ip,:screen,:agent)");
$query1->execute(array(
'user' => $USER['username'],
'type' => 'Red Flower',
'ip' => $ip,
'screen' => $sc,
'agent' => $ag
));
$row2 = $query->fetch();
?>
Can somebody tell me how to make the code insert the values of the JavaScript output without using POST AJAX/JQuery etc?

The embedded JavaScript won't be evaluated until your template reaches the client. It's not something the PHP interpreter understands. It's just a string. You have to execute this code in JavaScript and send it back to the server, there's no other way.
You will need to send a request back to the server containing the results of the evaluated JavaScript before performing the query against your database.
I realize this is something you were trying to avoid.

Related

send data from php array in javascript forEach loop to url of ajax call

I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.

I know why I am getting unexpected { token but I don't know how to fix it when my php needs to send collection of datas to javascript

I am using this javascript fetch code to get data from php
async sendRequest(selectValue=this.selectValue){
const fetchResponse = await fetch('/server/getLastWords.php?select='+selectValue);
const fetchJSON = await fetchResponse.json();
await console.log(fetchJSON);
}
this is php code which communicates with MYSQL and sends data to javascript
<?php
header('Content-Type: application/json');
include 'db/db_connection.php';
$mysqli = new mysqli('localhost','root','','worddb');
if(connectDB($mysqli)){
$mysqliQuery = "SELECT * FROM wordlist ORDER BY wordIndex DESC LIMIT ?";
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($mysqliQuery)){
print "Failed to prepare statement\n";
}else{
$stmt->bind_param("i", $_GET['select']);
$stmt->execute();
$result = $stmt->get_result();
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
}
}
?>
and this php returns
{"wordIndex":94,"english":"seemingly","korean":"\uc678\uacac\uc0c1\uc73c\ub85c,
\uac89\ubcf4\uae30\uc5d0\ub294","swedish":"till synes","synonyms":"apparently","example":"Seemingly,
he borrowed the money from the bank"}
{"wordIndex":93,"english":"evade","korean":"\ud53c\ud558\ub2e4,
\ud68c\ud53c\ud558\ub2e4","swedish":"undvika","synonyms":"elude, evoid","example":"He is using the
same tactics of distract and evade as the Chancellor used during his speech"}
{"wordIndex":92,"english":"eclipse","korean":"\uac00\ub9ac\ub2e4, \ube5b\uc744
\uc783\uc74c","swedish":"f\u00f6rm\u00f6rka","synonyms":"blocking, beating","example":"Her work was
in eclipse for most of the 20th century"}
{"wordIndex":91,"english":"impede","korean":"\uc9c0\uc5f0\uc2dc\ud0a4\ub2e4",
"swedish":"f\u00f6rhindra","synonyms":"delay, hinder","example":"This will impede learning,
essentially causing more problems than solutions"}
{"wordIndex":90,"english":"exposure","korean":"\uc704\ud5d8\uc5d0 \ub178\ucd9c,
\ud3ed\ub85c","swedish":"exponering","synonyms":"subjection, uncovering","example":"God knows you
probably saved my life, at least from exposure or pneumonia"}
I know it shows unexpected token { because php is returning multiple json object because
when I did echo just one json object it works fine.
$resultJSON;
foreach($result as $resultArray){
$resultJSON =json_encode($resultArray);
}
echo($resultJSON);
but my php needs to send all items ,but I don't know how to do that because console shows unexpected token {}
I read this post before posting my question
Why am I getting unexpected '}'?
but solution in this post was to add semicolon, but I have semicolons in my code..
Transform your results in an array :
$resultJSON = array();
foreach($result as $resultArray){
$resultJSON[] = $resultArray;
}
Then output the array :
echo json_encode($resultJSON);
It goes wrong here:
$resultJSON;
foreach($result as $resultArray){
$resultJSON = json_encode($resultArray);
echo $resultJSON;
}
You output:
echo json1;
echo json2;
echo json3;
However, on the clientside the output is collected and treated as one json. So javascript will work with json1json2json3. And that's not a valid json.
If you don't have to do anything else then sending the result back
echo json_encode($result);
would do.

Can't select specific element in JSON parsed array with JavaScript

So I have a mySQL database and I am pulling data from it to my website and want to change content with the help of JavaScript. The problem is that I can't seem to select specific elements out of my data which I received from the databse.
Here is how I pull data and parse it into a JSON string:
while($row = $result->fetch_assoc()) {
$return_array = array("region" => $row['region'], "capital" => $row['capital'], "surface_area" => $row['surface_area'], "land_area" => $row['land_area'], "water_area" => $row['water_area'], "global_area_rank" => $row['global_area_rank'], "land_boundary" => $row['land_boundary'], "bordering_countries" => $row['bordering_countries'], "coastline" => $row['coastline'], "climate" => $row['climate'], "terrain" => $row['terrain'], "avg_elevation" => $row['avg_elevation'], "highest_elevation" => $row['highest_elevation'], "lowest_elevation" => $row['lowest_elevation'], "natural_resources" => $row['natural_resources'], "land_use" => $row['land_use'], "irrigated_land" => $row['irrigated_land'], "natural_hazards" => $row['natural_hazards']);
}
echo json_encode($return_array);
In my JavaScript method I call this PHP script and receive the parsed JSON string which I temporarily output in a single div:
$.post('ajax/retrieve_data.php', { sel1: sel1, sel2: sel2 }, function(data) {
var return_array = $.parseJSON(data);
$('div#test-div').text(return_array.region);
});
The output however, just shows the entire JSON string with curly brackets and all identifiers, which means that the return_array.region selector does not work. I tried it with indices and all sorts of other syntax, but it did not work. Everywhere on the internet everyone uses this syntax to select specific elements, but it somehow doesn't work. I probably have a very stupid error in there, but I appreciate every help. I just can't seem to see the error.
My guess is that your PHP script isn't returning data with the proper Content-Type header. Make sure, in your PHP script, you run the following:
header('Content-Type: application/json');
This must come before echoing anything.

PHP Query Returning the Same Data Even Though It Changes

I am trying to loop through data to make a chat system.
I have made a php function:
function getLatestMessageTime() {
$handler = new PDO('mysql:host=localhost;dbname=*****', '******', '*******');
// Set the query \\
$query = $handler->query('SELECT `time` FROM `messages`');
// Loop through the data \\
$latestTime = 0;
while ($row = $query->fetch()) {
if ($row['time'] > $latestTime) {
$latestTime = $row['time'];
};
};
// Return the latest message time \\
Return $latestTime;
}
And I set my looping jQuery code:
var latestTime = <?php echo getLatestMessageTime(); ?>;
latestTimeLoop();
function latestTimeLoop() {
if (latestTime < <?php echo getLatestMessageTime(); ?>) {
$("#container").load('ajaxLoad.php?time='+latestTime);
};
document.log(latestTime + " - " + <?php echo getLatestMessageTime(); ?>);
setTimeout(latestTimeLoop, 200);
}
But when I change the time in phpMyAdmin to be much higher than the rest of the data, it doesn't update in my console.logs. It seems like my query isn't occuring more than once within my function, it only grabs the data once instead of requesting it each time my javascript code loops.
Is there any way to reset the query each time to it grabs new info each loop?
View Full Code
use ORDER BY in your query and also limit the query to one.
$query = $handler->query('SELECT `time` FROM `messages` ORDER BY `time` DESC LIMIT 1');
Only last record details is needed to get the latest message time. thats why i said to use limit and modify php code according to it.

Storing a value changes in the DB

<?php
$id = rand(10000,99999);
$shorturl = base_convert($id,20,36);
echo $shorturl;
$db->query("INSERT INTO maps (id, url, user_id, locationData, userData) values ( null, '$shorturl', null, '$locationData','$userData')");
Using the above PHP I have been trying generate a unique shorturl which gets stored into a Database and then gets sent to javascript to tell the client side the values echoed.
In an example I tested the above code and in Javascript it console.logged lyhc but when I checked the Database it had the following 6c796863
The database row is set up like url varchar(255) utf8_bin
Am I doing something wrong here?
Your JS code must be taking your output in a different type.
I'm using this function to generate random strings:
function createRandomCode($length='30'){
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code= '';
while ($i++ < $length){
$code = $code. substr($chars, rand() % 33, 1);
}
return $code;
}
It might be helpful.

Categories

Resources