Alternatively load page via php if ajax fails - php

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.

Related

self processing php pages with ajax

re this post AJAX Post to self in PHP
When using exit() doesn't something have to be printed before this call?
I have written markup/ph with references to external css php scripts. The script uses print (or echo) and a
call to header('type: text/css'). Isn't this useful or necessary in self processing php pages? I find
them endlessly useful. A whole site can be displayed in any state by one page using get queries and posts
from forms. I remember the text I was reading early on when beginning to learn php asserted that when
the page submits to itself, the browser will automatically use asynchronous requests. But in certain situations
an explicit ajax call is useful.
Here is what I am doing and what I am trying to do.
I have a text field and a button in a page
I write text to the text field and click the button
The javascript click event handler for the button gets the text field value
and appends it to a get query attached to the url in the request. The method is get
edit: to specify the environment in which this has been successful.
I am using Firefox v12.0 On Mac OSX with pre-installed apache server on local machine.
(anyone with a Mac running OSX, there is a pre installed apache server, but activating php requires
editing the httpd.com file to un comment the line(s) that load the php module. Also, there is a line
that tells Apache what extensions to use to look for and execute php code. You also must tell it
to take index.php as an index file to run the php in it and have it act as a directory index file)
the javascript code:
function _FETCH()
{
this.init = function(oName, elem, txt)
{
var but = document.getElementById(elem);
but.addEventListener('click', function(){ oName.req('GET', self, '', null, oName, txt) } )
}
this.req = function(method, url, type, msg, oName, txt)
{
var field = document.getElementById(txt);
url+="?ajxTst="+encodeURIComponent(field.value);
var it = new XMLHttpRequest();
it.open(method, url, type);
it.setRequestHeader('Content-Type', 'text/plain');
it.onreadystatechange = function()
{
var elem = document.getElementById('well');
switch(it.readyState)
{
case 0:
case 1:
break;
case 2:
case 3:
elem.childNodes[0].data = " waiting";
break;
case 4:
oName.handleResponse(it.responseText);
break;
default:
alert('ajax processing error');
break;
}
}
it.send(msg);
}
this.handleResponse = function(resp)
{
var elem = document.getElementById('well');
elem.childNodes[0].data = " "+resp;
}
}
The php, javascript and markup in the page:
<?php
/*
created 11/4/2014
*/
$_self = basename($_SERVER['PHP_SELF']);
if($_POST || $_GET)
{
if($_GET['ajxTst'])
{
header("Content-Type: text/plain");
print $_GET['ajxTst'];
exit();
}
}
?>
<!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>JS lab 2</title>
<link rel="stylesheet" type="text/css" href="local.css" media="screen" />
<script type="text/javascript" src="local.js">
</script>
<script type="text/javascript">
//<![CDATA[
var self = "<?php print $_self; ?>";
window.onload = function()
{
var ajx = new _FETCH();
ajx.init(ajx, 'send', 'tlk');
}
//]]>
</script>
</head>
<body>
<div class="panel">
<p class="title">Js Lab 2</p>
<p class="norm">Lab 3 home</p>
<p class="norm">Work with ajax and self processing page (this)</p>
<hr />
<p class="norm" id="well"> idle </p>
<p class="norm">
<input type="text" id="tlk" value="" /><input type="button" id="send" value="send" />
</p>
</div>
</body>
</html>
I hope That someone looking for this will find it. It took me a while to get it right

jquery ui button not appearing after ajax call

I have a jquery ui button in a main page (index.php) which appears and works fine. In the main page I have a div <div id="cardarea"> which I use as a placeholder for dynamic content. The dynamic content is stored in another file (cardarea.php) and elements from this file is displayed dependent on the $_GET['key']; variable it gets from input forms in the main page.
Now the problem is that when I try to include the same jquery ui button (<settingsbtn>) in a part of the contents in the file cardarea.php, this does not display.
The javascript code and definitions are included in the header of index.php. I guess the button in the file cardarea.php cannot reach this information, or that there is an error in my javascript definitions. I've tried including the same javascript code and definitions also in the file cardarea.php, but with no effect.
I'm really quite at a loss of what is the problem here. I will include the javascript definitions, but I'm not sure what other code may be relevant to decifer this problem. Please let me know what additional information may be useful to find the problem, if applicable. Thanks.
Javascript:
$(function() {
$( "settingsbtn" ).button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
});
});
</script>
INDEX.PHP
<?php
include 'functions.php';
include 'incl_ajax.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" />
<link href="css/amariffic.css" rel="stylesheet" type="text/css" />
<title>Test</title>
<link href="css/smoothness/jquery-ui-1.10.3.custom.css" rel="stylesheet">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui-1.10.3.custom.js"></script>
<?php include 'snip_javascript.php'; // innholder både kode og css-link. ?>
</head>
<body class="body">
<settingsbtn></settingsbtn>
<a href="javascript:ajaxpage('_cardarea.php?key=5', '_cardarea');" class='nodecor'>Show</a>
<div id="_cardarea"></div>
</body>
</html>
CARDAREA.PHP
<?php
include 'functions.php';
$key = $_GET['key'];
if ($key == '5') {
echo '<div>';
echo 'Button: <settingsbtn> </settingsbtn>';
echo '</div>';
}
?>
You have to run the Javascript function you already wrote again after you complete the AJAX request.
Your function you have to run again:
$(function() {
$( "settingsbtn" ).button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
});
});
I actually ran that function in my Chrome console after the AJAX call, and the second button was correctly shown.
Just define in your javascript functions:
function initButtons(){
$( "settingsbtn" ).button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
});
}
Then overvrite your previously pasted javascript code with:
initButtons();
In the end, you have to add this function call to the end of your AJAX callback function:
initButtons();
put it just right after the instruction where you append the code you recieve from AJAX to the HTML.
EDIT: i looked at your code and i saw that you should put this function here:
function ajaxpage(url, containerid){
[...]
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
initButtons();
}
[..]
}
Perhaps delegate() is what you are looking for.

Passing js variable into php string

I need a little bit of help im trying to page a js variable into a url thats being parsed in php using file_get_contents. Im not sure where to start to do that.
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
</script>
<?php
$ticker = js_varable_here;
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re');
?>
any advice is appreciated, like i said im in the dark on this one.
Here's an example using jquery.
Javascript:
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
$.post("/somephp.php", {ticker: js_variable}, function(data) {
// returned from php
});
</script>
PHP:
<?php
$ticker = $_POST['ticker'];
$file = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re");
?>
Expanding on what Jashwant says...
PHP is a server-sided language, which does work behind the scenes. Javascript is client-side, which runs and executes code on the local client's machine (ie through the browser).
You can however use AJAX (Asynchronous JavaScript and XML) so the local client sends HTTP requests to the server without reloading the current page. For instance, you can use AJAX to send the contents of the variable to the server.
For easier usage, you should check out jQuery's methods regarding ajax calls. See: http://api.jquery.com/jQuery.ajax/
Hope it works well.
Heres how you can do it with jquerys post() and then return json, you could build the result as you expect to output within the php part or you could use jquery to loop with each() through the result.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
if(!empty($_POST['s'])){
$ticker = $_POST['s'];
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s='.$ticker.'&f=soac1p2ghjkj1re');
header('Content-Type: application/json');
echo json_encode(array('result'=>$file));
}else{
echo 'Request not allowed!';
}
die;
}
?>
<!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></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script>
var js_variable = "appl+goog+fb+mfst+nflx";
$.post('this_script.php',{s: js_variable}, function(data) {
$('#divResult').replaceWith('<div id="divResult">'+ data.result +'<div>');
});
</script>
</head>
<body>
<div id="divResult"><div>
</body>
</html>

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.

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

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>

Categories