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.
Related
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.
});
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>
I want to do some autosuggest for my text field, using this plugin AutoSuggest jQuery Plugin
I have an array, already json_encoded, and the files on the server, js, css, but Im not getting yet how the example works, here my code,
<html>
<head>
<title>test-data</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link href="inc/css/admin_style.css" rel="stylesheet" type="text/css">
<link href="inc/css/autoSuggest.css" rel="stylesheet" type="text/css">
<script language="javascript" src="inc/js/functions.js"></script>
<script language="javascript" src="inc/js/jquery-1.5.1.js"></script>
<script language="javascript" src="inc/js/jquery.autoSuggest.js"></script>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<center><br><font class="title">test</font></center>
<form action="dataAll.php" method="post">
Name: <input type="text" name="fname" />
<input type="submit" />
</form>
<p> </p>
<p>JSON</p>
<p> </p>
<?php
$encoded = json_encode ($familyNames);
echo $encoded;
?>
</body>
</html>
so Im supposed to put this code,
$(function(){
$("input[type=text]").autoSuggest(data);
});
but the question is where??( as if I put it inside the php tags, it gives me an error
where should I put the name of my json formatted array? "$encoded" for the function to recognize that is the source of data?
thanks a lot!
You've got all the pieces, but your order/methodology is a bit off. Try creating a second file, named something like ajax.php, and place all of your php code in there. To ensure you are outputting good JSON, add the line header('Content-Type: text/json; charset=ISO-8859-1'); at the very beginning of the ajax.php file (you must set the header before any output is sent or you'll get an error). Now you've got to request your suggestion data:
$(document).ready(function() { // Runs when your page is loaded in the user's browser
$.getJSON('ajax.php', function(data) { // Runs ajax.php, then executes an anonymous function to handle the response
$('input[name="fname"]').autoSuggest(data); // Set your input field to use automatic suggestions with the returned data
}); // end getJSON
}); // end ready
This code simply executes an asynchronous HTTP request for ajax.php, and hands off the returned JSON data to the auto-suggest jQuery plugin. Place it inside a <script type="text/javascript"></script> tag. It will run once when the page loads due to the use of $(document).ready(...). I added the small optimization (input[name="fname"]) so jQuery doesn't attempt to attach the auto suggestion functionality to every text input you have on your page. If thats what you wanted to do (unlikely), just change it back to input[type=text].
You really do not need a separate php file to get this to work. There is nothing stopping you from doing it all in one file, but you'll soon realize how cluttered and unmanageable that can get. For me, its easiest to think of my "ajaxy" php code as a single, modular piece of my web application.
Be sure to reference these pages for detailed information:
http://api.jquery.com/
http://api.jquery.com/ready/
http://api.jquery.com/jQuery.getJSON/
You put it inside a tag in the html.
<script type="text/javascript">
$(function(){
$("input[type=text]").autoSuggest(data);
});
</script>