How to capture the output of a php from javascript - php

I have written few php files which sit in a server. The output of the php would be as follows:
172.xx.xx.xx/myphpfile.php?arg="abc"
Output
{
status: "ok",
result: "asdsdf"
}
My requirement is to call this php api (172.xx.xx.xx/myphpfile.php?arg="abc") from my javascript, parse the output and draw a chart in the page. To summarize the following are my doubts.
How to call a remote php file from javascript?
How to capture the output of a php file in a javascript?

Remote PHP? Due to the same origin policy you have to write the PHP so it emits JSONP. (That link also explains how to use it from JS).
Alternatively, and with more limited browser support, use CORS with XHR

First of all, javascript is client-side and php is server-side. The web servers outputs text to your browser and it doesn't know about server techniques used.
For fetching and manipulating the data, have a look at jQuery and jQuery ajax

Both can easily be done with javascript (and even easier with jQuery). If your resulting page is in JSON format (which it appears to be), you can simply do..
$.getJSON('172.xx.xx.xx/myphpfile.php', 'arg=abc', function(obj){
alert(obj.status);
});
More info: http://api.jquery.com/jQuery.getJSON/
If the API file is not on your server
If the API is not on the same domain as your page with the JS, you will need to create your own PHP page to read the remote file, and dump its contents locally to the domain.
getJson.php
die(file_get_contents('172.xx.xx.xx/myphpfile.php?arg='.$_REQUEST['arg']));
JS
$.getJSON('gtJson.php', 'arg=abc', function(obj){
alert(obj.status);
});

You have to use Ajax.
Avoid the classic method, prefer using a framework like jQuery or ExtJS, it will be easier and cross-browser.
http://api.jquery.com/jQuery.ajax/
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.Ajax

Here is the code which I use
<script type="text/javascript">
//Global Variables
var xmlHttpFP;
if (window.ActiveXObject)
{
xmlHttpFP = new ActiveXObject("Microsoft.XMLHTTP");
}//End if
else
{
xmlHttpFP = new XMLHttpRequest();
}//End else
//Function To fetch Data From Server
function LoadFPSummary()
{
xmlHttpFP.open("GET","172.xx.xx.xx/myphpfile.php?arg='abc'");
xmlHttpFP.send();
document.getElementById("response").innerHTML = xmlHttpFP.responseText;
}
xmlHttpFP.send(null);
</script>

AJAX is the tool you need.
Read more here.

You have to move AJAX technology
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("172.xx.xx.xx/myphpfile.php?arg=abc",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Get from PHP</h2></div>
<button type="button" onclick="myFunction()">Load</button>
</body>
</html>

Related

Using AJAX for GET data from other server on Mouse Over

I am searching for this from yesterday, Do not know, I am unable to implement, or going in wrong direction.
My currently ajax function which is working with local server
function tooltipajax(r_ID)
{
var str ;
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('span'+ r_ID).innerHTML = xmlhttp.responseText ;
}
}
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
xmlhttp.send();
}
PHP code:
print("<tr bgcolor=\"#EEEEEF\">");
print("<td class='normal' id=\"serialno\" onMouseOver='tooltipajax(this.id)'>
<a class=\"tooltip\" >Serial Number <span id=\"spanserialno\"
class=\"custom info\"></span> </a></td>");
print("<td bgcolor = \"#FFFFFF\" ><b>$serial</b></td>\n");
print("</tr>\n");
How can I get data from another server?
xmlhttp.open("GET","accounteditajax.php?key=" +r_ID,true);
I want to get from
http://iphere/filename.php
If you use use jQuery like so, this works.
function tooltip_ajax(r_ID) {
$.ajax({
url: "http://iphere/filename.php?id=" + r_ID,
context: document.body,
success: function(data) {
if(data) {
$('span' + r_ID).html(data);
}
}
});
}
That's tested with a different server and it works.
In order to retrieve data from another server using AJAX, you will need to utilize JSONP. This is due to Cross-Domain restrictions on AJAX requests. To expand on this further, if you wanted to make an AJAX request from a page located at http://test1.com, to a page / script located at http://test2.com, you would not be allowed.
Check out this article for more information: http://www.jquery4u.com/json/jsonp-examples/
Basically, JSONP involves adding a temporary SCRIPT tag to the page, which CAN load external content. The URL for this SCRIPT tag contains data, and a callback function name. The JSONP should then respond with the data, enclosed in a call to that function. Of course, the one downside is that the target server must support JSONP requests.
One alternative is using a bridge PHP script locally, that utilizes CURL to make the request, and return the information to your page, via AJAX.
For a bit more information regarding utilizing CURL in PHP, take a look at this article: http://codular.com/curl-with-php

javascript commands not executing after ajax loads PHP file

I have a PHP script being executed by AJAX, the PHP script loads everything fine except for js scripts in the actual PHP file which I am using to close divs(if the PHP file isnt run via AJAX all the scripts work FYI)..
this is the script not being run in the PHP file by ajax
echo "<script> closeOne('" . $postid . "'); </script>";
The JS scripts to close divs are included in the header of the page
This is the AJAX script I am using
<script type="text/javascript">
function mainload(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest(str);
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("loadmain").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mainload.php?page="+str,true);
xmlhttp.send();
}
</script>
Any help would be appreciated.
JS in the ajax response is not executed by default. You have to parse and identify JS statements, then run them using eval function of js. See this code as an example to start your own code:
var sc=xmlhttp.responseText;
sc=sc.replace(/[\n\r\t\v\u00A0\u2028\u2029]{1,}/gm, ''); //Remove all types of White Space
sc=sc.match(/<.*?script.*?>.*?<\/.*?script.*>/gm); //divide into array, all the script tags
Then you will loop each of the 'sc' and run the following in the loop:
abc=loop_var.replace(/<.*?script.*?>(.*?)<\/script>/gm, "$1"); //remove script/open close tags and get JS only
eval(abc);
If you add script element to innerHTML of a DOM element, JS wont run immediately.
because that script element is just added.
and that tag is not going to get parsed at all.
Ideally you should send a response in form of a JSON wrapped function.
You can send output like this from the PHP page.
echo "(function(){ closeOne('" . $postid . "'); })";
In response, you could evaluate this String containing the function using eval.
codeToExecute = eval(xmlhttp.responseText);
then call the function,
codeToExecute();
Note: sending functions from server and directly executing it using eval could be a security concern.
be careful and better use some JS libraray function to evaluate the string into a JSON object.
There will be String-To-JSON convertersin jQuery,prototype and sencha's libraraies.
Better use them or if the browser supports, JSON.parse is also a good option.
But I hope the concept is clear to you.
Alternatively,
You could just send the post id from server in a JSON and call closeOne on the response like this:
in PHP,
echo "{post_id:".$postid."}";
and when the response comes,
responseObject = eval("("+xmlhttp.responseText+")");
closeOne(responseObject.post_id);

How can I call a PHP file with GET on an AJAX request?

I am trying to get data back from a PHP file assigned with GET parameters in an AJAX request:
xmlhttp.open("GET","getMyData.php?name="+name+"&email="+email,true);
Can I call the getMyData.php like that, or it has to be in the root of the project? Now is in the same directory as the javascript file.
Also, if possible, a small example of how to insert the returned data into an input field.
Thanks a bunch!
Here the example
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//xmlhttp.responseText; //content
document.getElementById("myDiv").innerHTML=xmlhttp.responseText; //write inside myDiv
}
}
xmlhttp.open("GET","getMyData.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+name+"&email="+encodeURIComponen(email));
xmlhttp.send();
}
Look here get more information and example
Have a look at relative and absolute paths. You will understand how the /, ../ etc. work. You will also see that your example is correct if the PHP file is in the same folder as your web page where the javascript is executed.
About the last part, I'm cutting off a little bit the code (that you can find fully here for example), but here is the point:
if (xhr.readyState === 4 && xhr.status === 200) {
// The datas returned by PHP are in the variable 'xhr.responseText' or 'xhr.responseXml'.
// In this case you can add straight the HTML into a DIV, but you usually have datas in JSON.
// To "transform" your JSON string into a javascript object, use the following:
// var obj = JSON.parse(xhr.responseText)
document.getElementById("myDiv").appendChild(xhr.responseXml) // Don't use 'innerHTML', it is evil.
}

Constructing a more efficient javascript user-based chat

I am going to bed soon, so I will not be on until the morning, but I have been struggling with trying to find a javascript/jquery method that solves my problem. I am trying to make a chat box feature where once a post is submitting it is then echoed back out and users on both ends can see it. I know that I need to use javascript and or jquery. Right now I am using a very inefficiency system:
<script language='javascript' type='text/javascript'>
setInterval( function() {
$('#responsechat').load('echogetconversation.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>');
}, 100);
</script>
The only reason that I am using it is because it is the only way I know how to project new posts to both users. I was wondering if someone knew a way to do this. Once a post is submitted, it fades into a div and both users can see it, not only the user who submitted it, so it is like a facebook chat in a way. I have no idea about any possible solutions, and have done research, but I could not find any that i could get to work. Any help and/or insight to what I should do next would be appreciated.
What you are looking for is ajax long pulling, also called Comet (it's a silly pun). The basic idea is simple--instead of polling the server, you send your ajax request and the server blocks on it until it gets a new message.
"Blocking" here simply means it does not send a response. You get your request then first up a thread (is that what you would do in PHP? I've only ever used node.js for this) and wait until something changes before sending the response back to the client.
Once the client has a response, it sends another request immediately.
There is one other trick: requests can time out. This means that the server should send a response back after a certain time even if nothing has updated.
This methodology is good if you have to support older browsers; if you can ignore those and stick to newer ones, you can use "websockets".
There are libraries that help you use websockets or fall back on Comet. I think the most popular one is socket.io.
Coincidentally, if you're not tied to PHP, I really suggest using a different server. node.js is a great option--it is a natural fit for this sort of problem and you can write the server-side code in JavaScript, which you already know. Even Facebook--the bastion of PHP--used a different language (Erlang) for their chat backend.
So, in summary: use socket.io. If you can, try using a different backend, although PHP is fine too.
If you don't want to use another language you can simply do it by AJAX..
Just set an interval and update the PHP-generated div's html.. and when you send a message then the reply would be the updated div -html so that both you and the user can assure that their message is posted successfully.. There's a snippet of my own chat system code : look:
function updMsg() {
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()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","Msg.php?pg=1",true);
xmlhttp.send();
}
function sendMsg()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
msg=document.getElementById('msgfrm').value;
sender='<?php echo $name;?>';
xmlhttp.open("GET","Msg.php?msg="+msg+"&sender="+sender+"<?php if(isset($_GET['a']) && $_GET['a'] = 1) { echo "&a=1"; } ?>" ,true);
xmlhttp.send();
document.getElementById('msgfrm').value="";
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
}
function interval() {
updMsg();
t=setTimeout(interval(),500);}
interval();
This code is actually only PHP and Javascript. It's not sufficient to include the whole jQuery Library just for using the AJAX capability. right?

HTML / AJAX / PHP synchronous harmony? Could asynchronous ever work?

I've been working out the best way to bridge javascript to get data from php with Ajax.
And all while trying to keep the lines of code to a minimum and with greatest speed.
I've come up with a way to pass AJAX a value by Object so it can be altered as if it was passed by reference and then send it back. But so far, I can only do this synchronous as the data will not be available until AJAX completes.
Point is:
I've been looking for an easy way access all of my PHP content with javascript.
Build a simple javascript(GetSomePHPstuff) API if you will.
As I am a novice at web programming, I would love to hear some input and feedback on this.
This is what I have come up with.
In this example, I am sending a text value from html through javascript to ajax to php and php sends it back to ajax back to javascript back to my html page.
Here is our simple HTML type file.
TEST.html
<script language="javascript" src="ajax.js"></script>
<input type="text" id="text"/>
<input type="button" value="Return Text"
onClick="alert(ajaxReturnText(document.getElementById('text').value));"/>
Here is the ajax/javascript file.
AJAX.js
function ReturnText(input, output){
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){
output.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET","php.php?text="+input,false);
xmlhttp.send();
}
function ajaxReturnText(input){
var output = new Object();
ReturnText(input, output);
return output.value
}
And here is the PHP file
php.php
<?php
function ReturnText($text){
return $text;
}
if($text = $_GET["text"]){
echo ReturnText($text);
die();
}
?>
This cannot work asynchronously this way. You have to understand that this line:
output.value = xmlhttp.responseText;
is going to be executed after ajaxReturnText() is done if you define it asynchronously. If you defined synchronously then ajaxreturtext() will not proceed until the request is done. To me your problem is that the code must respect the foundamental rules, in your case this is that you have to remember to define what to do after ajax inside this the "update function here:
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
output.value = xmlhttp.responseText;
/*define what to do next here*/
}
So you never call code to be executed asynch directly but insted you call it from inside the proper function, see complete code:
<html>
<head>
<script type="text/javascript">
/*to be called synch*/
function ReturnText(input){
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){
/*here define what to be called asynch*/
ajaxReturnText(xmlhttp.responseText);
}
}
xmlhttp.open("GET","php.php?text="+input,true);
xmlhttp.send();
}
/*to be called asynch*/
function ajaxReturnText(input){
var output = new Object();
output.value =input;
alert(output.value);
document.getElementById('test').innerHTML=
"This is the value of the object: "+input;
}
</script>
</head>
<body>
<div id="test"></div>
<input type="text" id="text"/>
<input type="button" value="Return Text"
onClick="ReturnText(document.getElementById('text').value);"/>
</body>
</html>
If you want to experience more I have a class for it: see here
You can receive server-generated events asynchronously in realtime without any problem, I did it long time ago before any AJAX. Now this way called Comet. I used frames and script techniques. Now it's better to do with ajax, but here some problems you have to solve.
You can receive data in realtime using .onreadystatechange callback with .readyState==3.
This callback generated every time when new data come from server. You need to remember last .responseText size and read new data from this point to end, then store new size.
Problem number one:
IE generate exception when you try to read .responseText before event with .readyState==4. So server part must drop connection after every event to make readyState readable and force client recreate it again (see 'long polling'). If browser is not IE you don't need to recreate connection every time. But here we face problem number too.
Problem number two:
.responseText size. It can be very big if connection used for long time. So you need to implement (events or bytes send) counter on server or client and recreate connection by counter overflow.
One more problem - timeouts. You need to disable timeout on server (see set_time_limit()) and send something insignificant (space forexample) to browser when you have no events to prevent browser timeout.
Usually you need two channels to server: upload and download. You have upload channel with jQuery or another framework but I don't sure about download. I afraid you can't use readyState==3 technique with jQuery. May be APE Framework can do it?

Categories