redirect location after execution is wrong - javascript

I have been mulling over this for hours, to the point of myopia looking at this screen and I can't figure out what is causing the problem.
I can a script which redirects to a unique page (defined in variables) after execution. The script works fine but the location it redirects to is wrong every time.
For example. A user has 4 links to check, lets say they are new comments on his/her page. When he/she clicks the link it directs to the oldest one every time. Not the one they clicked on.
I have 2 parts of code:
<?
$result_s = mysql_query("SELECT * FROM pins a LEFT JOIN comments b ON a.id = b.pin_id WHERE b.to_id = '$myid' AND b.status = '0' ORDER BY date DESC");
$rows = array();
while ($row = mysql_fetch_assoc($result_s)) {
$jS = '"'.$row[id].'"';
$boardid = $row['board_id']; // collection id
$postid = $row['pin_id']; // post id
$posturl = $row['pin_url']; // post id
echo "<table width='100%'><tr>";
echo "<td align='center'><a href='javascript:setActive(".$jS.")'><img src='".$posturl."' height='100'><br>".$boardid."/".$postid."</a></td>";
echo "</tr></table>";
}
?>
and
<script type="text/javascript">
function setActive(ObjID) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//Return Value. Handle as you wish. Display or ignore.
var x = xmlhttp.responseText;
if (document.getElementById(ObjID).style.color == 'black') document.getElementById(ObjID).style.color='red';
else document.getElementById(ObjID).style.color='black';
document.getElementById(ObjID).innerHTML = '<center><font face="Century Gothic">' + x + '</font></center>';
}
}
var p_str = "a="+ObjID;
xmlhttp.open("POST","/application/views/setActive.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(p_str);
location.href="/board/pins/<?php echo $boardid; ?>/<?php echo $postid; ?>";
}
</script>
I have tried using different variables in the location part of the script but nothing works. I'm not educated in this so maybe I'm missing something that is glaringly obvious to some programmers out there, which is my reason for asking here.
Can you see what the problem might be?

There are a few issues
The A in Ajax stands for asynchronous. So whatever you do right after the .send is executed BEFORE the Ajax call (The use of XMLHttpRequest is called Ajax)
You call the function with an ObjID which is then acted upon in the RETURN of the Ajax call (whatever is inside the xmlhttp.onreadystatechange) but not known in there since ObjID is not global and not copied to the scope (closure)
Try this
function setActive(ObjID) {
var xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
var ID = ObjID
xmlhttp.onreadystatechange = function(id) {
return function() {
if (this.readyState != 4) return;
if (this.status == 200) {
var obj = document.getElementById(id); // id is passed now
var style = obj.style; // but please use CSS intead
style.color = style.color == 'black'?'red':'black';
style.fontFamily = "Century Gothic";
style.textAlign="center";
obj.innerHTML = xmlhttp.responseText;
setTimeout(function() {
location.href="/board/pins/<?php echo $boardid; ?>/<?php echo $postid; ?>"
},3000); // assuming this is what you want
};
}(ID); // passing the ObjID
}
var p_str = "a="+ObjID;
xmlhttp.open("POST","/application/views/setActive.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(p_str);
}

Related

Cannot get data passed to a php file using AJAX

I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.

AJAX Session called twice. It doesn't show an alert the second time

I have an AJAX session that gets called once on page load and again after a click. It's not getting a readystate change the second time so I decided to test it by putting an alert box in the function. The alert box shows up on the page load. But on the click it doesn't show up - get this - even though the PHP side executes. More puzzling is that if I try to measure the readystate it never appears (not 0,1,2,3 or 4 - an alert box won't even show up), and I don't get an return text.
What I ultimately am trying to achieve is for the xmlhttp.responseText to return a value like it does on the page load. What am I missing?
JavaScript:
function ajaxSession()
{
alert();
xmlhttp = undefined;
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)
{
z = xmlhttp.responseText;
}
}
}
function stateCheck()
{
ajaxSession();
xmlhttp.open('POST', thisurl + '/favoritecheck.php',false);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send("0=" + perform + "&1=" + thisplace + ",&2=" + thisusername);
}
function firstCheck()
{
perform = 0;
stateCheck();
if (z == 'found')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if ( z == 'nouser')
{
perform = 1;
stateCheck();
}
}
function heartCheck()
{
perform = 2;
stateCheck();
if (z == 'added')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if (z == 'subtracted')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-off.png";
document.getElementById("favtext").innerHTML="Add to your favorites.";
}
}
if (loggedin == 1)
{
document.writeln('<img id="favorite" style="cursor: pointer;" onclick="heartCheck()" src="http://www.********.com/images/favorite-off.png" alt="Favorite" />'
+ '<br />'
+ '<div id="favtext" style="color: #D20425;">'
+ 'Add to your favorites.'
+ '</div>');
firstCheck();
} else if (loggedin == 0)
{
document.writeln('<img id="favorite" style="cursor: pointer;" src="http://www.********.com/images/favorite-off.png" alt="Favorite" />'
+ '<br />'
+ '<div id="favtext" style="color: #D20425;">'
+ '<a style="color: #800000; font-weight: bold;" href="' + thisurl + '/wp-login.php">Log in</a> to add favorites.'
+ '</div>');
}
PHP:
<?php
include('connect.php');
$salt = "********";
$perform = $_POST[0];
$place = $_POST[1];
$user = $_POST[2];
$usercrypt = crypt(md5($user),$salt);
$placeid = trim($place,",");
function checkNow()
{
global $usercrypt;
global $place;
global $conn;
$urow = mysqli_query($conn, "SELECT Users.User FROM Users WHERE Users.User='" . $usercrypt . "';");
if (mysqli_num_rows($urow) > 0)
{
$favcheck = mysqli_query($conn, "SELECT Users.Favorites FROM Users WHERE Users.User='" . $usercrypt . "';");
$favcheck = mysqli_fetch_array($favcheck);
$favcheck = $favcheck[0];
if (strpos($favcheck, $place) !== false)
{
$answer = 'found';
}
else
{
$answer = 'notfound';
}
}
else
{
$answer = 'nouser';
}
return array($answer,$favcheck);
unset($answer);
}
if ($perform == "0")
{
$sendback = checkNow();
echo $sendback[0];
unset($sendback);
}
if ($perform == "1")
{
global $usercrypt;
global $conn;
mysqli_query($conn, "INSERT INTO Users (User) VALUES ('" . $usercrypt . "')");
}
if ($perform == "2")
{
$sendback = checkNow();
global $place;
global $placeid;
global $usercrypt;
global $conn;
$currentnum = mysqli_query($conn, "SELECT Places.Favorites FROM Places WHERE Places.PlaceID=" . $placeid);
$currentnum = mysqli_fetch_array($currentnum);
$currentnum = $currentnum[0];
if ($sendback[0] == 'found')
{
$currentnum--;
$change = str_replace($place,'',$sendback[1]);
mysqli_query($conn, "UPDATE Users SET Favorites='" . $change . "' WHERE User = '" . $usercrypt . "'");
mysqli_query($conn, "UPDATE Places SET Places.Favorites=" . $currentnum . " WHERE Places.PlaceID =" . $placeid);
$answer = 'subtracted';
}
if ($sendback[0] == 'notfound')
{
$currentnum++;
$change = $sendback[1] . $place;
mysqli_query($conn, "UPDATE Users SET Favorites='" . $change . "' WHERE User = '" . $usercrypt . "'");
mysqli_query($conn, "UPDATE Places SET Places.Favorites=" . $currentnum . " WHERE Places.PlaceID =" . $placeid);
$answer = 'added';
}
return $answer;
unset($answer);
}
unset($_POST);
?>
The value of z will be evaluated before the xmlhttp object receives the readystate change. You need to put all the code that deals with the returned value into a onreadystatechange function itself, since that is the only function which is guaranteed to be called after you receive an asynchronous response.
You could do something like this:
var xmlhttp = false;
// The rest of your code, but remove the `onreadystatechange` assignment from ajaxSession()
// ...
// ...
function heartCheck() {
perform = 2;
stateCheck();
xmlhttp.onreadystatechange = function() {
z = xmlhttp.responseText;
if (z == 'added')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-on.png";
document.getElementById("favtext").innerHTML="This is a favorite!";
}
if (z == 'subtracted')
{
document.getElementById("favorite").src="http://www.********.com/images/favorite-off.png";
document.getElementById("favtext").innerHTML="Add to your favorites.";
}
}
}
And you'd need to do a handler like that for each time you want to evaluate the AJAX response.
It'd also be most clear to declare the global variables at the beginning of the script like I did above--as #jeroen mentions, it's not explicitly required, but it's good practice and will help you keep track of scope. It's confusing that z is only defined inside the xmlhttp.onreadystatechange function, yet you're using it throughout the script globally. So a simple tip is to put var z = '' at the beginning of your JavaScript to make your intentions clearer (both to yourself and to others who may be viewing your code :))
This is a bit of a mess: You are mixing asynchronous and synchronous javascript in a way you will never know what is what and in what state you are in. Apart from that you are using global javascript variables that you reset and overwrite synchronously while you are using them for your asynchronous requests.
Check for example your firstCheck() function: That will reset your xmlhttp variable (in another function...) and make a asynchronous request but you are already checking for the return value of your asynchronous request in the next line when you are checking the z value. That value (another global variable...) will only be set when your asynchronous call finishes so that logic has no place there.
You need to rethink your architecture keeping in mind that each time you make an ajax request, the result will not be available right away, a separate event will fire - a readyState change - and only then can you do the things you want to do with the returned information from the server.

Is it possible to call PHP-Script from JavaScript section of JSP page..?

I have written following script on server-
<?php
//Create an array
$json_response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$status = "In Progress";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$con)
{
die('Could not connect to database: ' . mysql_error());
}
//Query to select pending queries database
$result = mysqli_query($con, "SELECT * FROM tbl_query_master WHERE status='".$status."' ORDER BY query_date DESC");
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row_array['query_id'] = $row['query_id'];
$row_array['sender_mobile_no'] = $row['sender_mobile_no'];
$row_array['sender_name'] = $row['sender_name'];
$row_array['query_string'] = $row['query_string'];
$row_array['action_taken'] = $row['action_taken'];
$row_array['status'] = $row['status'];
$row_array['query_date'] = $row['query_date'];
$row_array['action_date'] = $row['action_date'];
$row_array['view_status'] = $row['view_status'];
$row_array['read_status'] = $row['read_status'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
Above script returns one JSON object which is useful for me in JavaScript section of my JSP page, but I don't know how to call php-script from the java script section, so need your guidance for the same. Hope you understand what I'm saying Thank you..!
Suppose your php script is deployed to a web server (apache with php mod) and is triggered by some URL, e.g. http://localhost/script.php
Then in your javascript you can do POSt request using jquery:
$.getJSON('http://localhost/script.php', function(json) {
// do what you need with your json data
});
Finally I solved it using AJAX as follows, I don't know whether performance wise this method is correct or not, but perfectly worked for me. Write the following code in your JavaScript section.
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function getDataChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether server response came back with no errors.
{
//THE RESPONSE FROM SERVER. DO YOUR STUFF WITH xmlHttp.responseText
alert("Responce= "+xmlHttp.responseText);
//document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function getData()
{
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "http://yourdomain.com/your_script.php"; // URL of server-side resource.
// Using following way you can send parameter to your script.
//url += "?param1=" + param1 + "&param2=" + param2;
xmlHttp.onreadystatechange =getDataChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
And finally create event to call "getData()" function. That's it. Thank you..!

Need Javascript to locate individual divs looped by PHP

I managed to create a PHP loop that takes an array and create multiple copies of the same button while the buttons each have their own idenfication ("adiv_1" , "adiv_2", "adiv_3", etc). I have a javascript function that is able to take a single button "before it was called just 'adiv'" and change the text of the button if one clicks on it.
However due to the PHP loop which named it "adiv_1 or adiv_2 or adiv_3", I don't know how to create a javascript function that can take one of the buttons looped with a different identification div tag and get javascript to identify each one if one click on a certain button in that group. Can anyone help?
PHP loop that create the group of buttons
<?php
$array_query = mysql_query("SELECT * FROM person_finder_info");
$i = 0;
while($search_row = mysql_fetch_array($array_query)){
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i?>'>Add this person</div></button></p>
<?php
$i++;
}
?>
Javascipt / AJAX function that changes button text (by getting echoed information in PHP file)
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("adiv_1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();
This is rudimentary, but I think you're trying to do something like this, just loop inside of the onreadystatechange function like you did in the other one to display what you want in there to handle all of the buttons.:
<?php
for($i = 0; $i < count($array); $i++)
{
?>
<p><button type="button" onclick='load()'><div id='adiv_<?php echo $i;?>'>Add this person</div></button></p>
<?php
}
?>
<script>
//Changes button text to "You added him!"
function load(){
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
<?php
echo "var divArray = {";
for($i = 0; $i < count($array); $i++)
{
echo "'adiv_".$i."'".($i < $count-1 ? "," : "");
}
echo "};" /// after the loop this will output like var divArray = {'adiv_1','adiv_2', ... };
?>
for (var i = 0; i < divArray.length; i++) {
document.getElementById(divArray[i]).innerHtml(dataFromResponse[i]); // assuming you've processed the response from AJAX into an array
}
}
}
xmlhttp.open('GET','include.inc.php', true);
xmlhttp.send();
</script>
I can't help you with setting up all of the button innerHTML though since I don't know what kind of response you're getting from AJAX. This is just to lead you in the right direction.

pass PHP variable to AJAX call (JS)

I have a script that rotates some images from their current position, there are 4 available rotations(positions) of the image and they are present by the values 0,1,2,3. My problem is that I need two variables from the database in my AJAX call to make this happen. I need the rotation and the src. My PHP currently look like this; Please notice the query where I take out rotation and src.
<?php
$item_number = -1; //This value is -1 in order to make the list start on 0
$rowsize = 12;
$itemArray = array();
$finalArray = array();
$results = 0;
for ($i = 0; $i < $rowsize; $i++) {
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, rotation, src, name FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE house_room1.ref_id = ?');
$stmt->bind_param('i', $i
);
if ($stmt->execute()) {
$stmt->bind_result($z, $rotation, $src, $name);
while($stmt->fetch()) {
$results = 1;
$itemArray['number'] = $item_number;
$itemArray['name'] = $name;
$itemArray['ref_id'] = $z;
$itemArray['rotation'] = $rotation;
$itemArray['src'] = $src;
array_push($finalArray, $itemArray);
}
}
else {
echo 'Something went terribly wrong' . $mysqli->error;
}
$stmt->close();
$item_number++;
}
if($results == 1){
aasort($finalArray,"ref_id");
foreach($finalArray as $arr){
echo '<li id="item-' . $arr['number'] . '" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $arr['name'] . '
<img class="rotate" id="img_'.$arr['number'].'" src="images/house/other/settings.jpg" onclick="rotateObject(this)" alt="'. $src.'">';
}
}
//create a function for sorting
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
?>
It then makes an AJAX call to this file:
function rotateObject(e)
{
//e is handler which contains info about the item clicked. From that we can obtain the image id.
//since the id are of the form img_123(some number), we need to extract only the number.
var img_id = e.id.split("_")[1];
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");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var getEle = document.getElementsByClassName('item' + img_id)[0];
var imagePath ="images/house/objects/stone_chair_1.png"; //This has to be
getEle.src = imagePath + xmlhttp.responseText;
}
}
xmlhttp.open("POST","database/update_settings_rotate.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("item_id="+encodeURIComponent(img_id));
}
This code is then supposed to have the imagePath equal to src. and then the rotation after it, but I don't know how I can get the src for that specific image from the database query made in the PHP file.
Any suggestions or advice on how I can pass that value? Thanks in advance.
One way to pass variables from php to javascript is:
<script>
var myJavascriptVariable = <?php echo $myPhpVariable; ?>
</script>
Hope this help you

Categories