Problems with ajax div refreshed page calling to parent.window.location - php

I have a parent page that calls to a child page using the prototype.js library. I am having problems redirecting a user based on a php mysql check. I would like to redirect the user to a new page if he gets removed from a mysql table. I have all of the code working correctly except my javascript that is calling to parent.window.location = "http://www.mysite.com/index_use.php?bye";. I used this same exact code on another page and it works totally fine. What could I be missing.
Prototype code:
var myTimer5 = setTimeout("myFunction5();",5000);
function myFunction5() {
var refint5 = 5000;
var myAjax5 = new Ajax.Updater("userguestcheck","userguestcheck.php?id=<?php echo $pid; ?>&prevent_cache="+new Date().getTime(),{
method:'get',
onComplete:function(data) {
var a5 = setTimeout("myFunction5();",refint5);
}
});
}
userguestcheck.php code:
<?php
$iuajksdv = 9846598234;
include "include.php";
session_start();
//Added check for total user guest disconnect
$usercheck = mysql_query("SELECT nickname FROM useronline WHERE nickname = '".$_SESSION['username']."'");
$usercheckslect = mysql_num_rows($usercheck);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<?php
if($usercheckslect == '') {
echo '<script type="text/javascript">
parent.window.location = "http://www.mysite.com/index_use.php?bye";
</script>';
} else {
}
// end disconnnect
?>
</head>
<body>
</body>
</html>

Related

How to get data form MySQL db and output as JSON through PHP, then cross domain ajax request for the data in JQuery

I'm using a digital signage player that allows me to use HTML and javascript to display things , in my case I'm building a menu board with a list of products and prices. I've already created a php system to create entries for products and prices and those values are stored in a MySQL database. What I would like to do is have a PHP script output the mysql data in JSON format, then have a cross domain ajax request for the products and prices to display on the menu board. Unfortunately the menu board cannot support PHP so I have to improvise and get the data through JSON. I've been pulling my hair the past couple of hours trying to figure this out but I can't seem to get it. Any help would be appreciated.
EDIT 1
I have a php script and html file but can't seem to have the data show. Here are the files below
showjson.html
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
url:"http://localhost/blakewilson/api.php",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
$("#userdata tbody").html("");
$.getJSON(url,function(data){
$.each(data.members, function(i,user){
var tblRow =
"<tr>"
+"<td>"+user.postID+"</td>"
+"<td>"+user.postProduct+"</td>"
+"<td>"+user.postPrice+"</td>"
+"</tr>" ;
$(tblRow).appendTo("#userdata tbody");
},
error:function(){
alert("Error");
}
});
</script>
api.php
<?php
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect");
mysql_select_db("dn_name") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM products");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo $_GET['callback']."(".json_encode($arr).");"; // 09/01/12 corrected the statement
?>
EDIT 2
This code give me an alert with success so I know it works.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery PHP Json Response</title>
<style type="text/css">
</style>
</head>
<body>
<div id="msg"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
url:"http://localhost/blakewilson/api.php",
dataType: 'jsonp',
success:function(json){
alert("Success");
},
error:function(){
alert("Error");
}
});
</script>
</body>
</html>
I'm trying to get a few values like postID, postProduct, and postPrice from JSON, but I can't seem to figure it out. I'm very new to jQuery/AJAX etc.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery PHP Json Response</title>
<style type="text/css">
</style>
</head>
<body>
<div id="msg"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.ajax({
url:"http://localhost/blakewilson/api.php",
dataType: 'jsonp',
success:function(json){
// loop through the productg here
$.each(json.members,function(i,dat){
$("#msg").append(
'<div class="members">'+
'<h1>'+dat.postID+'</h1>'+
'<p>Firstname : <em>'+dat.postProduct+'</em>'+
'<p>SurName : <em>'+dat.postPrice+'</em></p>'+
'<hr>'+
'</div>'
);
});
},
error:function(){
alert("Error");
}
});
</script>
</body>
</html>
EDIT 3
What I'm basically trying to do is take this project: http://tournasdimitrios1.wordpress.com/2011/11/04/how-to-generate-json-with-php-from-mysql-and-parse-it-with-jquery/ and make it work cross domain. That is all I need.
EDIT 4
This is the output of the api.php file. It's throwing an error "Notice: Undefined Index"
Notice: Undefined index: callback in E:\xampp\htdocs\blakewilson\api.php on line 13
([{"postID":"8","postProduct":"Synthetic Oil Change","postDollar":"29","postCents":"95","postDate":"2014-08-12 12:11:00"},{"postID":"9","postProduct":"Tire Rotation","postDollar":"16","postCents":"95","postDate":"2014-08-12 12:11:10"},{"postID":"10","postProduct":"Rotate and Balance","postDollar":"39","postCents":"95","postDate":"2014-08-12 12:11:21"},{"postID":"11","postProduct":"4-Wheel Alignment","postDollar":"79","postCents":"95","postDate":"2014-08-12 12:11:35"},{"postID":"12","postProduct":"Cooling System Service","postDollar":"129","postCents":"95","postDate":"2014-08-12 12:11:51"},{"postID":"13","postProduct":"Transmission Flush","postDollar":"189","postCents":"95","postDate":"2014-08-12 12:12:07"},{"postID":"14","postProduct":"AC Performance Service","postDollar":"69","postCents":"95","postDate":"2014-08-12 12:12:19"}]);
the Below link works well for me, you can try
http://jquery-howto.blogspot.in/2013/09/jquery-cross-domain-ajax-request.html
Not sure whats in the
echo $_GET['callback']."(".json_encode($arr).");";
But you might try removing it all down to
echo json_encode($arr);
If you need to send 2 pieces of data back, just build that into another array. Such as:
echo json_encode(array('message' => $_GET['callback'], 'data' => $arr));

Output data from mysql using ajax

I want to view the data on mysql using ajax, im having a problem with my code. This code doesn't alert anything.
index.php
<script>
function forusedata(id) {
$.post('insert_home.php', {BOOKDATA: id}).done(function(data) {
alert(data);
});
}
</script>
});
insert_home.php
else if (isset($_POST['BOOKDATA'])) {
$ENUM = ($_POST['BOOKDATA']);
$result = mysqli_query($con, "SELECT *FROM book WHERE BOOKID='$ENUM'");
while ($row = mysqli_fetch_array($result)) {
echo $row['BOOKCAPTION'];
}
mysqli_close($con);
}
Try that:
script
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Test POST</title>
</head>
<body>
<script type='text/javascript'>
$(document).ready(function() {
$.post(
'insert_home.php',
{
BOOKDATA: 1
}
).done(function(data) {
alert(data);
});
});
</script>
</body>
</html>
insert_home.php
<?php
if (isset($_POST['BOOKDATA'])) {
// search user
echo 'BOOKDATA = ' . $_POST['BOOKDATA'];
}
In you case, you need to transform your mysql result in a text or json format, like echo json_encode($your_var);
Your problem maybe is in your SELECT/mysqli connection.
Try see the return in you Developers Tools (Chrome):
Press F12
Clique in Network tab
Search for your insert_home.php request
Click in Response
Hope this helps

Alternatively load page via php if ajax fails

I am trying to replace the contents of a div with an external file via ajax. the code I am using to do so is :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";
var x = null;
if (window.XMLHttpRequest) {
var x = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
} else {
// fallback
}
x.open("GET", "other_content_1.php", true);
x.send("");
x.onreadystatechange = function() {
if(x.readyState == 4) {
if(x.status==200)
document.getElementById("aside").innerHTML = x.responseText;
else
document.getElementById("aside").innerHTML = "Error loading document";
}
}
}
</script>
</head>
<body>
<div id="aside">This is other content</div>
</body>
</html>
My Questions:
If JavaScript is enabled, then the above code works fine but if JavaScript is disabled, then php should load that file. How d I do this?
If you are going to make your code backward compatible without JavaScript then you really have no reason to use AJAX at all. If you just want the string into your aside Element then do something like:
//first the PHP page 'other_content_1.php'
<?php
$resp = 'Whatever String Response You Want';
?>
//now your other page
<?php
include 'other_content_1.php';
?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Test</title>
</head>
<body>
<div id='aside'><?php echo $resp; ?></div>
<script type='text/javascript' src='should_be_external.js'></script>
<body>
</html>
Note, that if you want this to happen besides onload then you would submit a form using $_POST or $_GET to handle the PHP response.
Have you considered trying the noscript option?
See: What do I do if Javascript is disabled by a client?
However, if you have a lot of pages this might be a lot of work if you use jquery/ajax throughout your pages - which I am guessing you do or loading them in with jquery/ajax would be slightly pointless.
By the time the web page is displayed in the browser and found that JS is not supported, PHP/server already served the page. You can try this.
#aside element can have text & link informing user about not having JS support and take another page
PHP can load the file and serve the content in the new page.
If JS is supported, your above code will be anyway replacing the above link.

Javascript not pulling php variables, page not loading php?

I have a site online to test and edit using "000webhost.com" which has php and mysql.
Either javascript is not pulling the PHP variables or the site is not loading php.
when I load the page I start up chrome code viewer to check the code live. when looking over the default.php (index page) it does not show my php variables.
Javascript
window.onload = function(){
var iso = "<?= $isop; ?>";
var meg = "<?= $megp; ?>";
var mex = "<?= $mexp; ?>";
var mor = "<?= $morp; ?>";
var noc = "<?= $nocp; ?>";
var pye = "<?= $pyep; ?>";
var tri = "<?= $trip; ?>";
var zyd = "<?= $zydp; ?>";
}
php page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Str8nge Brew Calculator</title>
</head>
<body>
<?php
$isop = "1";
$megp = "1";
$mexp = "1";
$morp = "1";
$nocp = "1";
$pyep = "1";
$trip = "1";
$zydp = "1";
?>
<script type="text/javascript" src="calceve.js"></script>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
....
</body>
If you want your calceve.js file to render the PHP contained within, you'll need to change the file extension to .php, src="calceve.php". Whenever I have a javascript file that contains PHP, I use something like myfile.js.php, just to keep it straight in my head what the file actually is.
I fixed it by taking all the javascript code and moving it inside the tag on the php page. not sure why this fixes it exactly but it works. I did also move the window.onload so the var are first

ajax: responsetext returns my entire php code locally

I found a good Tutorial: tutorial
but it doesn't work locally.
The Problem is, that the responsetext returns my entire php code.
I double-click at my ajaxclock.html and use Firefox.
Surprisingly, it works on the server.
Here the code:
ajaxclock.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>AJAX Tutorial</title>
</head>
<body>
<div id="time"></div>
<button onclick="getTime();">Aktualisieren</button>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
script.js
var req = getXmlHttpRequestObject();
window.onload = getTime();
function getXmlHttpRequestObject()
{
if(window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert('Ajax funktioniert bei Ihnen nicht!');
}
}
function getTime()
{
if(req.readyState == 4 || req.readyState == 0)
{
req.open('GET', 'ajaxclock.php', true);
req.setRequestHeader("Content-Type","text/plain");
req.onreadystatechange = setMessage;
req.send(null);
}
}
function setMessage()
{
if(req.readyState == 4)
{
var response = eval('(' + req.responseText+ ')');
document.getElementById('time').innerHTML = response.time;
}
}
ajaxclock.php
<?php echo '{"time": "'.date("H:i:s").'"}'; ?>
Surprisingly, it works on the server.
PHP is a server side technology. It will only ever work on a server (specifically a server configured to run PHP programs).
If you use it without such a server then nothing will execute the PHP and it will be delivered to the browser in its raw state.
I had the same problem. Did not find any reason until I realized that the LiveServer Plugin in Firefox (97.0.1 (64-Bit)) didn't execut the php file. For whatever reason. I use XAMPP (v.3.2.4) and tried it the "old" way via: localhost/project/index.php and it worked fine for me again.

Categories