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.
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 wasn't 100% how to phrase this question. I have a request to a URL similar to
example.php?miscData=JSON_FILE_NAME
Now JSON_FILE_NAME contains data unique to that file. I've got example.php set-up similar to below
xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.onload = function(e) {
var data = JSON.parse(this.response);
}
xmlHttpReq.send();
The request file has a function to handle the success of the call and is set up as below
function(retData, textStatus, xhr) { }
I expected retData would contain the JSON data {"name":"Dominic"} etc... But it doesn't. what am I doing wrong?
Your server side code from http://pastebin.com/c7h8V9JK is responding with an HTML page, not a JSON response. The code outside of your PHP is nothing but HTML. So naturally, when requesting the page, the server will return the HTML you've put outside of that php script.
Keep in mind, an AJAX request at its most basic is nothing special in terms of sending and receiving data from the server. Imagine that you have another tab open in your favorite tabbed browser, and that tab is navigating to the URL that your AJAX request is navigating to. That's what's going on when you make an AJAX request.
If you're trying to get JSON data from example.php, begin by removing all of the HTML from that file and serialize the data that you're trying to get using a JSON serializer.
encode json using php?
I have pages that send POST/GET requests to PHP scripts on the server. All PHP scripts respond in JSON. Question is how to capture the JSON response at the client-side in JavaScript.
Example : when i submit the form register.html, i want to capture and manipulate (using Javascript) the JSON response returned from http://localhost/register.php.
You have to make an AJAX request. You can do this quite simply by using a library such as jquery. Or a little more difficultly just using javascript.
Using AJAX will change the current flow of your application though.
This follow example is using jquery
<form onSubmit="makeRequest(); return false;"></form>
function makeRequest() {
$.post('register.php', formDataHereAsAnObject, function(response) {
console.log(response) // this response is your json
});
}
i could recommend http://www.json.org/js.html for a detailed description of using JSON.
The moment you submit a form in the classic sense, you're out of luck. What you want is to load the JSON response from the server. To achieve this, there are a few possibilities
Set the target of your form to an invisible iframe and do submit it, then take the JSON out of there via JS (old school)
Start an AJAX request (via a framework or directly), that ends up having your data in a JS variable
Ok so trying to get a page together that needs to connect to our SQL database. So on the javascript page I have functions that will autocomplete a textbox with data out of our mysql DB and then I need to send it to other functions and classes so that it will then look in our SQL DB and return some data. The problem I have is trying to get the .GET call to call in the php page, with the function that calls the class in which I need to get into for the SQL call. I have it setup somewhat but trying to figure out how to send the data through with it as well as just get clarification on how to work the .GET function.
Javascript page:
$.get("dsl_validate.php", calldsl(job));
Php Page
function calldsl($job){
var $dsljob = $job
hasfunctioncode($dsljob);
}
The hasfunctioncode function is in my DSL class page that will return the info I need. Any help on if I am in the right direction or not?
It looks like you're trying to physically call the PHP function calldsl() from the JavaScript. This... isn't right. (I'm assuming the $.get() you're using is from jQuery, please correct me if that assumption is incorrect.)
What $.get() does is simply call a resource on the web server. It doesn't have any knowledge of the server-side code (nor should it, for a number of reasons). From the perspective of the server-side code, there's no difference between a page being called via $.get() vs. one that's just loaded in a web browser.
What you essentially need to do is create a PHP page which accepts arguments either as a form post or query string (if you're using $.get() then the query string is the way to go), does its server-side logic, and then simply outputs the results to the "page." In the case of calling the page via AJAX as you are here, it's a good idea to render the page content using JSON notation. (Don't forget to set the content-type header to "application/json" as well.)
Then what you're getting on the client-side from the $.get() call is the response body, which would be that JSON data. It's really just a "page" like any other, the only difference is the content-type telling the browser that it's JSON data and that it doesn't have HTML, just JavaScript objects. The success callback on the $.get() call (the function you pass it, or create in-line) would receive that response data as an argument and can do what you need to with it.
The way I understand jQuery.get(), the second argument is the "callback" (http://api.jquery.com/jQuery.get/). The callback will hand the results from your server therefore should be a function. Currently your code actually executes the function "calldsl" where you should be only passing a reference like so...
Javascript:
$.get("dsl_validate.php", function(response){
alert("yay I haz ajax! "+response)
});
PHP: "dsl_validate.php"
echo "this is some data from the server";
No, your are not in the right direction. The first parameter of the get method have to br the complete URL of the page, not just the script (this works if the script resides on the same directory of the javascript file, though). The .php file shall return somehting "usable" for you javascript (JSON, or HTML, or text, or... whatever). The "calldsl" function will be called AFTER the data has been returned from the call. Something like that:
$.get('dsl_validate.php?value=somevalue', function(data) {
alert("Data returned from dsl_Validate: " + data)
});
i think you are better off passing the function as a param to your php page
$.get("dsl_validate.php?calldsl="+job, function(data) {
$response = $(data);// create a jquery object from the response
});
`
and in your php file
create a switch statement that call the function based on the parameter
Mmm I think you are wrong, the second argument on your get function is the javascript function that will process de data returned by "dsl_validate.php". I mean, if that page returns "foo", job will contain "foo".
But in my experience is better to use the autocomplete plugin from Jquery UI
jquery autocomplete plugin