Just now I found some code in a webpage which confuses me a lot:
$.ajax({
url: "/foo/bar/save.json",
data: {
key: value
},
type: "POST",
success: function(a) {
//some code
},
error: function(a) {
//some code
},
dataType: "json"
})
I know that it sends data to url using HTTP method POST, if the url is like /foo/bar/save.php or /foo/bar/save then there's no problem, but it ends with .json...
What kind of server-side languages can handle requests sent to a path ended with json?
Does json have any special meanings or is it just the same as .action .do which I can rename as whatever I like?
Thanks!
What kind of server-side languages can handle requests sent to a path ended with json?
Any. There is no need for a server to use file extensions to map URLs onto programs (or files).
Does json have any special meanings
Using it in a URL hints (without even having to make the request) at the data type being returned (instead of how the software used to produce it was written). This is much more useful to people using clients to fetch the data.
What kind of server-side languages can handle requests sent to a path ended with json?
Any kind.
This is just an url, the way it is handled, redirected or rewritten by the server is not shown to the client.
As an example, using a standard apache / php setup, you can have a rewrite rule on the server :
^(.*)\.json $1.php?json=true
and have your content dynamically generated by a php script.
Related
In the existing SO literature, I have seen examples that use jquery and PHP to proxy data:
jquery
function loadTheUrl(x){
$.ajax({ url: 'loader.php',
data: {url: x},
type: 'get',
success: function(output) {
$('.loading-space').html(output);
}
});
}
PHP
<?php
$doc = new DOMDocument();
$doc->loadHTML(file_get_contents($_GET['https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o']));
echo $doc->saveHTML();
Here is what the first few lines of the data look like at the URL seen in the PHP above. It is a page of plain text only, like this:
MARKET_OPEN_MINUTE=570
MARKET_CLOSE_MINUTE=960
INTERVAL=300
COLUMNS=DATE,OPEN
DATA=
TIMEZONE_OFFSET=-240
a1521120900,555.45
1,554.53
2,554.07
3,553.9
4,552.67
...
As far as I know, the PHP is correct. For my use case, I need to replicate the above jquery by means of d3. I was hoping that d3 would have something to use to interface with the data my php file is spitting out.
If you are wondering why I am going to such lengths, it's because my browsers are not letting me run scripts (i.e. d3.text(), d3.csv() et all) directly by say d3.text('https://www.google.com/finance...') due to the infamous access control origin header error. So my plan is to mirror the data from the google backfill off a local php file that I'm serving from my server. This way everybody is happy (or at least me).
When I try calling d3.text() on my php file, my data was not loaded correctly. In other words I tried: d3.text('my_loader.php'). But that resulted in lots of NaN errors, which I usually noticed are symptoms of a parsing error of some sort. Checking back through my code, things seem fine though. I have unary parsing in place, the strings should be cast to numbers. In fact, everything was working fine offline. I could load and parse the data directly when in my IDE. It was only when I published my d3 graph to the web did I realize I couldn't parse data from different origins. This is the point where I added the PHP component. My hunch was that d3 was actually trying to parse my PHP page and not the URL the PHP was pointing to. I later confirmed this by passing the data returned by d3.text() in the console and it was indeed the PHP page itself.
Question: In light of my cross-origin data situation, what can I do from the d3 side or the PHP side to make the two interface with each other correctly? I wonder if d3 is only suited for same origin data, or if there actually is a method to read/parse cross-origin data using a technique I'm not aware of (PHP or otherwise).
The url you are fetching does not exist within the $_GET variable.
The parameters you are submitting are an array:
$_GET = ['url' => 'some_url'];
Which means this:
$_GET['https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o]
is wrong (it's also missing a quote mark at the end of the string).
It should be $_GET['url']
With no validation:
<?php
header('Content-Type: text/plain');
echo file_get_contents($_GET['url']);
But that's neither here nor there.
The issue, I think, is with the url being passed. It contains a question mark and multiple ampersands (? and &). I think this is bjorking up the $_GET parameter so all you're getting is https://www.google.com/finance/getprices?q=.NSEI. You need to wrap the url in encodeURIComponent:
var url = encodeURIComponent('https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o');
d3.text('/path/to/myscript.php?url=' + url);
Cross origin applies to all ajax requests, instead of requesting d3.text('https://www.google.com/finance...') why not try d3.text('mymethod.php') and make sure the method returns a text file rather than html via the headers:
<?php
header('Content-Type: text/plain');
$file = file_get_contents('https://www.google.com/finance/getprices?q=.NSEI&x=NSE&i=600&p=1d&f=d,o');
echo $file;
I recently started translating an old Classic ASP site to PHP. Several of its pages (Response.ContentType = "application/json") would just serve JSON responses such as {"R":1} and everything worked fine.
now on PHP, with header("content-type:application/json") first thing on the code, ajax just will not parse it. The client-side JS code is the same I used before. I haven't even touched it.
$.ajax({
dataType: "json",
type : "POST",
url: "processthisrequest.php",
cache: false,
async: false,
data: { Field1:"bla", Field2:"blabla"},
error: function(data){
// code on error
},
success: function(json){
// code on success
}
});
if the request is accepted ALL it serves is {"R":1} with double-quotes as it's always been.
Ajax will fire the error function no matter what. trying to debug it I found this:
readyState:4
responseText:{"R":1}
status:200
statusText:OK
searching for help I found a lot of people with problems with ajax getting readyState:4, status:200 and the response still not being parsed. none of the solutions worked or applied to my problem.
as it was working with IIS/ASP, can it be something with Apache or PHP?
UPDATE:
still no success, but if I get the server to serve a .js file with {"R":1} instead of processing a response through a php page ajax will fire the success function. which only proves my point that this is a php problem and also explains why it worked with old dinosaur ASP. now why PHP is not serving a proper mime-type is something I am trying to figure out.
I sorted it.
PHP has some very strange ways of doing things.
right after the header("Content-Type: application/json") line I have an include "file.php". although both the file that processes the Ajax request and the include file were saved as Unicode one had BOM signature and the other hadn't.
processing these two files made PHP send "something" back to the browser that was anything but a proper application/json response which wouldn't allow Ajax to parse it.
I know I'm supposed to stay on point here but I am so frustrated I need to add this comment: after wasting almost 18 hours of my life on this, time I could have used working on other things, the only thing I can learn from this experience is that free software is not free at all.
How can we detect, in the content of javascript code returned by the web server, the portion of code that allows client Web to make AJAX calls?
In other words, I want to know if there are existing libraries that can return the URL contained in the javascript code returned by the web server to the Web client. The URL returned by the web server to web client will allow the web client to make Ajax calls to the web server.
Here is an example
in the javascript code returned by a web server to web client, there are the following lines:
$.ajax({
type: "POST",
url: '/index.php?option=com_rechercheperso&view=recupeSecteur&format=raw',
data: 'style='+value_style+'&type='+value_type,
success: function(response){
$('#secteur').html(response);}
});
}
The question, is there a library that allows us to return the url ('/ index.php? Com_rechercheperso option = & view = & format = raw recupeSecteur') in analyzing the content of javascript code.
Thank you for your answers
Toufik
From the description I assume, that the Server is handing back a page, in which there are scripts using ajax calls with predefined urls, and you want to get those urls.
If right, you could use any language to call that page which loads the scripts (php, perl or even a JS ajax), and search with a regexp for all the urls in the responseText, and then try the matching ones for forther ajax calls against the Server.
Looks like brute-force solution, but should work.
I've made on my website a search.php file that produce a JSON string, helping me to use real-time ajax for my apps.
But now, I'd like to open it as an API to others, but I discovered that $.get $.getJSON $.ajax doesn't allow to use my search.php file from other servers/domains.
How can I do to transform my php search into a search.json, exactly like Twitter, passing parameters to it.
Thx
getJSON is limited by your browser's security restrictions that lock down non-origin domains. In order to do cross-domain, you have to use JSONP, which requires you wrap the data in a function that is defined by the callback variable (e.g. $_GET['jsonp_callback']). e.g.
Search.php
<?php
echo $_GET['jsonp_callback'] . '(' . json_encode($data). ');'
// prints: jsonp123({"search" : "value", etc. });
?>
jQuery
$.ajax({
dataType: 'jsonp',
data: 'search=value',
jsonp: 'jsonp_callback',
url: 'http://yourserver.com/search.php',
success: function () {
// do stuff
},
});
Just make sure that the callback variable that you define in your php script matches the jsonp value that you call through the .ajax query (or it defaults to "callback").
Twitter uses two mechanisms to allow cross-domain access to the search.twitter.com domain: crossdomain.xml (for Flash) and JSONP (for JavaScript).
With JSONP, the calling JavaScript includes a callback=? parameter in the URL, where ? is the name of a callback function. The server-side script wraps the encoded JSON as:
?(<JSON here>)
This allows the query parameters to be encoded as the src URL of a script tag, allowing cross-domain access that XMLHttpRequest does not allow. When the data arrives, it is executed as a script. The JavaScript interpreter decodes the JSON since it is a valid subset of JavaScript and then calls the callback function with the decoded JSON as an argument. It shouldn't take more than a few lines of code to implement JSONP in your PHP script.
I would like to using (Ajax) PHP or Javascript, Post information to http://en.lernu.net/cgi-bin/vortaro.pl then read the results back (Not from lernu.net).
I am trying to learn Ajax, PHP + Javascript, Nobody there know's how to help me. I would very much like doing this without touching Lernu's code, So if there is a way to do it all on my code, that would be great!
You need to proxy the request due to browsers preventing cross-domain ajax calls.
You can either do this with a PHP page on your site or configure url rewrite rules for your webserver.
You maybe able to do a simple post to your url with jquery in following ways:
$.ajax({
type: "POST",
url: "http://en.lernu.net/cgi-bin/vortaro.pl",
data: "name=John&age=21",
success: function(msg){
alert( "Data Posted to server: " + msg );
// you may additionally call other javascript methods here to do modifications to your page based on your request
}
});
Jquery is an excellent framework for javascript and I would highly recommend using it for most of your functionality. You might want to readup a bit about javascript and then start up with jquery.
You need to write a PHP script in your domain that forwards your POST to http://en.lernu.net/cgi-bin/vortaro.pl, then forwards their response back to the client.
You can then send an AJAX POST to your server with jQuery.