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);
Related
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
I've trying to send some infromation to a php file and display the result returned. First of all I'm not receiving any results from php file i.e. no value in xmlhttp.responseText. Instead of responseText, I tried putting 'something else' which made no difference. But when i comment out //if (xmlhttp.readyState==4 && xmlhttp.status==200), the result briefly appears.
What have I done wrong?
Ajax code looks like this:
var div = 'display';
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
writeBack (div, xmlhttp.responseText+'something else', 'red');
}
}
xmlhttp.open("POST","update_profile2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("rr="+id);
Php code:
..
if(isset($_POST['rr']))
{
die('connection made');
}
..
Every problem I've ever had with AJAX is usually caused by trying to submit an AJAX request using a 'submit' button in a form. If you are doing that, make sure you stop the .submit() .... Also, if you use jQuery, your AJAX code will look sooooo much better :)
As others users say with jquery the code looks much better.
However I am quite sure your problem is with this line:
xmlhttp.open("POST","update_profile2.php",true);
The request above access directly the update_profile2.php and gets back the entire content of the php page, not the output elaborated by the page.
This is way you access the page without asking the web server (with the php engine) to serve it for you. And of course the http call fails so the condition && xmlhttp.status==200 blocks the execution of the next instruction that fills in the div.
use instead:
xmlhttp.open("POST","http://localhost/update_profile2.php",true);
This will send a ajax http request to apache, il will run the php page and returns the answer of the page!
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>
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?
I have checked the suggestions that came up before posting, hope I didn't miss anything now.
I have a piece of code that I use to get txt-files for my website but now I need to redo the code so it gets both txt and php-files, but it just won't read the php-script. I'm a bit afraid to mess up the code at this moment so I'm walking on the safe side of the road and ask here if anyone knows a good add to the code. It's quite embarrasing that I still have codes for IE 5&6 in it, so if you wish to remove that at the same time, go ahead. I won't hate you for it, I promise.
UPDATE:
I have four files:
html - Calling the .js-file with the ajax-script.
js - With all my javascript(and simular)-codes.
php - That contains... Well, you get the point.
I have to call the php-code somehow, like I call my txt-files, but of course so the php works as it should. I am very new to AJAX, so I don't dare to mess around with this code at the moment, but I figured that I might be able to add some kind of if-statement that calles the php-file as it is intended to be.
But I have no clue what that code might be and where to put it for things to work accordingly. Any help would be appritiated and credited in the code, of course.
Heres the AJAX-code that is contained within the .js-file:
/*Load the link.*/
function loadXMLDoc(url)
{
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("leftCol").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
/*Highly unnecessary, but I wanted to see if it worked and it looks better on the .html-page.*/
function get_link(url)
{
loadXMLDoc(url);
}
As the above commenter said, it is best to use a 3rd party tool for such things - if for no other reason than to greatly increase cross-browser compatibility.
if you were to use jQuery, the code would be reduced to.
function get_link(url)
{
$.ajax({url: url, success: success:function(result){
//the code / resulting string will be in the result variable.
}});
}
jQuery CDN Hosted: http://code.jquery.com/jquery-1.5.min.js
Let me ask this... if you change your code to
function get_link(url)
{
window.location=url;
}
Does your web browser successfully navigate to the page you are trying to retrieve via AJAX? If not, there is likely a problem with your PHP syntax.
it just won't read the php-script
It's a rather vague statement, but here are few pointers that could be the solution :
PHP file are interpreted on the server so when you do an Ajax call to that page what you receive on the client side is the result of that php script, not his content.
You are assigning the result of the query directly in the HTML, if the result contains data that does not render anything, you won't see anything. For example the content <script>Text here bla bla bla</script> will just show nothing.
If you want to make sure you get some data back from a file, you can just alert the content when you receive it.
Make sure your path to your PHP page is correct. To detect if the file is not giving a 404 error code or any other error code, you can use this :
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementById("leftCol").innerHTML = xmlhttp.responseText;
} else {
alert("Error " + xmlhttp.status);
}
}
}