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
Related
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.
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.
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>
Upon suggestion of using Ajax for an html page, I decided to attempt to learn how it works. In my example, I'm just trying to get the response from a php file (which just echoes a simple string as a test) but it doesn't work, in that nothing actually happens.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Incident Center </title>
<!--<link rel="stylesheet" href="http://web.njit.edu/~swp5/assignment/style/style.css">-->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function onsubmit()
{
var sender;
if (window.XMLHttpRequest)
{
sender=new XMLHttpRequest();
}
else
{
sender=new ActiveXObject("Microsoft.XMLHTTP");
}
sender.onreadystatechange=function()
{
if (sender.readyState==4 && sender.status==200)
{
document.getElementById("myDiv").innerHTML=sender.responseText;
}
}
sender.open("GET","proz.php",true);
sender.send();
}
</script>
</head>
<body>
<div class="header">
Incident Center
</div>
<p>
<button onclick="onsubmit()">Test</button>
</p>
<div id="myDiv"></div>
</body>
</html>
As I already mentioned in my comment, you should check the response code of your request to see if something went wrong. Add the following line to the start of your onreadystatechanged function:
alert(sender.readyState + ', ' + sender.status + ', ' + sender.responseText);
Based on this output you can probably determine your error.
Using Opera 11.51 here, it doesn't actually like the fact that you use onsubmit() as a function name. Presumably because onsubmit() is actually already an eventhandler hook of a <button> element itself. I presume other browsers won't like this function name either.
So, first off, rename the function. Let's assume dosubmit() here.
Furthermore, you should wrap a button in a <form> element. And because a default button, acts as a submit button, the form is being submitted, causing the page to reload.
To prevent this, you should let the function return false; and call the function like so onclick="return dosubmit()", if you are going to call it inline like this, or make the button a button of type button, like so: <button type="button" onclick="dosubmit()">
Why don't you use jQuery ? http://www.jquery.com/
Send doesn't actually display anything. Send calls the page and populates two different variables. What send does is populates the "responseXML" and "responseText" properties of the sender. Try after your send:
alert(sender.responseText);
See http://en.wikipedia.org/wiki/XMLHttpRequest
It's much easier to use jQuery to do this as it has a built in AJAX function. Your code would look like this:
jQuery.ajax({
type: 'get',
url: 'proz.php',
error: function(r) {
alert("Something went wrong - "+r);
}
success: function(response) {
alert(response);
}
});
Hope that helps
How to append to textarea with PHP and then refresh the textarea?
THANK YOU
edit:
It should be server triggered from PHP code
The simplest approach would be to have a javascript function that polls the php script using ajax - say every 10 seconds. You could add a timestamp as a parameter to the php function so it only returns the latest log entries.
When the ajax call returns you can append the resulting text to your textarea using javascript.
I could fish out some sample code if you like?
So, here's an HTML file - it has a function to make an AJAX call to a script - log.php that returns some stuff (in this example it's a very simple line of text) and then append this to the text area.
When the script loads we set up a timer to fire every 1000 milliseconds (obviously change this according you your needs).
We've also got a "cancel updates" function and a "start updates".
So - put the html file and the php file (which you need to call log.php - or call it what you like and change the code) into the same directory on your web server and see what happens!.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var http = createRequestObject();
var updateInt=self.setInterval("updateLog()",1000);
function startAutoUpdate(){
if(updateInt==""){
updateInt=window.setInterval("updateLog()",1000)
}else{
stop_Int()
}
}
function stopAutoUpdate(){
if(updateInt!=""){
window.clearInterval(updateInt)
updateInt=""
}
}
function createRequestObject() {
var objAjax;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
objAjax = new ActiveXObject("Microsoft.XMLHTTP");
}else{
objAjax = new XMLHttpRequest();
}
return objAjax;
}
function updateLog(){
http.open('get','log.php');
http.onreadystatechange = updateNewContent;
http.send(null);
return false;
}
function updateNewContent(){
if(http.readyState == 4){
document.getElementById('log').innerHTML = document.getElementById('log').innerHTML + http.responseText;
}
}
</script>
</head>
<body>
<h2>Log</h2>
<textarea cols="80" rows="10" name="log" id="log"></textarea>
<span onclick="updateLog()">Update</span><br>
<span onclick="stopAutoUpdate()">Cancel Auto Update</span><br>
<span onclick="startAutoUpdate()">Start Auto Update</span><br>
</body>
</html>
Here's the php script (very simple)...
<?PHP
/* Log responder script
*
* When invoked this script returns log entries
* as this is a sample it just returns a couple of random items
*
*/
echo "Log Entry ".date("d/m/y h:i:s")."\n";
?>