Redirection in an ajax called page - javascript

I have read quite a bit and I still am missing something.
I have a page that has a button on it. When you click the button it will call an AJAX function that will then wait and refresh every 5 seconds in waiting for a MySQL database change. Once the change in the database is made, I would like to take the user to a new page all together.
I have tested the refreshing for the database changes and they work great with echos. I have tried to use windows.location and the php header redirect. Neither are working.
I am not using jquery for the ajax call. Any help would be greatly appreciated.
Thank you
code:
index.php
<?php
session_start();
$_SESSION = array(
'player' => 0
);
?>
<!DOCTYPE HTML>
<html>
<head>
<script src="ajax.js"></script>
<title></title>
</head>
<body>
<div id="join"><button type="button" onclick="startGame()">Throwdown!</button></div>
</body>
</html>
rpsjoin.php
<?php
include("db.php");
session_start();
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$gameStatus_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT game.game_status FROM game WHERE game.id =' . $lastId));
$gameStatus = $gameStatus_q['game_status'];
if ($gameStatus == 2) {
mysqli_query($con, "INSERT INTO game (game_status, player1_joined) VALUES(1,1)");
$_SESSION['player'] = '1';
$playerNumber = $_SESSION['player'];
$lastId_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT MAX(id) AS id from game'));
$lastId = $lastId_q['id'];
$_SESSION['lastId'] = $lastId;
} elseif ($gameStatus == 1 && $_SESSION['player'] != 1) {
mysqli_query($con, "UPDATE game SET player2_joined = 1 WHERE id = " . $lastId);
$_SESSION['player'] = '2';
$playerNumber = $_SESSION['player'];
$_SESSION['lastId'] = $lastId;
}
$player1_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player1_joined FROM game WHERE game.id =' . $lastId));
$player2_join_q = mysqli_fetch_assoc(mysqli_query($con,'SELECT player2_joined FROM game WHERE game.id =' . $lastId));
$player1_join = $player1_join_q['player1_joined'];
$player2_join = $player2_join_q['player2_joined'];
echo $lastId . "<BR>";
echo $gameStatus . "<BR>";
echo $player1_join . "<BR>";
echo $player2_join . "<BR>";
if ($player1_join == 1 && $player1_join == $player2_join) {
echo '<form action="rpsover.php" method="post">
<button type="submit" name="player" value="1">Rock</button>
<button type="submit" name="player" value="2">Paper</button>
<button type="submit" name="player" value="3">Scissors</button>
</form>';
} else {
echo "Locating player. Please be patient";
}
echo session_id();
?>
function startGame() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("join").innerHTML=xmlhttp.responseText;
setTimeout('startGame()',1000);
}
}
xmlhttp.open("GET","rpsjoin.php",true);
xmlhttp.send();
}
At the end of rpsjoin.php, instead of showing a form, i want to be redirected to another page.
Yes I know my code is bad and there are test echos in it.
Thank you

Related

Retrieving large data amount as datalist from Remote PC

I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.

Pass a current page's php variable through to XMLHttpRequest2 (i.e. $user_id)

I am trying to figure out if a current page's php $var can be passed through to the XMLHttpRequest2. The file that is being called is located outside of the views(where the current php page is located) folder in the /assets/js directory. I am using CodeIgniter as well. Trying to pass the $user_id along to use in a SQL query in side the XMLHttpRequest2 requested file.
publication_call.php (current file)
<form>
<input type="hidden" id="someid" value="<?= $idz ?>"/>
<?php
echo form_label('Validation: (Enter Publication keywords, Matches will appear in Dropdown > )');
echo form_label('Matching<br>Publications:');
?>
<select name="matched_pub" id="matched_pub"></select>
</form>
<script>
jQuery(function($){
//still want to bind the change event
$('#matched_pub').bind('change', function(){
$('#title').val($('#matched_pub option:selected').text());
});
$('#validation').keyup(function() {
showKeywords( $('#validation').val() );
document.getElementById('matched_pub').style.display='block';
});
});
</script>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
<?php
$user = 'root';
$pass = 'root';
$db = 'hey_there';
$host = 'localhost';
$conn = mysql_connect($host, $user, $pass);
$db_selected = mysql_select_db($db, $conn);
//trying to display special chars
mysql_query("set names 'utf8'");
if(!$db_selected) {
echo 'broke';
}
//echo 'db connected';
$q = $_GET["b"];
//explode and parse $q into all the fragments separated by spaces and do full text search +word1 +word2 +word3, this will ignore HTML tags as it ignores word order, will also solve the middle initial problem [db setup is not compatible with full text search, but can do likes per word, less efficient, but how it must be done]
$queryWords = explode(' ', $q);
//for services query, explode the query into words and search for each separately
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = 103 <-- $var will go here
";
$queryServicesLoop = '';
$queryServicesEnd = ' ORDER BY pub_title ASC';
//loop through all words in string
foreach($queryWords as $queryWord) {
$queryServicesLoop .= " AND (keywords LIKE '%{$queryWord}%')";
}
$queryServices = $queryServices.$queryServicesLoop;
$queryServices = $queryServices.$queryServicesEnd;
$resultServices = mysql_query($queryServices);
$services ='';
if(mysql_num_rows($resultServices) > 0){
while($rowServices = mysql_fetch_assoc($resultServices)) {
$services .= '<option value="' . $rowServices['pub_title'] . '">' . $rowServices['pub_title'] . '</option>';
}
}
if( mysql_num_rows($resultServices) == 0 )
{
echo '<option value="">Your search failed to find any matching results.</option>';
}
else
{
echo '' . $services . '';
}
/* ==============================
Edited Code
============================== */
publication_call.php (current file)
<input type="hidden" id="someid" value="<?= $user_id ?>"/>
<script>
function showKeywords(str)
{
if (document.getElementById("matched_pub")) {
if (str.length==0)
{
document.getElementById("someid");
document.getElementById("matched_pub").innerHTML="";
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("matched_pub").innerHTML=xmlhttp2.responseText;
}
}
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid'), true);
// xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str,true);
xmlhttp2.send();
}
}
</script>
searchwords.php (requested/external file)
$usr = $_GET["user_id"];
$query = "SELECT DISTINCT(pub_title)
FROM teacher_publications
JOIN users ON teacher_publications.user_id = users.id
WHERE keywords IS NOT NULL
AND pub_title IS NOT NULL
AND teacher_publications.user_id = ".$usr."
";
You can put $user_id inside of a hidden input field, and using Javascript, read the value of it to use in your Ajax request
You can do it like this:
<input type="hidden" id="someid" value="<?= $user_id ?>
And then after you've done that, you can get the value by doing this:
document.getElementById('someid'); using plain Javascript or $('#someid').value(); if you use jquery
This will get you the user ID value which you can then use in the request.
Like so:
xmlhttp2.open("GET","/assets/keywordsearch.php?b="+str+"&user_id="+document.getElementById('someid').value, true);
Replace your current xmlhttp2.open with the one above
Now you can access the value of user ID in $_GET['user_id'] in the requested file.

AJAX issue : button doesn't responsed anymore

Last night I had issue with registration where php was saving null data to my database when ajax was used but with a help of stack overflow the issue was resolved. I was sending data in url and rather than using $_GET i used $_POST, problem solved so this morning I thought lets do the same with login page but this time when I add ajax to it the login button it does nothing, it just clicks and does nothing
what I was trying to do was when user login with correct info it goes to home page index.php but when the user try to log in with wrong info then it echo invalid. so I was trying to echo it in index.php rather than taking user to new page.
the following is the code i was working on.this one is saved as index.php where user puts there details.
<?php
if (!isset($_SESSION['uid'])) {
echo "<form action='login_parse.php' method='post' style='display: inline-block'>
Username: <input type='text' name='username' id='username' />
Password: <input type='password' name='password' id='password' />
<input type = 'button' value='login' id='submit' onclick='hello2()'/>";
echo "</form>";
echo "<form action='signup.php' method='post' style='display: inline-block'>";
echo "&nbsp";
echo "<input type='submit' name='submit' value='Signup'>";
echo "</form>";
echo "<div id='ack1'></div>";
} else {
echo "<form style='display: inline-block'>";
echo "<p>You are logged in as ".$_SESSION['username']."";
echo "</form>";
echo "<form action='logout_parse.php' method='post' style='display: inline-block'>";
echo "&nbsp";
echo "<input type='submit' value='logout'>";
echo "</form>";
}
?>
this one is saved as ajax.js
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
var HTTP = loadXMLDoc();
function hello2(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack1").innerHTML=HTTP.responseText;
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
and at last this one is saved as login_parse.php
<?php
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = mysql_real_escape_string( $_GET["username"]);
$password = mysql_real_escape_string( md5 ($_GET["password"]));
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: index.php");
exit();
} else{
echo "INVALID login information.";
exit();
}
}
?>
am I doing something wrong, do I have to use ajax just to echo invalid in index.php
Here are the fixes for the ajax code not displaying the invalid login message.
First i removed the function call for the hello2 function and placed in a javascript event at within a script tag at the bottom of the page. This made it easier for me to conduct tests. You will have to add the id submit-button to your button html.
The previous echo in your index php file will look like this now.
echo "<form action='login_parse.php' method='post' style='display: inline-block'>
Username: <input type='text' name='username' id='username' />
Password: <input type='password' name='password' id='password' />
<input id='submit-button' type = 'button' value='login' id='submit' />";
Here is the javascript that will before the closing body tag of your index.php file:
<script src="ajax.js"></script>
<script>
//return XMLHTTP request and store it
var HTTP = loadXMLDoc();
//on click event for #submit-button
var submitEvent = document.getElementById("submit-button").onclick = function(){
hello2(HTTP);
};
</script>
This is were I found the main problem. I made the variable xmlhttp have global scope by placing it at the top your ajax.js code.
I found this problem initially by changed the following line of code:
document.getElementById("ack1").innerHTML= HTTP.responseText;
to:
document.getElementById("ack1").innerHTML= "it worked";
By doing this I discovered that your function call at this point was working but your HTTP.onreadystatechange=function(){} was unable to access the responseText.
Here is the new ajax.js file code below:
//moved variable outside of functions to give it the global scope
var xmlhttp;
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function hello2(HTTP){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState===4 && HTTP.status === 200){
document.getElementById("ack1").innerHTML= HTTP.responseText;
}
};//<--was missing a semicolon ;
HTTP.open("POST", url ,true);
HTTP.send();
}
Fix for PHP code so that you don't have to refresh index.php to show the You are "logged in as ..." message.
Place this php code before any other php code in you index.php file so that you can access your session variables.
//start the session so that you can echo session variables on this page
session_start();

javascript prompt sent to php but output empty

I am trying to allow adding of a category to category dropdownlist by clicking the '+' button below it using ajax but my dropdownlist keeps disappearing instead.
HTML codes are as follows
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script>
function addCategory()
{
var category = prompt("Please enter new category: ", "");
if (category != null){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4){// && xmlhttp.status==200) {
document.getElementById("category").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","add_category.php?category="+category,true);
xmlhttp.send();
}
}
</script>
<script language="javascript" src="calendar/calendar.js"></script>
</head>
<body>
<?php
include ('db_conn.php');
session_start();
if(!empty($_REQUEST['event'])){
$event = $dbc->prepare("SELECT * FROM `COO_DEF_EVENT` WHERE EVENT_ID = :eventid;");
try{
$event->bindParam(':eventid', $_REQUEST['event']);
$event->execute();
$eventdet = $event->fetch(PDO::FETCH_ASSOC);
}catch(PDOException $ex){
echo 'Error getting event data';
}
echo '<form id="form1" name="form1" method="post" action="editEvent.php">';
}else{
echo '<form id="form1" name="form1" method="post" action="addEvent.php">';
}
?>
Category:
<div id="category"><select name="categorydpl" id="categorydpl">
<?php
$categorySQL = $dbc->prepare("SELECT * FROM `CATEGORY` WHERE USER_ID = :userid; ");
try{
$categorySQL->bindParam(':userid', $_SESSION["userid"]);
$categorySQL->execute();
$categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);
foreach ($categoryList as $category){
echo '<option value="'.$category['CATEGORY_ID'].'">'.htmlspecialchars($category['CATEGORY_NAME']).'</option>';
}
}catch(PDOException $ex){
echo 'Error getting data';
}
?>
</select></div><button onClick="addCategory()">+</button>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit"
value="Submit" /><button onClick="location.href ='index.php';">Cancel</button>
</form>
</body>
</html>
PHP file
<?php
include ('db_conn.php');
session_start();
$category = $_GET['category'];
$print='category entered: '.$category;
$sql = $dbc->prepare("INSERT INTO `COO_CATEGORY` (`USER_ID`, `CATEGORY_NAME`) VALUES (:userid, :category_name);");
try{
$sql->bindParam(':userid', $_SESSION["userid"]);
$sql->bindParam(':category_name', $category);
$sql->execute();
}catch (PDOException $ex){
echo 'Insertion failed. Please try again';
}
$categorySQL = $dbc->prepare("SELECT * FROM `COO_CATEGORY` WHERE USER_ID = :userid;");
try{
$categorySQL->bindParam(':userid', $_SESSION["userid"]);
$categorySQL->execute();
$categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);
$print .= '<select name="categorydpl" id="categorydpl">';
foreach ($categoryList as $category){
$print.= '<option value="'.$category['CATEGORY_ID'].'">'.htmlspecialchars($category['CATEGORY_NAME']).'</option>';
}
$print.='</select>';
}catch(PDOException $ex){
echo 'Error getting data';
}
echo $print;
?>
When I open the php by typing .../add_category.php?category=sad
The page will display
"category entered: sad " followed by a dropdown list with sad inserted.
But when I try with the html file, the dropdownlist will disappear after I click the plus button and enter any value.
Any advice?
Thanks in advance!!!
Submit buttons submit forms. Submitting a form will reload the page.
Use <button type="button">
Try it with jQuery. In html file
$.ajax(
{
type: 'GET',
url: 'add_category.php',
dataType: 'json',
data: {'category' : category},
success:
function(answer){
$('#categorydpl').empty();
answer && answer.forEach(function(entry){
$('#categorydpl').append(new Option(entry['id'], entry['name']));
})
},
error:
function(){
console.log('Error');
}
}
);
and in your php file
$categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);
foreach ($categoryList as $category){
$result[] = array('id' => $category['CATEGORY_ID'], 'name' => htmlspecialchars($category['CATEGORY_NAME']));
}
echo json_encode($result);
Make sure your not doing a cross-site request (http://en.wikipedia.org/wiki/Same-origin_policy). When calling a page on a different domain with an ajax call, the browser doesn't allow it by default as a security measure.

onchange in onchange won't work

When I am building 2 dropdowns filling them from the database, the second dropdown is created when a value is picked from the first dropdown. But then, when I select an option in the second, my ajax is being executed. But when I have only one value in the second dropdown, it won't work. Even if I call the javascript function manualy.
The 2nd dropdown:
<?
include ('../dbconnect.php');
$query = "CALL get_projects(".$userid.",".$q.")";
$result = mysql_query($query);
$countprojects = mysql_num_rows($result);
if ($countprojects != 0){
echo '<select class="form-control" onchange="showContent(this.value)">'."\n";
if ($countprojects > 1){
echo "<option value='none' selected>Select project</option>";
}
while($rowprojecten = mysql_fetch_assoc($result)){
echo '<option value='.$rowprojecten['projectID'].'>'.$rowprojecten['projectname'].'</option>';
$lastvalue = $rowprojecten['projectID']; // see below why i did this
}
echo '</select>';
?>
the javascript function I wrote/copied:
function showContent(str)
{
if (str=="")
{
document.getElementById("project").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("project").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","./includes/ajax/getcontent.php?q="+str,true);
xmlhttp.send();
}
The phpfile what is called from this javascript:
<?
$q = intval($_GET['q']);
include ('../dbconnect.php');
$query = "CALL get_project(".$userid.",".$q.")";
$return = '<div id="project">';
$return .= $query;
$return .= '</div>';
echo $return;
mysql_close($con);
?>
Why do I see the div 'project' change when I select one, but does'nt it change when it is created?
I tried to call the function manualy with adding this to the first php file. But it also doesn't work.
if ($countprojects == 1){
echo '<script type="text/javascript">
showContent('.$lastvalue.')
</script>';
}
sorry for my bad english, I hope you can help me solve this.
This is because there is only one option in your second drop down list. you cannot fire change event if there is only on or zero options in drop down list. what you can do is add this code where your first Ajax call get fired when selection changes. and place your second Ajax call in inside below code.
if ($('#selectproject').children().length == 1) {
// make sure you have imported latest jquery. if not add this inside HTMl head : <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
var selectedProject = $('#selectproject').children()[0].value;
showContent(selectedProject); // i hope this is the function you are calling when executing. if not please replace your function call here.
}

Categories

Resources