JSON Response keeps coming back undefined (ajax file upload) - php

I'm currently using Valum's Ajax File uploader to do same-page file uploads. For my script, I need to pass the final file path (after it gets uploaded) back to the client-side and store it in a variable, however, I keep getting "undefined" for responseJSON['filename']. I've tried tons of different solutions and nothing seems to work (changed datatype from json to text, played around with the way PHP sent the response, etc. etc.)
There must be something simple I'm overlooking here....
All help is welcome. Thanks!
EDIT: JS is here: http://jsfiddle.net/acw9V/ for the PHP portion, I'm using the default PHP code in Valum's zip archive.
Update: still no luck... keep getting back undefined from responseJSON. I'm wondering if there's some way to just return whatever message is echo'd in PHP, maybe I could work with that?

I think that 'responseJSON' in fact is STRING , not an array. (assuming that you just echo-ing your output in php and you cannot echo array) To be treated as array, after receiving, responseJSON should be eval-ed.
var data = eval(responseJSON);
(eventually: var data = eval ("(" + responseJSON + ")"); )
then data['filename'] should contain uploaded file name (if this was specified in php)

Related

d3 means of reading proxy data via PHP

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;

server not parsing php file called from jquery ajax

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....

jQuery (without $.ajax) $.POST+json retrieves "null" from PHP json_encode

My first time writing, but not the first here. I felt forced to ask here because none of those apparently alike questions here were able to give me a clear workaround or solution.
My projects involves a tic-tac-toe game, all jQuery, PHP and log file based. It's working fine, but for every information sent to the txt log, I have to star a new $.post to retrieve the information that will be displayed in different parts of the page, not all in a single list (specially O and X that are retrieved back to their original text element) ...
The game is real-time, multiplayer and is working fine, but is using two txt logs written by PHP which also manages the game: one log keeps the position (filled space) and the other what char was used (X or O). Nice, but I'm calling the two via $.post, storing their data in respective global variables and using them in a setInterval, to update on time for the other player. But as there are many other informations like name and remaining moves (from 9 to 1), I'd like to put everything in a single log, something easier to be retrieved all in a time and be displayed in their respective positions through the game page. My problem (now what I need to get working for now) here is retrieving them from PHP. During tests, I simulate three informations: position, char (O or X) and player's name, put them in an array and echo them with json_encode, as it follows (my jQuery post and then my PHP):
<script type="text/javascript" src="jquery.js"></script>
$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
alert (data); //returns null...
//alert (data.pos); //nothing, script ignores execution
//alert (data[0].pos); //returns null...
//alert (data[1].pos); //returns null...
//alert (data[2].pos); //returns null...
//alert (data[3].pos); //returns null...
//tests above based on some suggestions I'fe found through the web, ineffective...
},"json");
And my PHP:
<?php
//Simulating values being received during the game:
$pos='s3'; //simulation player's move on slot 3
$weapon='O'; //player puts O on slot 3
$name= 'fulano';
//Putting general player info into the array to be used by jQuery:
$coord= array();
$coord['pos']= $pos; //Sets the position where the player put his char
$coord['weapon']= $weapon; //The "weapon" to be put in respective "pos"
$coord['nome']=$name; //Player's name to be displayed during the game
echo json_encode($coord); //encoded json is returning {"pos":"s3","weapon":"O","nome":"fulano"} nicely
?>
Both are post, both using json, jQuery returns something, but is null, PHP echoes alright... $.ajax simply didn't make it either...
What I need: that $.post retrieves every datum so that I can store one by one in their respective global variables, but if alert can't even show one of them coming, something's wrong. Changed every variable names to avoid any kind of conflict, not solved...
I made this test just to make sure PHP json would be clearly gotten by jQuery, what's not happening here. My HTML is using default charset, I'm testing it in localhost, I have the main project working perfectly here, this was a side test to test specifically json response. I simply had no success in using $.ajax ({}) (my jQuery is 1.7.1), no matter what, the script simply stops executing, PHP keeps responding alright here, but jQuery is not giving me what it should other than "null", I've tested it on FF15 and IE8, problem is just with my json routine on jQuery, PHP is working fine and my $.posts here and on the main project, too. What could be going wrong here? Why is it simply returning data as null regardless to what I may try? I thank everyone in advance, I'm just asking because there were no examples here and outside that really gave me the answer, and 99,9% depend on Ajax, but Ibelieve it can be simpler like this.
Add this to your code
$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
$(data).each(function(){
alert(this.s3);
alert(this.0);
alert(this.fulano);
});
},"json");
Valid JSON is as follows: {"key":"value"} not {key:"value"}
Note: All quote encapsulated, not just the value. Hope that helps.

how to send json to php file to save on server

Im developing a javascript/php/ajax application and have stumbled across some problems.
Im confident at javascript and ajax but my php is a little rusty.
My aim is to get a json file from the server, modify it using javascript, and then save this modified json back to the server.
After some research it was obvious that the modified json file must be sent to a php file, this php file will then do the saving.
HOW do i send a json string from javascript to php? OR how do I get the php file to pick up the json variable from the javascript?
im assuming the php will be something like:
<?php
$json = $_POST["something"];
?>
but how do i send or "post" the javascript variable to the php file?
I was thinking about creating a hidden html form, setting a hidden textbox to the json string, then posting the html form
But surely there must be a way without including the html middle man?
Im looking for answer WITHOUT jQuery. Seeing as this is an application i would like a relieve the dependancy of jQuery.
The only, as far as I know, proper way to do this is sending data to a file through Ajax, then attaching some POST or GET data.
Example:
You could send the data in the url as GET:
http://example.com/foo.php?myvalue=cake
And then in the php you'd say:
<?php
$yourvalue = $_GET['myvalue'];
// Some code to save it to the database/server
?>
You would need to create a XMLHttp-Request like this:
xmlhttp.open( "POST", url, false );
xmlhttp.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);
xmlhttp.send("data=yaystuff!")
So you can send it. In PHP just get the $_POST['data'] variable and do some json_decode() on it, if you send JSON :)

Problems with $.getJSON in certain browsers

I have a php file that outputs json encoded text via
echo '(' . json_encode( $final ) . ')';
And i have a javascript file that fetches that page
$.getJSON(file, function(data){
var object = eval(data);
alert(object); //for testing
...
When any browser other than firefox 3.5 visits the page that calls .getJSON it alerts null
BUT!!! If i take the text that is output by the php file paste it into a new file and load that via .getJSON it works fine. It's only when its output by php that it doesn't work.
The only difference i can see is that the PHP file's content length is 2 more than the other, i can't figure out why.
Thanks
UPDATE
I created a small array to test it with other data and it's working. There's something in my data that's causing the issue. Looking now...
a call to array_merge is the culprit.
data is not a string, it is a JSON object. Therefore eval will not work on it. Try the following instead:
$.getJSON(file, function(data){
alert(data); //for testing
I've narrowed it down to a call to array_merge that is corrupting the data somehow.

Categories