Dynamic links/redirect with javascript/php - php

Having an annoying small problem. Cannot find the solution that works tried just about everything i could find from searching here and google.
Purpose of this is to pass them along into a "room" that has been created previously.
Seems like it doesn't matter what i try i cannot get it to load into another page using onclick with an href. And i know its an easy fix its just something silly i cannot think of.
and sorry if i am not posting my code just right this is my first time asking a question i normally just lurk around for answers.
//..Left out <?php and my connect info but it is in my script
//--CLEANUP MY MESS
$sql = "SHOW TABLES";
$result = mysql_query($sql) or die('err11');
while ($row = mysql_fetch_row($result)) $testing[$row[0]] = true;// Gets a list of tables in the database and turns them into a handy format
if ($testing['prim']){// Checks to see if table prim exists
$sql = "SELECT * FROM prim"; // Pulling all info again after cleaning
$result = mysql_query($sql) or die('err11');
$_e = '';
while ($row = mysql_fetch_assoc($result)){// Cycle through enteries to see what rooms are up
$_e = $_e . "<a href='' onclick='join(" . $row['room'] . ");'>" . $row['teach'] ."</a><br>";
}
}else $_e = "Sorry no rooms are open";
mysql_close($con);
?>
<!DOCTYPE html>
<html>
<head>
<script>
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
//THE LINE BELOW DOES NOT SEEM TO WORK
document.location = "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er;
//THE LINE ABOVE DOES NOT WORK
}
</script>
<title>Portal</title>
</head>
<body>
Name:<input type="text" id='name' name="name"><br><?php echo $_e ?>
</body>
</html>
I tried many different small variations like window.location window.location.href etc etc.. also messed with returns and just driving me nuts
Grateful for any help and you folks have a nice day

window.open will open a new window for you. (see http://www.javascript-coder.com/window-popup/javascript-window-open.phtml )
Alternatively you could set the href and use target="_blank". That way you don't have to use javascript so it's more accessible.

On first hand I am thinking try
<a href='#' onclick=...
but I will investigate further.
My thought is to try the following and see if it works.
hello
Then at least that will tell you if javascript is working properly on your browser etc.
You could try rename it from join to something another name because join is a javascript function (operating on arrays) maybe its having a conflict?

Try the following and tell me if it works. Then try adding some PHP code to the top and see if it still works.
<script>
function test()
{
alert("testing");
document.location = "http://location_edited_out/provingground/start.php?name=abcd&room=1";
}
</script>
hi
One thing you could try is to move the script out of the "head" section and into the body.
For example:
<html>
<head><title>Portal</title>
</head><body>
<script>
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
//THE LINE BELOW DOES NOT SEEM TO WORK
document.location = "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er;
//THE LINE ABOVE DOES NOT WORK
}
</script>
Name:<input type="text" id='name' name="name"><br><?php echo $_e ?>
</body>
</html>
Also you could try putting the script at the end of the body (after the php echo command).
Also you could try splitting it into two statements maybe it doesn't like doing it on the one line:
var url = "http://webaddr.com/start.php?name=" + document.getElementById("name").value + "&room=" + er;
document.location = url;
http://www.webmasterworld.com/javascript/3285118.htm
Try window.location.href or simply, location.href
top.location
?
The following works in internet explorer, having a button instead of an "a href".
<html>
<body>
<script>
function test()
{
alert("testing");
window.location.assign("http://location_edited_out/provingground/start.php?name=abcd&room=1")
}
</script>
<input type='button' value='Load new document' onclick='test()'>
</body></html>
Not sure if this is an option?
So the code is:
while ($row = mysql_fetch_assoc($result)){// Cycle through enteries to see what rooms are up
$_e = $_e . "<input type='button' onclick='join(" . $row['room'] . ");' value='" . $row['teach'] ."'><br>";
}
...
function join(er) {
alert('ffs is this even firing');//this is a debug statement i was using... it was firing
window.location.assign( "http://***late edit to get rid of the web address lol sorry***start.php?name=" + document.getElementById("name").value + "&room=" + er);
}
Let me know if it works.

Related

Javascript wont run in PHP

I have this piece of code:
if(isset($_POST['btnSubmit']) && $_POST['btnSubmit'])
{
require_once($_SERVER['DOCUMENT_ROOT'] . 'database.php');
$derpCard = $card;
$derpAccessGroup = $_POST['tbAccessGroup'];
$derpComments = $_POST['tbComments'];
if(isset($_POST['cbActivated']))
$derpActive = $_POST['cbActivated'];
else
$derpActive = "DEACTIVATED";
$x = editCard($derpCard,$derpAccessGroup, $derpComments, $derpActive);
if($x)
{
$_SESSION['editcard'] = $derpCard;
$_SESSION['editgroup'] = $derpAccessGroup;
$_SESSION['editcomments'] = $derpComments;
$_SESSION['editstatus'] = $derpActive;
echo "<script>";
echo "alert(\"Done!\");";
echo "</script>";
}
echo "<script>location.reload(true);</script>";
}
Basically, editCard runs an SQL "UPDATE ... where..." to edit the content within the db. If this is sucessful, I want it to display an alert telling the user it's been updated, as well as refresh the page.
Both the alert and reload code do not run, and i've been trying any and all alternatives! If someone has any idea as to simply refresh the page (thats the minimum i need!) It would be greatly appreciated!
I have to apologize if this answer is too short but the question is too broad or is missing more info. I noticed that one of your lines is wrong.
require_once($_SERVER['DOCUMENT_ROOT'] . 'database.php');
should be:
require_once($_SERVER['DOCUMENT_ROOT'] . '/database.php');
There should be / in it since $_SERVER['DOCUMENT_ROOT'] returns something like this:
"C:/xampp/htdocs"
So if you are to concatenate that with "database.php", you'll be having
"C:/xampp/htdocsdatabase.php" instead of "C:/xampp/htdocs/database.php"
In any case, you should try using firebug or similar browser add-on to help you debug those javascript errors(if there are any).
I hope this helps.
Try to format the script echo like this:
echo "\n<script>\n<!--\n";
echo "alert(\"Done!\");";
echo "\n-->\n</script>\n";
and
echo "\n<script>\n<!--\nlocation.reload(true);\n-->\n</script>\n";
Note the new lines added.
You appear to be missing the type attribute for script.
If you want to specify javascript, you need to include the type.
echo "<script type=\"text/javascript\">";
echo "alert(\"Done!\")";
echo "</script>";
Same goes with the other line
echo "<script type=\"text/javascript\">location.reload(true);</script>";
If the above does not help in the slightest, the problem could be with your logic statements, or that your javascript may just not be outputting what you want.
There are tools to help you figure out these issues, such as the apache logs and firebug plugin
EDIT: Forgot missing semicolon

how to get an id of an element, which is returned from php code

I am trying to build a db driven web site in which the user selects from a drop down menu a
value and some Information from a database are returned. I use an ajax post cause i dont want the page to get refreshed:
$("#button").click(function(){
var datastr = ($('#act').val());
var datastr1 = ($('#loc').val());
$.ajax({
type:'POST',
url:'activities_code.php',
data: {datastr:datastr, datastr1:datastr1},
success:function(response){
$("#msg").html(response);
} });});
In the url parameter I have the following php file (this is a part of the php file):
$query = "SELECT PK,title,Information from activities where Activities='$category'";
$result = mysqli_query($dbcon, $query) or die('no available data');
echo "<table>";
$num_results = 0;
$t = 0; //title counter for the id of each title
while ($row=mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// Here the columns of title and information are printed
echo "<tr><td>";
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
echo "<br>";
echo $x = $row['PK'];
echo "</td></tr>";
echo "<tr><td>";
echo $row['Information'];
echo "</td></tr>";
// Here I sum up the number of the results
$num_results=$num_results+1;
$t = $t+1;
}
}
As you can see, I have a while loop in which I echo each time a link with an id:
"<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
What I want to do is to use this id of each link later in my code by doing something like this:
document.getElementById("t1").value
My question is, how can I return this id's to the client side? I think I should write something in the success function but I have no idea what.
If you dont understand some part of the code or I didn't explain everything clear, please ask me.
Thanks
D.
This is what I get when I alert(response) in the success function.
<!DOCTYPE HTML>
<table id="container"><tr><td><a href='test.php' id="t0" target="_new" class='pickanchor'>Rafting in Voidomatis</a><br>1</td></tr><tr><td>
<img src="m.jpg" class="textwrap" height="120px" width="120px">
<p style="text-align:left;">Our experienced rafting instructors will show you the best way to enjoy Voidomatis, the river with the most clear waters inSouth Europe. You can also cross the Vikos Gorge by following Voidomatis river in an attractive one and a half hour long walk. Alternatively you can ask for the more demanding Aoos river rafting.</p>
<br>
<br>
<hr></td></tr><tr><td><a href='test.php' id="t1" target="_new" class='pickanchor'>Rafting in Lousios</a><br>4</td></tr><tr><td><img src="raf.jpg" class="textwrap" height="120" width="120">
<p>You will be surprised to know that Greece hides numerous, densely vegetated rivers offering amazing rafting opportunities. In the whole mainland, there is a company base awaiting you, for an amazing � off the beaten track experience!</p>
<br>
<br>
<br>
<hr></td></tr><div id="r2" align="center" id="result_2">2 results for rafting were found!
</div></table> <!-- End of PHP code-->
First, There is problem with ID of your anchor tag. here is correction
"<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Second, Give id to your table like
<table id="container">
Third, give class to your anchor tag.
"<a href='test.php' class='pickanchor' id=\"t.$t\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
Now write following code into your success handle after .html() statement
NEW EDIT
$("a.pickanchor").each(function(i){
alert(this.id);
});
In line you presentd you made mistake. In wrong place you have added ".
echo "<a href='test.php' id=\"t\".$t onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
It should be
echo "<a href='test.php' id=\"t".$t."\" onClick=\"test()\" target=\"_new\" >".$row['title']."</a>";
As simplest solution you could add after the while loop
echo "<script> my_max_id_num=$t </script>"
This will give you knowledge about which ids are present on page. This should give your js script access to my_max_id_num variable. It's not considered best programming practice but is simple.
Second (better) way of solving problem could be returning json instead of html and rewriting your success method. This will be more work to be done:
Rewrite while loop so it returns something like:
{ "data":[
...
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
{ "id":"10", "target":"_new", "title":"one_of_your_link_titles" },
...
]}
Rewrite your ajax query so it will accept json, and rewrite success method so it will create your links on basis off data returned from server.
This way you will have both, ids and your links in one query. What's more in case of changing requirements it will be easier.
The simplest solution would be to give your elements a class, that way you don't need to select based on the elements id, but you can access it easily:
eg.
test 0
test 1
$('#msg').on('click', '.className', function() {
console.log(this.id);
});
I don't have enough rep points to ask for clarification, but what do you mean by 'return this id's to the client side'? Also what would the 'value' of the element 't1' be?
Lets say you wanted to get the link location it could be something like:
var value = $('#addButton').attr('href');
and then do something with the value (not sure what you mean by 'return this id's to the client side') but perhaps you want the value then to be visible to the client?
So if you have a div somewhere on the page where you want it to show you could populate it with you value, maybe something like:
HTML
<div id="valueBox"></div>
jQuery
$("#valueBox").html(value);

How to use AJAX to store a javascript variable to my sql database

I'm trying to save a logged in user's score to my sql database. I programmed a simple game of pong in HTML5 and javascript. Basically I need to get the score variable from the pong.js file and write that score to the database when the user hits a button on my page. I just simply can't get it to work. I'll hit the button as a logged in user and my games score will update to 1 (which is just a test) but i won't get any type of feedback from my server's php file.
Here's my Index.php file:
<?php
session_start();
$_SESSION['score'] = 0;
?>
<html>
<head>
<meta name = "description" content = "Josh Siegl's home web server"/>
<meta name = "keywords" content = "home, web, server, pong, html5, game"/>
<link rel="stylesheet" type = "text/css" href = "mycss.css" />
<title> JOSH SIEGL HOME WEB SERVER </title>
</head>
<body>
<div align = "center">
<?php if(!isset($_COOKIE['ID_SERVER']))
{
echo '<form id = "signIn" action = "getuser.php" method = "post">
UserName: <input type = "text" name = "username" />
Password: <input type = "password" name = "password" />
<input type = "submit" name = "SIGNIN" value = "SIGN IN"/> or
<a href = "register.html" id = "register" style="text-decoration:none"/> <i> Register </i></a>
</form>';
}
else
{
?>
<p> <?php echo "WELCOME " . $_COOKIE['ID_SERVER'];} ?> <?php if(isset($_COOKIE['ID_SERVER'])){echo ' logout';} ?> </p>
<h1 id = "GAMENAME"> PONG </h1>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script type="text/javascript" src = "pong.js" id = "gamescript"></script>
<div id = "status"></div>
<script language = "JavaScript" type = "text/javascript">
function Ajax_Call()
{
playerscore = 1;
var hr = new XmlHttpRequest();
var url = "submitscore.php";
var keys = "score=" + playerscore;
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function()
{
if (hr.readyState == 4 && hr.status == 200)
{
var returndata = hr.responseText;
document.getElementById("status").innerHTML = returndata;
}
}
hr.open("GET", "submitscore.php?score="+playerscore, true);
hr.send();
document.getElementById("status").innerHTML = "posting...";
}
</script>
<input type = "submit" name = "submitscore" value = "POST SCORE" onclick = "Ajax_Call();"></input>
<br /> <p> This is a pong clone, created by Josh Siegl, hosted on a home web server.
This game was created in HTML5 and should run on most up to date browsers. </p>
<br /> <p> I programmed this entire game in javascript and HTML5. The source code is publicly available, right click and hit inspect element </p>
</div>
</body>
</html>
the submitscore button calls Ajax_Call(), I know that this works because I updated my score variable to show that Ajax_Call is at least executing (the playerscore variable is contained within pong.js, if you need to see that file i'll post it, although I don't believe i'll need to).
Here's my submitscore php file:
<?php
$q=$_GET['score'];
$con = mysql_connect("localhost", "root", "");
if (!$con)
{
die(mysql_error());
}
$mydb = mysql_select_db('users', $con);
if (!$mydb) {
die ('Can\'t use $con : ' . mysql_error());
}
$sqlstatement = "UPDATE people
SET score= $q WHERE username =$_COOKIE['ID_SERVER']";
if (mysql_query($sqlstatement, $con))
{
echo "your score of: $q is now in the database";
}
else
{
die(mysql_error());
}
mysql_close($con);
?>
(this is just for practice, so don't go trying to hack my database ;) ) anyway i've been trying a bunch of different things so that's why the code may look a little bit sloppy, again all I want to do is submit my score variable to the database when the user hits the button. (I'm using firefox to test my site, so at this point to keep things simple, I didn't throw any checks for other browsers when creating my new xmlhttprequest object if you believe this is the problem let me know)
If you could possibly tell me a direction to go in, or something to try, or at least a website that could help me out. it would be VERY much appreciated. This is my first post so if I did something wrong please let me know. Thank you very much for the help
An answer the question from the title would be extremely simple: exactly the same way as any other data. PHP knows nothing of AJAX. From the PHP point of view there is no AJAX or browser or bot or whatever but only regular HTTP calls with data. So, PHP have to process that data and store it in the database (or reject), the same way for the all.
The question body seems more an article rather than a question. Following the stackoverflow habit, I didn't bother with reading such a novel. Only I can tell that such long posts often inspired by the trivial lack of debugging.
it seems that you need Firebug as your current debugging tool. A Net tab of this brilliant Fitrefox add-on will show you either HTTP request made my js and a response from PHP. So, it will let you have an idea of what's going wrong.

Problem getting results from mysql database via php and jquery

I try to realize the following:
I generate via php a table of two fields (about training lessons) - lessons' name and location.
This table has several rows and i implemented an like this:
<table border='0' id='testing'>
<thead>
<tr class='small_title_bold'>
<th>Formation</th><th align='center'>Niveau</th><th align='center'>Ville</th>
</tr>
</thead>
<tbody>
<?php
db_connect();
if (isset($etablissement)){
$sql_find_id_etablissement = "select id_etablissement, subdesignation, address1, address2, zip, city, town, department, phone, fax, www from etablissements where designation = '$etablissement' and id_region='$id_region'";
$result_find_id_etablissement = mysql_query($sql_find_id_etablissement, $connection) or die('error');
while ($row_find_id_etablissement = mysql_fetch_row($result_find_id_etablissement)){
$id_etablissement = $row_find_id_etablissement[0];
$subdesignation = $row_find_id_etablissement[1];
$address1 = $row_find_id_etablissement[2];
$address2 = $row_find_id_etablissement[3];
$zip = $row_find_id_etablissement[4];
$city = $row_find_id_etablissement[5];
$town = $row_find_id_etablissement[6];
$department = $row_find_id_etablissement[7];
$phone = $row_find_id_etablissement[8];
$fax = $row_find_id_etablissement[9];
$www = $row_find_id_etablissement[10];
print "<tr class='small_subtitle_bold'><td colspan='3' align='center'>".$id_etablissement."-". $subdesignation."</td></tr>";
$sql_find_master = "select id_master, designation, master_level from masters where id_etablissement = '$id_etablissement' order by designation, master_level";
$result_find_master = mysql_query($sql_find_master, $connection) or die('error');
$count=mysql_num_rows($result_find_master);
for($i = 0; $i < $count; $i++) {
$row_find_master = mysql_fetch_row($result_find_master);
$id_master = $row_find_master[0];
$designation = $row_find_master[1];
$level = $row_find_master[2];
if($i % 2) {
print "<tr class='univ' bgcolor='#A4D2FD'>";
print "<td><a class='univ' href='master-details.php?master-id=".$id_master."&etablissement-id=".$id_etablissement."' onclick='popup('master-details.php?master=".$designation."')>".$designation."</a></td><td class='small_text' align='center'>".$level."</td><td class='small_text' align='center'>".$town."</td>";
print "</tr>";
}
else {
print "<tr class='univ' bgcolor='#FFFFFF'>";
print "<td><a class='univ' href='#' onClick='javascript:swapContent(".$id_master.",".$id_etablissement.")'>".$designation."</a></td><td class='small_text' align='center'>".$level."</td><td class='small_text' align='center'>".$town."</td>";
print "</tr>";
}
}
}
}
?>
</tbody>
</table>
When a user clicks a row, i want to run a mysql query and present the results (the lesson's details) in a separated located in the same page without reloading the page.
I placed the following script in my head section:
<script language="JavaScript" type="text/javascript">
function swapContent(id_master, id_etablissement) {
var url = "master-details.php";
$.post(url, {id_master: id_master, id_etablissement: id_etablissement} ,function(data) {
var content = $( data ).find( '#content', function () {alert('Query was performed.');} );
$( "#queryResults" ).empty().append( content );
});
}
</script>
I want my jquery script to run a php file named master-details with the parameters id_master and id_etablissement and returns the results in a DIV section named queryResults.
However, when I clicked on a row in my table, nothing happened.
Any help would be greatly appreciated.
Something like this:
jQuery("tr").live("click", function(){
$.post///what you already have.
});
You just need a way to tell it to do something when you click.
...when I clicked on a row in my table, nothing happened.
Something happened, even if it was not apparent. The task is to determine exactly what happened, and why it didn't produce the expected results.
There are several steps you can take to determine what really happened:
Check for Javascript errors. You can use Firebug for Firefox or the built in Developer Tools for Chrome to view the Javascript console. If a Javascript error occurred, it will be shown there.
Determine if the PHP script was executed. You can do this by checking your webserver's logs, or by looking at the "Network" tab of the aforementioned tools.
If the PHP script is successfully executing, determine what output it produces. You can do this by running the script directly. Find the URL that your AJAX call references, and paste it into your browser's address bar. Is the output what you expect it to be?
If the PHP script executes and returns appropriate results, check your Javascript selectors. Are you sure they reference the correct div? Does that div exist?

Calling Javascript function from PHP function

Below is my code in a single PHP file named testOne.php
<html>
<head>
<script type="text/javascript">
function testAlert(firstValue, secondValue)
{
alert ("Passed: "+firstValue+secondValue);
}
</script>
</head>
<body>
....
</body>
</html>
<?php
function testPassedValues($One, $Two)
{
echo "<input type = \"button\" onclick = \"testAlert($One[2], $Two[2])\">Click Here!</input>";
}
$link = mysql_connect("localhost", "root", "");
if (mysql_select_db("myDatabase", $link))
{
$result = mysql_query("SELECT * FROM MYTABLE");
while($currRowOne = mysql_fetch_row($result) &&
$currRowTwo = mysql_fetch_row($result))
{
testPassedValues($currRowOne, $currRowTwo);
}
}
?>
To help in understanding, I am calling a javascript method testAlert() from the PHP function testPassedValues(). However, I am not sure what the issue is since the call is not successful. In Mozilla(Firebug), I don't find any issues and in Chrome->Developer Tools, I get the error Uncaught Syntaxerror: Unexpected token ILLEGAL in the console.
Can anyone please help me as to the root cause here?
I don't think you've fully understood where and how JavaScript and PHP are executed.
PHP is run on the server. It generates an HTML page (potentially containing JavaScript), which is then sent to the client. The PHP is now finished.
The client's web browser then runs the JavaScript.
To debug your JavaScript problem, take a look at the web page the client actually saw. If Firebug is reporting a problem, that's where it is.
Most likely the values of $One[2] and $Two[2] are strings, so the generated HTML is:
<input type = "button" onclick = "testAlert(string one, string two)">Click Here!</input>
Which is obviously invalid javascript.
Enclose the parameters in quotes:
echo "<input type = \"button\" onclick = \"testAlert('$One[2]', '$Two[2]')\">Click Here!</input>";
You should also correctly escape the of $One[2] and $Two[2] values for HTML and JavaScript, so that you don't introduce XSS flaws or errors when a string contains an apostraphe. I'll leave that up to you to figure out.

Categories