I have a json string being printed using Lib.print(string); in haxe/php and am hosting that on my localhost
I've checked http://localhost/index.php, and it does indeed print the json object as text.
My HTML5 app has the following code in it
var h = new HttpJs('http://localhost/index.php');
function traceFunc (d:String){trace(d); }
h.onData = traceFunc;
h.onError = traceFunc;
This has yet to come back with an onData response (or onError for that matter). I know I have to be missing something simple.
It seems like you forgot to actually invoke the request?
h.request(false);
(using false for the post argument to make sure it's a GET instead of a POST request)
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;
Im using a basic jquery ajax call.
I make a call to a php file without input parameters with option datatype set to json.
I want the server to parse the php which queries a table in a mysql db, convert it to array and finally encode it to json and return.
I tried a test call from the browser by copying the php file url in the address field, and it shows that it works, since I can see a blank page with all the rows of the table in json formatting.
Instead, when calling from my javascript code the $.ajax call fails with error
Requested JSON parse failed
which means ajax call was expecting json (since I set option datatype to that) but received another format.
So I tried removing the datatype option from the call, and lo and behold I got a response success, but what did I received from my php file?
Well, it was the whole code in the file, like the server doesn't parse it cause it thinks it's plain text.
Is there a way out of this problem? Thanks.
Send also content header with json data
<?php
header('Content-Type: application/json');
echo json_encode($data);
The ajax function is expecting a JSON encoded document so you have to send a header with the response saying that the response contains JSON. Something like this:
<?php
header('Content-Type: application/json');
// All your code here
echo json_encode($someArray);
?>
I'm an idiot, I may answer my own question, I was debugging jquery from visual studio, which automatically instatiates an iis web server, and it explains why it was treating php files like text files. Obviously under apache everything works fine.
Sorry for taking your time....
I'm no expert in AJAX (or jQuery) but I thought what I was doing was pretty easy yet when I send an ajax request with:
$.ajax ( requestObj );
it doesn't send and I'm hoping someone can help. In order to give context, I've set the "requestObj" up as follows:
//initialise a request object
var requestObj = {};
requestObj.response = 'ajax-response';
requestObj.type = 'POST';
requestObj.url = my_config['ajax-service-list'][service]['url'];
requestObj.data = $.extend ( requestObj.data , {
action: service,
other: parameters,
_ajax_nonce: my_config['ajax-service-list'][service]['nonce']
});
requestObj.global = false;
requestObj.timeout = 30000;
requestObj.success = function ( r ) {
alert ( "Success: " + r );
}
requestObj.error = function ( r ) {
console.log ("FAILURE WITH AJAX Call ( " + JSON.stringify (r) + ")");
}
There's one thing that probably needs explaining. The two references to "my_config" are references to a Javascript variable that I set using Wordpress's wp_localize_script() function. Basically it just provides context about where to find the URL, the NONCE to use, etc. I have tested that the URL and NONCE information is working correctly so that shouldn't be the problem. For example, I put a breakpoint on the browsers debugger on the line after the two references are defined and got these results:
When I call the ajax function it immediately executes the success function and sends in the value of 0. Looking at my PHP error logs though I can see that the request was never sent. What could be getting in the way of $.ajax(requestOb) from actually sending the request?
UPDATE:
Thanks to Michael's sage advice I realised that I am in fact getting a request to go out but as it's running in a local environment the response is coming back lightening fast. Now I am suspecting this has more to with Wordpress configuration. I have hooked into the wp_ajax_[service_name] but it immediately returns 0. I'll re-ask this question with this new information in the wordpress forum.
You should be using a browser inspector to detect if an ajax request is made. Open up the network tab of any inspector, and you can watch requests as they happen. How is the $.ajax() method being instantiated? You may have an issue with that, as opposed to $.ajax().
Once you've used the inspector, look at the $_POST or $_GET data you're sending in the headers section, and then look at the response. Is the HTTP response code 200? If it's 500, then you probably have an error in your PHP controller that receives the request.
If you have PHP CLI, run this to see if you have a syntax error:
php -l path/to/php/controller.php
If you have a non-fatal error in your file, you'll see the error output in the request response.
Try var_dump( $_REQUEST ) at the top of your php file, too, to make sure that the file is receiving the data, and you can inspect it inside the browser-inspector response.
If you have a problem with the program inside of your controller... you've got yourself a new question to post. :)
At first look, it looks like your URL has spaces around get_action_template. That might be an issue.
Also, passing dataType might help.
If not try getting a JSON response without any parameters and post the output
Ok, i've answered this damn question finally. Arrgh. BIG, BIG THANKS to Mathew to who's troubleshooting skills I could not have done without. Anyway, the problem was in the AJAX request and as a result the Wordpress Ajax manager was never respecting the "hooks" I had put into place on the PHP side.
How was my AJAX request off? I had a POST request but the URL had GET variables hanging off of it. The key variable for Wordpress based Ajax requests is the "action" variable. This is the variable which WP's ajax manager uses to distinguish the various services and is the name that you'll be hooking into.
So in the end, my URL was:
http://mysite.com/wp-admin/admin-ajax.php
and my POST variables included:
action: get-action-template
My wordpress hook is:
add_action ( 'wp_ajax_get-action-template' , 'AjaxServiceManager::ajax_handler' );
My sleepless nights may continue but they won't be related to this damn problem anymore. :^)
I have a javascript application calling an ajax function that looks like this
$.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) {
if (data.ok) {
//do things
}}});
the ajax url im trying to access is through etsyapi
everything works fine and dandy until i try to access the application in chrome with adblock on. it makes the ajax call fail completely, returns an error with a Failed to load resource-"theActualURL" message.
I couldn't figure out how to get past this in javascript and was told that i need to do a php call to get this working.
Unfortunately, i dont know the first thing about php- ive tried to understand even the basic structure for it, and i havent been able to find any work arounds in javascript, so i think it has to be done with php.
Is there simplest way to call the ajax function in php with a dynamic url(which is passed to the php page from javascript) and have it pass the array back to javascript to maniuplate?
ive gotten this far with the php-
<?php
$json = array();
????????????????????????
$jsonstring = json_encode($json);
echo $jsonstring;
?>
but dont understand how to access a dynamic url from javascript.
If it's genuinely using jsonp you shouldn't need php. Replace your $.ajax... with:
var newScript = document.createElement('script');
newScript.src = apiURL;
document.head.appendChild(newScript);
Ignore the above, I'm out of date with jQuery. Even so, you shouldn't need php if the API endpoint is really responding with jsonp. It sounds like the url was wrong/bad if you're getting an error. Have you tried simply opening apiURL by putting it in your browser's address bar?
jsonp is a work around for cross domain ajax restrictions that wraps the returned data in a javascript function call. This allows you to load it in a script tag and the function is run with the data as a parameter when the script is executed.
I am trying to debug a simple PHP/JSON/jQuery problem.
The following PHP script:
header('Content-type: text/javascript');
echo json_encode(array('type'=>'error','message'=>'arg'));
is being consumed by jQuery but when the line:
var results = jQuery.parseJSON(responseText);
is executed, the jQuery JSON parser gives the following:
uncaught exception: Invalid JSON: <head></head><body><pre>{"type":"error","message":"oops!"}</pre></body>
Obviously the head/body/pre are not supposed to be returned.
I cannot see any hidden characters nor anything out of order in my PHP code..
Any ideas?
This one has had me stumped for the last two days. I'm using the jQuery Form plugin's ajaxSubmit function to submit a form via AJAX without reloading the page. I finally stumbled across the answer after this question showed me a parameter I hadn't noticed previously: dataType.
Behind the scenes, an iframe is being created and is actually making the call back to the server. The response from the server is being pulled from the iframe, which is bringing along with it the tags.
The jQuery Form plugin handles the situation by allowing you to specify the type of response to expect from the server. If I specify 'json' as the response type, the following few lines of code are executed to get the JSON from within the tags:
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
}
(doc is a reference to the iframe's document and xhr is the XmlHttpResponse object that ultimately gets returned from the plugin's function.)
I don't know exactly how you're making your AJAX call, but I'm guessing a similar construct (perhaps using a document fragment) will allow you to extract the necessary JSON from the response.
Try not to send header('Content-type: text/javascript');
json for php find "function send_as_json($obj)"
headers types
Set the header to application/json.