Can someone help me out? I have an html file that calls a php script via ajax and displays a random number that the php script generates. It works just fine when both files are on the same domain, but if the 2 files are located at different domains, which is what I need, nothing happens. Can someone help me fix this.
The code for the HTML file is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
}, 5000); // the "5000" here refers to the time to refresh the div. it is in milliseconds.
});
// ]]></script>
</head>
<body>
<div id="divToRefresh">Loading users...</div>
</body>
</html>
If the line
$('#divToRefresh').load('http://www.OTHERDOMAIN.com/random.php');
is changed to:
$('#divToRefresh').load('random.php');
and placed in the same folder as the html file all is well.
The code for the php file is:
<?php
$random1 = sprintf("%02f", rand(0,9212));
echo $random1;
?>
What would the revised code that would allow cross domain ajax calls look like? I was reading documentation that talked about a json request wrapper, but I did not get where it was going. Any help would be hugely appreciated.
you are not able to use ajax cross domain its not possible, you have the following options though:
1.do the ajax to your own page and make a curl call to that page..
2.do $.getJSON('ur', variables, function(data){}).
there are few other solution, but those 2 are basically your best options
here is how getJson works:
On your server you should have a page that is ready to receive the $_GET sort of like an API or normal ajax call would do with $_POST.
should look something like :
<?php
if(!empty($_GET['jsoncallback']) && !empty($_GET['variable'])){
/* do whatever you like with the variable you get as get
*
*
*
**/
// echo the name of the callback function + the variables you want to receive back in JS
echo $_GET['jsoncallback'].'('.json_encode($jason_echo).')';
}
?>
Your JS or page you are going to do the call from should look something like:
$.getJSON("SomePage/PagethatTakesTheGet.php?jsoncallback=?", {variable:15}, function(response){
// do whatever you want with response.
});
Related
I have a page where I am loading external site content through Jquery Post method to my PHP file (due to cross site issue) which looks like this.(back.php)
$url = $_POST['url'];
echo file_get_contents($url);
And My HTML code looks like this
$.post ("back.php",
{
url : "http://www.ralphlauren.com/product/index.jsp?productId=2130294&cp=1760781.1760809&ab=ln_men_cs1_polos&parentPage=family"
}
,
function (data)
{
document.getElementById ("output").innerHTML = data;
}
);
The site content is loading fine, but the script is not loading, because of that I am getting error while changing any options which should execute the script.
I tried different methods but no use.
How Can I achieve to load the script also.
EDIT
It looks like my question was not clear.
The issue is, the content along with script of the given URL is loading in my page. The external URL contains some embedded scripts which is not executing.
Here is an example of the external site
<html>
<body>
Hello
<script>
alert("This is some message");
</script>
</body>
</html>
Now if we run this page directly in browser, it shows the text "Hello" as well as alert message, however when I load this file though the above method (POST/Jquery), it is showing "Hello" but not displaying the alert message (means, not executing the javascript).
Please help me to execute that script.
You should use $(function() { }) to load the js when execute it !
Loading HTML with elements into the page is not very stable. This will not work cross-browser cause some browsers don't run the onload in the external page (fetched with ajax).
So don't do this, run the javascript you need in the callback op you $.post.
edit
see also this
Not sure why yours is not working but, try this, seems to work perfectly:
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['url']){
header('Content-Type: text/html');
echo file_get_contents($_POST['url']);
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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<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 charset="utf-8" type="text/javascript">
$(function() {
$.post ("back.php",{
url : "http://www.ralphlauren.com/product/index.jsp?productId=2130294&cp=1760781.1760809&ab=ln_men_cs1_polos&parentPage=family"
},function (data){
document.getElementById ("output").innerHTML = data;
});
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Error may be caused for following reasons:
May be you forget to load jQuery library.
You forget wrap you code within DOM ready ie. $(function() { })
If you are trying to retrieve data from different domain, then you should try with jsonp type request.
I would like my PHP script to be able to access the width of the browser window. I've been reading up on this, and PHP can't access this information itself, but Javascript/jQuery can, and can then pass it to the server using AJAX, so PHP can get at it.
Following a few solutions online I've written the following test file, and called it "test.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>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<?php
if (!isset($_POST["window_width"])) {
?>
<script type="text/javascript">
var window_width = $(window).width();
$.ajax({
type: "POST",
data: "window_width="+window_width,
});
</script>
<?php
}
if(!isset($_POST["window_width"])) {
echo "not set";
}
?>
</html>
Loading test.php displays "not set" which shows that the window_width variable is not being picked up by PHP. This seems weird to me, because Firebug shows that the variable is there (set at 1366 on my computer, as this is the width of my browser).
How can I ensure that $_POST["window_width"] is set so that I can access it using PHP?
Description
I dont understand whats you goal ist but it looks like you forgot to wait till the DOM is ready.
Sample
$(function() {
var window_width = $(window).width();
$.ajax({
type: "POST",
data: "window_width="+window_width,
});
});
Your server side code doesn't pause processing to wait for the JavaScript to run. You are dealing with two separate HTTP requests here.
The browser requests the HTML document
Since $_POST['window_width'] is not set for that request. PHP returns an HTML document that includes the script. Since $_POST['window_width'] is still not set for that request, it also echos not set.
The browser receives the HTTP response and parses it. As part of this process, it runs the JavaScript.
The JavaScript makes a POST request to … wherever jQuery sends requests to by default since you didn't include a URI (which a very quick test suggests is the current URI).
For this request $_POST["window_width"] is set and included in the document returned to JavaScript.
Since the JavaScript doesn't have a success handler (or any other code that runs when the HTTP request comes back) the browser doesn't do anything with that document.
Ajax is a shorthand way of saying "Talk to the webserver with JavaScript". It doesn't stop HTTP being a stateless Request-Response protocol.
You haven't stated your usecase for getting the window width (which can change after the page has loaded), so it is hard to suggest a good solution to whatever problem you have. (You appear to have asked an XY Problem).
The two common reasons for wanting to know the window width are:
Statistics — in which case you can just process the data in PHP and not worry about rendering it to the client
Changing the layout — which is usually better achieved with CSS media queries
I don't think you need to use ajax in this case, the 'outer' (?) page needs to receive the data, not the 'inner' ajax request.
<?php session_start(); ?>
<!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>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<?php
if (!isset($_POST["window_width"]) && !isset($_SESSION['window_width'])) {
?>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="window_width_form" style="display:none;">
<input name="window_width" id="window_width" value="" />
</form>
<script type="text/javascript">
$(function(){
$('#window_width').val($(window).width());
$('#window_width_form').submit();
});
</script>
</body>
<?php
}
elseif (isset($_POST['window_width']) && !isset($_SESSION['window_width']))
{
$_SESSION['window_width'] = $_POST['window_width'];
exit(header("Location: {$_SERVER['PHP_SELF']}\r\n"));
}
if(!isset($_POST["window_width"]) && !isset($_SESSION['window_width'])) {
echo "not set";
}
?>
</html>
Try
$.ajax({
url : "your url goes here"
type: "POST",
data: {"window_width":window_width}
});
I'm trying to get access to a Javascript API, I created, on other sites. The javascript is at https://ksc105.kscserver.com/query.js and it pulls ajax calls to https://ksc105.kscserver.com/suggestions.php (?action=getall). Of course using this on https://ksc105.kscserver.com/index.php works.
However I'm trying to use import that javascript into another domain site. I know cross-domain ajax calls do not work, but I supposed that if the ajax call is made from a javascript on that site that it was going to work. I supposed this based on Google's Map API. I'm pretty sure it uses ajax.
How do I get ajax to work like the Google Map API? Where any website can add my script and use its functions?
In firebug, I get the request to fire but I just get an empty return but it should not be returning empty. In IE9, I get the error "SCRIPT5: Access is denied." / "query.js, line 62 character 5".
If you go to https://ksc105.kscerver.com/index.php and type 3 or more characters in the box you should get "suggestions" much like Google Search. I need the same thing to work on any other website without a server proxy. You can use "Test" as it pulls a bunch of test data.
Try using AJAX callbacks. jQuery does this well but as a raw example, if you load some JSON with a callback function (From a <script> tag) it will run the function. This is how you can use the Twitter API across sites. I.E. if you call http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter&count=20&callback=handletwitter and create a handletwitter function:
<script type="text/javascript">
function handletwitter(data){
console.log(data);
}
</script>
<script type="text/javascript" src="http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter&count=20&callback=handletwitter"></script>
This is also known as JSONP
There's a smart solution to do so. You can have an iFrame of width and height 0, so it won't be visible. From within it, you can load data on main page using 'parent' property. Since you are allowed to load anything in an iFrame, this should be a good solution for you.
Consider the following example (will also work on different domain).
<html>
<head>
<script type="text/javascript">
function loadData(data)
{
var a = document.getElementById("H");
a.innerHTML = data;
}
</script>
</head>
<body>
<div id="H">hello</div>
<iframe src="sample.html" width="0px" height="0px">
</iframe>
</body>
</html>
Sample.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script>
<!--
parent.loadData("I am inside iFrame");
-->
</script>
</body>
</html>
Been looking around the web, but not found anything so far... can anyone help?
I have created a simple html page that contains a list-box of values that when selected calls a seperate php script to run database query and print out a structure html page. This has been implemented using ajax calls and it results in the page being reloaded when the user changes the value in the list-box.
Now, I would like to move away from the generating of the table using html tags and print statemetns to something more slick and have discovered google visualisation api. I have look ready through many pages of the site and used the code playground, but was unable to find information to help me understand how I might use the visualization api to generate the table and pass this back to the main page in the div tag, using the same php script.
Does anyone have any pointers, or experience of doing this in the past?
Thanks.
You could achieve this using jQuery AJAX and some arrays generated by your php. This is a pretty basic but straightforward approach - you may want to look around for php client libraries that generate gviz code for you in your php if this proves to be insufficient.
Here's a working example:
HTML file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.6.1");
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization(dataFromAjax) {
var data = google.visualization.arrayToDataTable(dataFromAjax);
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data);
}
function makeAjaxCall() {
$.ajax({url:'test.php',
data: {},
success: function(responseData) {
// eval just for testing - make safer
var arrayForGviz = eval("(" + responseData + ")");
drawVisualization(arrayForGviz);
}
});
}
</script>
</head>
<body>
<input type="button" onclick="makeAjaxCall();return false;" value="Click to get data"></input>
<div id="table"></div>
</body>
</html>
PHP File
<?php
echo "[['Country','City','Value'],
['Ireland','Dublin','10'],
['France','Paris','15']]"
?>
Obviously my php file is static, but each time the user interacts with the page and triggers makeAjaxCall() you could send different parameters, and return different array responses.
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax