<?php
include ('config.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Platser</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.json-2.2.min.js"></script>
</head>
<body>
<div id="glassbox">
<?php
if(isset($_POST['Spara'])){
}
$antal = $mysqli->query("SELECT `Grupp ID` FROM `Elevgrupper` WHERE `Grupp ID`=25");
$num = $antal->num_rows;
$res = $mysqli->query("SELECT `Namn`, `Efternamn` FROM `Elever` WHERE `ID` IN (SELECT `Användar ID` FROM `Elevgrupper` WHERE `Grupp ID` = 25)");
for ($i = 1; $i<=$num; $i++){
$get_coords = mysqli_query($mysqli, "SELECT * FROM coords WHERE id = '" . $i . "'");
$row = $get_coords->fetch_assoc();
$ok = $res->data_seek($i-1);
$row1 = $res->fetch_assoc();
//
$x = $row['x_pos'];
$y = $row['y_pos'];
echo '<div id="e'. $i .'" class="e" style="left:'.$x.'px; top:'.$y.'px;"><p id="p' . $i .'">'. $row1["Namn"] . " " . $row1["Efternamn"] . '</p></div>';
}
?>
</div>
<form action="<?echo $_SERVER['PHP_SELF'];?>">
<input onclick="spara();" type="submit" name="Spara">
</form>
<div id="respond"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
var antal = document.getElementsByClassName("e");
for (var i = 1; i <= antal.length; i++) {
$("#e" + i).draggable({
containment: '#glassbox',
scroll: false
});
}
});
function spara(){
var antal = document.getElementsByClassName("e");
for (var i = 1; i <= antal.length; i++) {
var coords=[];
var coord = $("#p" + i).position();
var item={ coordTop: coord.left, coordLeft: coord.top };
coords.push(item);
var order = { coords: coords };
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){
});
}
}
</script>
</html>
<?php
if(!$_POST["data"]){
echo "Nothing Sent";
exit;
}
include ('config.php');
$data = json_decode($_POST["data"]);
foreach($data->coords as $item) {
//Extract X number for panel
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
//Extract Y number for panel
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
//escape just-in case
$x_coord = mysqli_real_escape_string($mysqli, $coord_X);
$y_coord = mysqli_real_escape_string($mysqli, $coord_Y);
//Setup Query
$sql = "UPDATE coords SET x_pos = '" . $x_coord . "' WHERE id"= . substr($data->id, -1) .;
mysqli_query($mysqli, $sql);
$sql = "UPDATE coords SET y_pos = "'. $y_coord .'" WHERE id"= . substr($data->id, -1) .;
mysqli_query($mysqli, $sql);
}
//Return Success
echo "success";
?>
If I am not mistaken everything except the spara function should work and it's driving me crazy since I don't get even get any error messages, seems like it runs through the entire script without errors and without saving anything.
What I am trying to do is a teacher tool that from a database which contains all students places out benches that you can drag around and move to your choosing so that you can decide seats for everyone without having to do much work as the teacher. And I want the layout to save by pressing a button which runs the function.
I believe this line could be wrong:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response)
Usually I would have something like this:
$.post('updatecoords.php', {data: somevar}, function(response)
Give that a try, assign $.toJSON(order) to a variable and pass it as suggested.
UPDATE:
Based on Domeniks feedback below, you probably just need to do this:
$.post('/updatecoords.php', somevar, function(response)
Related
After sending the country name "US" in JavaScript to PHP code, I will try to receive the results of PHP's work back to JavaScript and use them.
To do this I used the below code.
$ctryNm_php_temp = "document.write(ctryNm);";
As a result, it seemed that the value 'US' of the ctryNm variable was well transfered to php code.
The cryNm value and $SQL value printed on the screen contain 'US'.
However, the results of the SQL query were returned to an empty value, so we checked.
The IF statement shows that ctryNm and 'US' are different values.
(The output on the screen shows the same value and data type as string.)
I printed $result_obj and found no value.
echo and console.log command result for checking:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var ctryNm = "US";
</script>
<?php
$ctryNm_php_temp = "<script language='javascript'>document.write(ctryNm);</script>";
$ctryNm_php = $ctryNm_php_temp;
echo $ctryNm_php . "<br><br>";
echo "--------------" . "<br>";
echo gettype($ctryNm_php) . "<br>";
if ($ctryNm_php == 'US') {
echo "Same" . "<br>";
} elseif ($ctryNm_php != 'US') {
echo "Different" . "<br>";
}
$conn = new mysqli("...", "...", "...");
mysqli_select_db($conn, '...');
mysqli_query($conn, "set names utf8");
$sql = "SELECT * FROM acst_covid_who WHERE country_code = '$ctryNm_php'";
echo $sql . "<br>";
$result_obj = mysqli_query($conn, $sql);
echo "result_obj :" . $result_obj . "<br>";
$date_adjust = 0;
$latestDate_trend = '';
while ($row = mysqli_fetch_array($result_obj)) {
if ((int)$row['confirmed_new'] !== 0) {
$latestDate_trend = $row['date'];
$date_adjust = 1;
} elseif ((int)$row['confirmed_new'] === 0) {
$latestDate_yester_trend = strtotime($row['date'] . "-1 days");
$latestDate_trend = date("Y-m-d", $latestDate_yester_trend);
$date_adjust = 0;
};
};
$result_obj = mysqli_query($conn, $sql);
$total_rows_trend = mysqli_num_rows($result_obj) - $date_adjust;
$arr_trend = array();
while ($row = mysqli_fetch_array($result_obj)) {
array_push($arr_trend, $row);
}
echo $total_rows_trend;
echo json_encode($latestDate_trend);
?>
<script>
var latestDate_js_trend = <?php echo json_encode($latestDate_trend) ?>;
var arr_js_trend = <?php echo json_encode($arr_trend) ?>;
var arr_length_trend = <?php echo $total_rows_trend ?>;
console.log(latestDate_js_trend);
console.log(arr_js_trend);
console.log(arr_length_trend);
</script>
</body>
</html>
this sadly does not work like this.
PHP code is executed first on the server, so before the website is even shown in the browser. The order you write it does not matter.
The process is like this:
You type the address in the browser and it asks the server for the page.
The server literally runs an app called php, that reads what you wrote in the code, reads only what is between <?php and ?>, nothing else (technically the first one can be <?=)
When it is done, the server sends the page to browser
The browser reads html and fires JavaScript, long after PHP was already changed.
This is simplified but show why your code will not work.
I'm new at php. I get the last id from database. For each id I want the state and the link. I'll check if state == 1, then get the content of the link (there's JavaScript variable that I need that is in the content of link). I'll send that variable with location.href.
Then I get that variable with $_GET in the second page. I want to store that var into database, then come back to first page and get the second link from the database and again do the same works.
How can I send the $j into second page for saving the x_cor and y_cor, and how to increase the $j when it comes to first page again?
<html>
<head>
<title>firstpage</title>
</head>
<body>
<?php
include_once ('simple_html_dom.php');
include_once ('split_unicode_function.php');
// getting the last id from db
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$sql = "SELECT id FROM netbarg ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql, $connection);
$rows = mysql_fetch_array($result);
$last_id = $rows['id'];
// getting id and link for each column
for ($j = 1; $j <= 2; $j++)
{
$select_db = mysql_select_db("kk", $connection);
$id = "SELECT state FROM `table` WHERE id='$j' ";
$result = mysql_query($id, $connection);
$row = mysql_fetch_array($result);
echo $state = $row[0] . '<br />';
// getting link
$link = "SELECT link FROM `table` WHERE id='$j' ";
$result = mysql_query($link, $connection);
$rows = mysql_fetch_array($result);
$link = $rows[0];
// (state is just 1 or 2)check if the state is 2 or not...
if ($state == 1)
{
$f = file_get_contents($link);
echo "<div>$f</div>";
}
}
?>
<script>
$("body").hide();
location.href ='secondpage.php?val='+point0+;
</script>
</body>
</html>
second page
<html>
<head>
<title>second page</title>
</head>
<body>
<?php
if (isset($_GET['val']))
{
$hat = $_GET['val'];
echo $hat;
$coords = trim($hat, '()');
// echo $coords.'<br />';
$a = array();
$a = explode(",", $coords);
var_dump($a);
echo $long = $a[0];
echo '<br />';
if ($long == "undefined") $lat = "undefined";
else echo $lat = $a[1];
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
$connection = #mysql_connect("localhost", "root", "kkuser");
$select_db = mysql_select_db("kk", $connection);
$update = "UPDATE `table` SET `x_cor`='$long',`y_cor`='$lat' , `state`='2' WHERE `id`='$j' ";
$insert_todb = mysql_query($update, $connection);
if ($insert_todb) echo "coordinates has been updated", '<br />';
}
}
?>
<script>
location.href ='firstpage.php';
</script>
</body>
</html>
if get the last insert id use mysqli_insert_id($con);
it return last insert id from database using this geted id you can
i am trying to create a dynamic dropdown menu for my website to add address like state, city, area and postcode. i am using code is working when i try one by one preview in live browser but it does not work when i try to use java-script its not show the data in dropdown menucan you plese tell me where i am making mistake
it is index.php
<head>
</head>
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/scripts.js" type="text/javascript"></script>
<body>
<h1>address</h1>
<hr/>
<label>please select state</label>
<select id="slctstate"></select>
<br />
<br />
<label>please select city</label>
<select id="slctcity"></select>
</body>
</head>
it is script.js
$(document).ready(function() {
$.getJSON("get_stat.php", success = function(data){
var options = "";
for(var i = 0; i < data.lenght; i++)
{
options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#sltstate").append(options);
});
$("#slctstate").change(function(){
$.getJSON("get_city.php?state=" +$(this).value(), success = function(data){
var options = "";
for(var i = 0; i < data.lenght; i++)
{
options += "<option value='" + data[i].toLowerCase() + "'>" + data[i] + "</option>";
}
$("#slctcity").append(options);
});
});
});
it is get_state.php
<?php
require "Connections/dbopen.php";
$query = "SELECT state_name FROM states";
$data = mysqli_query($conn, $query);
$states = array();
while ($row = mysqli_fetch_array($data))
{
array_push($states, $row["state_name"]);
}
echo json_encode($states);
require "Connections/dbclose.php";
?>
and hers is get_city.php
<?php
require "Connections/dbopen.php";
if(isset($_GET["$state"]));
{
$state = $_GET["state"];
$query = "SELECT city_name FROM city
INNER JOIN states ON
city.state_id=states.state_id
WHERE state_name LIKE '{$state}'";
$data = mysqli_query($conn, $query);
$city = array();
while ($row = mysqli_fetch_array($data))
{
array_push($city, $row["city_name"]);
}
echo json_encode($city);
require "Connections/dbclose.php";
}
?>
but at the final step i did not get any value in my drop down can any one please help me thanks
You might want to make the following changes:
change lenght to length
change success = function(data) to function(data)
change isset($_GET["$state"]) to isset($_GET["state"])
refer to http://php.net/manual/en/pdostatement.fetch.php for fetching data in an easier way(optional if the first 3 changes dont work)
So I was following a tutorial and I came across the current problem. This is my first time using the ajax method. I copied and saved jQuery version 1.7.2.min.js in a folder. My php code seems to be working fine, the only thing that seems off is the code for the ajax part.
This code is in a folder called "includes"
<div id="messages">
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
This is the javascript in a folder called "script" named auto_chat
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
url: 'script/Chat.php' ,
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
There is a file called Chat.php containing code that links to the database.
When it runs it should show all the messages inside of the database. Instead it gives me blank and not even errors. Can someone tell me whats wrong with my method?
This is the my Chat.php
<?php
require('../includes/database/connect.db.php')
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
And this is all of my index.php
<!DOCTYPE html>
<?php
require('includes/core.inc.php');
function get_msg(){
$query = "SELECT `Sender`,`Message` FROM `chat`.`chat` ORDER BY `Msg_ID` DESC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)){
$messages[] = array('sender' => $message['Sender'],
'message' => $message['Message']);
}
return $messages;
}
function send_msg($sender, $message) {
if(!empty($sender) && !empty($message)) {
$sender = mysql_real_escape_string($sender);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `chat` . `chat` VALUES (null,'{$sender}','$message')";
if ($run = mysql_query($query)){
return true;
}else{
return false;
}
}else {
return false;
}
}
if(isset($_POST['send'])){
if(send_msg($_POST['sender'],$_POST['message'])){
echo 'Message Sent';
}else{
echo 'Message Failed to sent';
}
}
?>
<html lang = "en">
<head>
<!--Page TItle --!>
<title>Chat Application </title>
<link type="text/css" rel= "stylesheet" href= "includes/main.css" />
</head>
<body>
<div id="input">
<form action = "index.php" method = "post">
<label>Enter Name:<input type = "text" name = "sender"/></label>
<label>Enter Message:<input type = "text" name = "message"/></label><br />
<input type = "submit" name = "send" value = "Send Message"/>
</form>
</div>
<div id="messages">
<?php
$messages = get_msg();
foreach($messages as $message) {
echo '<strong>' . $message['sender'] .' Sent</strong><br />';
echo $message['message']. '<br /><br />';
}
?>
<!--Javascript-->
<script type= "text/javascript" src= "script/jquery-1.7.2.min.js"></script>
<script type= "text/javascript" src= "script/auto_chat.js"></script>
</div><!-- Messages -->
</body>
</html>
After a lot of trial and error, we found out that the problem was a simple missing semicolon on chat.php:
require('../includes/database/connect.db.php');
:)
I have the following script:
EDIT:
<?php
session_start();
//connect to database
function connect() {
$dbh = mysql_connect ("localhost", "d", "a") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
if(isset($_SESSION['username'])){
$dbh = connect();
$id = $_SESSION['id'];
$sql="SELECT a.athleteId, a.fName, a.lName FROM Athletes a, SupportStaff s, StaffAthletes sa WHERE sa.staffId = $id AND a.athleteId = sa.athleteId";
$result=mysql_query($sql);
$ids = array();
$options="";
$i = 1;
while ($row=mysql_fetch_array($result)) {
$ids[]=$row['atheleteId'];
$f=$row["fName"];
$l=$row["lName"];
$options.="<OPTION VALUE=\"$i\">".$f.' '.$l."</OPTION>";
$i++;
}
$array = "";
for($x = 0; $x < count($ids); $x++)
{
$array .= "[" . $ids[$x][0] . ", ". $ids[$x][1] . "]" ;
if($x+1 < count($ids))
$ids .= ", ";
}
$idsArray = "new Array( " . $array . ")";
echo("<script>");
echo("var $ids = ".$idsArray);
echo("</script>");
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#go").click(function(e){
if($("#selectathlete option:selected").val() == "0"){
alert("Please Select An Athlete");
}else{
//set hidden textfield to id of selected athlete
//NEED TO ACCESS $ids ARRAY HERE
$("form#athleteselect").submit();
}
});
});
</script>
<title>Personal Diary System - Home Page</title>
</head>
<body>
<h1>Home Page</h1>
<p>Select An Athlete:
<SELECT ID ="selectathlete" NAME="athletes">
<OPTION VALUE="0">Choose</OPTION>
<?php echo($options);?>
</SELECT>
</p>
<form id = "athleteselect" name="athleteselect" action="viewathleteprofile.php" method="post">
<input type = "hidden" name = "hidden" id = "athleteId" value = "">
<input type = "button" name = "go" id = "go" value = "Go"/>
</form>
</body>
</html>
<?php } ?>
I have a hidden textfield with id = 'athleteId". I have a php array which contains values that I want to assign to the hidden textfield upon pressing the go button (i.e. in the $("#go").click event handler.
Can you do something like:
$("#athleteId").text() = <?php echo("$ids[4]") ?>
to change value of a textbox you do
$("#id-of-your-textbox").attr("value","whatever-value");
of course whatever-value can be anything you want
Try to send the $ids array along with the page response as a JavaScript array.
//This code will render the php variable as a js array along with page response
$array = "";
for($x = 0; $x < count($ids); $x++)
{
$array .= "[" . $ids[$x][0] . ", ". $ids[$x][1] . "]" ;
if($x+1 < count($ids))
$ids .= ", ";
}
$idsArray = "new Array( " . $array . ")";
echo("<script>");
echo("var $ids = ".$idsArray);
echo("$(document).ready(function(){");
echo("$(\"#go\").click(function(e){");
echo("var selText = $(\"#selectathlete option:selected\").text();");
echo("if($(\"#selectathlete\").val() == \"0\"){");
echo("alert(\"Please Select An Athlete\");");
echo("}else{");
echo("$(\"#athleteId\").val($ids[$(\"#selectathlete\").val()]);"); //not working
echo("$(\"form#profile\").submit();");
echo("}");
echo("});");
echo("});");
echo("</script>");
Now since you are not using any php variable in the above code(echos) you can directly use it as a js on your page. You can just echo the $ids array.
//This code will render the php variable as a js array along with page response
$array = "";
for($x = 0; $x < count($ids); $x++)
{
$array .= "[" . $ids[$x][0] . ", ". $ids[$x][1] . "]" ;
if($x+1 < count($ids))
$ids .= ", ";
}
$idsArray = "new Array( " . $array . ")";
echo("<script>");
echo("var $ids = ".$idsArray);
echo("</script>");
<script type="text/javascript">
$(document).ready(function(){
$("#go").click(function(e){
var selText = $("#selectathlete option:selected").text();
if($("#selectathlete").val() == "0"){
alert("Please Select An Athlete");
}else{
$("#athleteId").val($ids[$("#selectathlete").val()]);
//If you want the fourth index as per your edited question use this
//$("#athleteId").val($ids[4]);
$("form#profile").submit();
}
});
});
</script>