I have a slight problem. I am connecting to a web service which provides JSON results and trying to parse the results. The code is working fine on my localhost (wamp server) but code doesn't run on any of the web hosting accounts I tried.
Here is the url providing JSON
http://mohamedbadr.com/webservice/list.php
And here is my file which is trying to fetch results:
http://contestlancer.com/web/getList.php
Here is the code of the Getlist file:
<!DOCTYPE HTML>
<html>
<head>
<title>Hotel Promotion List</title>
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script type="text/javascript">
function getList()
{
var i=0;
var ntable="<table><thead><tr><th>Image</th><th>Name</th><th>Rating</th><th>Highlights</th></tr></thead><tbody>";
$.getJSON("http://mohamedbadr.com/webservice/list.php", function(data){
$.each(data.promos, function(key, value) {
ntable+="<tr><td><a href='promotion.php?id="+value.promo.id+"'><img src='"+value.promo.image+"' height='100' width='150'/></a></td><td><a href='promotion.php?id="+value.promo.id+"'>"+value.promo.name+"</a></td><td> "+value.promo.stars+"</td><td> "+value.promo.highlights+"</td></tr>";
});
ntable+="</tbody></table>";
$("#content").html(ntable);
});
}
</script>
</head>
<body onLoad="getList()">
<div id="wrapper">
<div id="content"></div>
</div>
</body>
</html>
Most probably the url is not being opened what is the solution to this? Any help will be highly appreciated
It's not working because you are making a cross domain request. Domain A to Domain B.
Try adding this to http://mohamedbadr.com/webservice/list.php before any output is printed.
header('Access-Control-Allow-Origin: http://contestlancer.com');
As mentioned by Nadh, this is due to a cross-domain request. More info # HTTP Access Control. Understanding Same Origin Request.
Since you are using jQuery getJson(), you may alternatively try this approach
var url = "http://mohamedbadr.com/webservice/list.php";
$.getJSON(url + "?callback=?", null, function(data) {
... Success Logic here...
});
The ?callback=? at the end of the url, will convert your request to a JSONP. And if you remove it, this will be a plain Ajax call.
Understanding JSONP
-- Arvind.
Related
I'm planning to use googlecharts to chart data that is stored on in a local database - the googlecharts code will also be stored on a local server. I used XAMPP to create a local directory ('http://http://127.0.0.1/). Before jumping into the project, I am testing an example script (that I found from a google search) that takes data from a json file (which is called from a php script) and then feeds it to the googlecharts drawing functions. The 3 files are all stored in the folder 'C:\xampp\htdocs', as advised, but when I load the page in my browser (http://127.0.0.1/test_php_long.html) the page appears blank (on Chrome, IE and Firefox). When I run a googlecharts script with data hardcoded into the HTML it works fine. I have been looking online for several hours but have yet to find a solution that works.
This is the main html file ('test_php_long.html'):
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="https://www.maxcdn.com/one//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
//fetchjson.php is a php script that will fetch the JSON data e generated using above php code
url: "fetchjson.php",
dataType:"json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.LineChart(document.getElementById('chart_flow'));
chart.draw(data, {width: 1200, height: 300, lineWidth: 1, pointSize: 1.3, pointWidth: 3});
}
</script>
</head>
<body>
<div id="chart_flow"></div>
</body>
</html>
This is the php file ('fetchjson.php')
<html>
<head>
<title></title>
</head>
<body>
<?php
//Fill the ‘string’ variable with JSON data from file we used as json container populated by php //code: ‘flow.json’
$string = file_get_contents("flow.json");
//push JSON data out
echo $string;
?>
</body>
</html>
And this is the json file ('flow.json'):
{"cols":[{"id":"","label":"Time","pattern":"","type":"string"},{"id":"","label":"Cache Hits","pattern":"","type":"number"},{"id":"","label":"Non-Cache Hits","pattern":"","type":"number"}],"rows":[{"c":[{"v":"2014-01-21 00:00:00"},{"v":2},{"v":23}]},{"c":[{"v":"2014-01-21 01:00:00"},{"v":2},{"v":52}]},
...
,{"c":[{"v":"2014-01-23 01:00:00"},{"v":0},{"v":34}]},]}
Thanks!
Your problem might be related to the fact that your request is a cross-origin one, or at least being considered as once. There are two ways as far as I know to deal with this issue, either you allow cross origin requests, by adding the following lines at the top of your PHP script :
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
While this is potentially unsafe, and the * should be replaced by a list of trusted domains, it should solve your problem for now and shouldn't be much of a security threat since your app will be running in an intranet.
OR, you could also issue jsonp instead of json by wrapping your json object in a callback :
echo $_GET['callback'] . '(' . json_encode($something_to_be_encoded) . ')';
Don't forget that your url parameter passed to your ajax function should now be :
http://myawesomescript.php?callback=?
I am new to AJAX & trying to load a page (test.html) through ajax in to a DIV. I just want to know that is it possible to use AJAX without PHP server (which I am not using at present) or is there any error in the code:
My index.html file is as under:
<! doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/hwcb.css">
</head>
<body>
<input type="button" value="Load" class=”loadpage1”/>
<div id="loadpagea1"></div>
<script src="jquery.js"></script>
<script src="css.js"></script>
<script src="main.js"></script>
</body>
</html>
my test.html file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
We belongs to a great nation
</body>
</html>
main.js page:
$('.loadpage1').click(function(){
$.ajax({
url:'test.html',
success:function(data){
$('#loadpagea1').html(data);
}
});
});
I just want to know that is it possible to use AJAX without PHP server
Assuming by this you mean without any server in general, then no it is not. You cannot make an AJAX request to the local file system as it will be blocked by the browsers' security settings.
You need to make the request to a server, either local or remote. I would suggest setting up an XAMP server for PHP, or IIS for ASP.Net.
Try this,
var jqXHR = $.ajax({
url: "/test.html",
type: "get",
contentType: "text/html; charset=utf-8",
async: false,
success: function (result) {
}
});
$('#loadpagea1').html(jqXHR.responseText);
$(document).ready(function(){
$('.loadpage1').click(function(){
$.ajax({
url:'test.html',
success:function(data){
var data = $(data);
$('#loadpagea1').html(data.find('body').html());
}
});
});
})
Try this
you have html syntax error, see quotes class=”loadpage1” change with class="loadpage1"
I am using ajax for retrieving data from my remote server when i am posting the ajax url directly in the address bar of browser, i am getting the data but when i am doing ajax call to that url in javascript file , it is showing error.I am pasting my code here.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$.ajax({
url:"http://www.appitechture.com/api/index.php?action=getContactDetails&id=96",
type:'get',
datatype:'json',
success:function OnSuccess(data , status){
alert(data);
} ,
error: function OnError(request , status , error){
alert('error');
}
});
</script>
</head>
<body>
<div id="images"></div>
</body>
</html>
so please if any one knows its solution please tell me.
Thank's
puneet
Are you trying to do a crossdomain AJAX request? Bad idea, read this article http://en.wikipedia.org/wiki/Same_origin_policy
If it is not the same domain, you need to use JSONP (JSON with padding). This is due to Same Orgin Policy, as Bogdan Burim states.
jQuery.getJSON can help you with this in a easy way. It will include a script tag like this on your page.
<script type="text/javascript"
src="http://example.com/jsonp?callback=parseResponse">
</script>
You will also need to change the response of the remote server to include the callback var like this:
parseResponse({"bar": "foo", "foo2": "bar2"});
You can also have a look at easyXDM:
easyXDM is a Javascript library that enables you as a developer to
easily work around the limitation set in place by the Same Origin
Policy, in turn making it easy to communicate and expose javascript
API’s across domain boundaries.
Wikipedia have a nice article about JSONP.
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 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>