"invalid label" Firebug error with jQuery getJSON - javascript

I'm making a jQuery $.getJSON request to another domain, so am making sure that my GET URI ends with "callback=?" (i.e. using JSONP).
The NET panel of Firebug shows that I am receiving the data as expected, but for some reason the Console panel logs the following error: "invalid label".
The JSON validates with JSONLint, so I doubt that there is anything truly wrong with the structure of the data.
Any ideas why I might be receiving this error?

This is an old post, but I'm posting a response anyway:
Let's assume you want to get the jSON code generated by the following file, "get_json_code.php":
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Like you mentioned, $.getJSON() uses JSONP when you add a "jsoncallback=?" parameter to the required URL's string. For example:
$.getJSON("http://mysite.com/get_json_code.php?jsoncallback=?", function(data){
alert(data);
});
However, in this case, you will get an "invalid label" message in Firebug because the "get_json_code.php" file doesn't provide a valid reference variable to hold the returned jSON string. To solve this, you need add the following code to the "get_json_code.php" file:
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['jsoncallback'].'('.json_encode($arr).')'; //assign resulting code to $_GET['jsoncallback].
?>
This way, the resulting JSON code will be added to the 'jsoncallback' GET variable.
In conclusion, the "jsoncallback=?" parameter in the $.getJSON() URL does two things: 1) it sets the function to use JSONP instead of JSON and 2) specifies the variable that will hold the JSON code retrieved from the "get_json_code.php" file. You only need to make sure they have the SAME NAME.
Hope that helps,
Vq.

It looks like you're misusing JSONP in your server script.
When you receive a request with a callback parameter, you should render the following:
callbackName({ "myName": "myValue"});
Where callbackName is the value of the callback parameter.

Related

JS $.post > dump PHP $_POST data to file

I've been trying this for hours and finally give up.
As you can tell I've a huge noob and have little to no idea what I'm doing...
I have some JS being called from a button onclick= which POSTs to a PHP file. I'd like to take this POST data and just write it to a file, nothing fancy, just dumping it raw.
I've tried various methods, but none seem to work - either not writing the data at all, or writing "()", "[]" (if trying to encode the POST data as JSON), or just the word "array" and so on.
Methods I've tried;
file_put_contents('test.txt', file_get_contents('php://input')); //this I thought *should* definitely work...
var_dump / var_export / print_r
I've tried storing the above as $data and writing that as well. Just nothing I do seems to work at all.
I'm mostly trying to use fopen/write/close to do the deed (because that's all I really "know"). File is writable.
(part of the) JS I'm using to POST:
(from button onclick="send('breakfast'))
function send(food){
if(food == 'breakfast'){
$.post("recorder.php?Aeggs=" + $("textarea[name=eggs]").val());
I'm not looking to extract(?) values from the POST data, just write it "as-is" to a file, and I'm not bothered on the formatting etc.
Would someone please assist in putting me out of my misery?
You could use fopen() and fwrite() to write text to a new file. print_r() could be used to get the structure of the data or you could write the post var itself to the file. But since your client side code is not sending any POST data, use $_GET on the php side instead of $_POST. Here's an example:
$f = fopen("post_log.txt", 'w'); // use 'w' to create the file if not exists or truncate anew if it does exist. See php.net for fopen() on other flags.
fwrite($f, print_r($_GET, true)); // the true on print_r() tells it to return a string
// to write just the Aeggs value to the file, use this code instead of the above fwrite:
fwrite($f, $_GET["Aeggs"]);
fclose($f);
NOTE: The 2nd param to $.post() would contain the "post" data. Since you dont have that in your code, the $_POST on the PHP side will be an empty array.

JSON.parse reads "{\"number\":\"7\"}

Hi I have troubles to generate JSON with json_encode() PHP function.
I have a .php file that is doing only following:
<?php
// include_once for a few files here
$address = MyModelClass::getByAtrrId(52);
echo json_encode($address, JSON_HEX_QUOT | JSON_HEX_APOS) ;
result is following:
{"number":"7"}
Then there is jQuery in another file, retrieving this by following code:
$(document).ready(function e() {
let file_path = 'myJson.php';
let json = $.getJSON(file_path);
console.log(json);
let json_obj = JSON.parse(json);
However $.getJSON reads this string as "{\"number\":\"7\"}, therefore JSON.parse ends with following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I'm sorry, I'm almost 100% sure this is beginner's mistake, however I have failed with my search for correct answer. Anyone having idea what might be the problem?
I have found plenty of articles taking into account input into jason_encode, but right now I have more feeling real trouble is in fact input to jQuery function, however I'm still unable to resolve.
If your web server sends JSON, it's good practice to set the Content-Type accordingly:
header("Content-Type: application/json; charset=utf-8");
On the client, you need to do:
$(document).ready(function() {
$.getJSON('myJson.php', function(response) {
// the response is already parsed by jQuery
alert(response.number);
});
}
$.getJSON() is asynchronous, so you need to pass a handler function to process the response.

call a $.getJSON and sending URL parameter

I have a page with the following URL test.php?city=Paris and I have a php script (getData.php) which executes a SQL request and return a JSON object. To execute my request I need the parameter city in my URL. I call the getData.php script like this :
var ville = "<?php echo $_GET['ville']?>";
$.getJSON("bat/getData.php", {ville: ville}, function( data ) {
console.log(data);
});
I don't think that is the best way to send the URL parameter to my php script.
What do you think?
You should not echo arbitrary data into a script. You have opened yourself up to cross-site scripting attacks.
You can get around the problem by JSON-encoding your data, which is compatible with JavaScript.
var ville = <?php echo json_encode($_GET['ville']); ?>;
There is nothing wrong with passing parameters as part of the query string.
But implementing a little REST service is probably more elegant. Based on your current implementation the REST service would provide the following resources:
GET /cities/{cityname}
Example:
GET /cities/paris

jQuery Fails To Read JSON Response From PHP Script

In my form, I want to do something with two fields:
"website_domain" and "website_ip_address"
I'm trying to use jQuery/JSON to call a PHP script, pass the website_domain to it, and receive JSON including the IP address of that website.
Problem/Symptoms Description:
It's partially working: On blur, it GETs the url of the PHP script. I can see that much in firebug. I get a 200 OK. Output from the PHP script is valid JSON according to JSONLint:
{"field":"website_ip_address","value":"74.125.225.70"}
But in Firebug, I don't have a JSON tab. I only have Params and Headers tabs. Not even a Response tab.
Needless to say, the website_ip_address field is also not being populated with the data I should be getting from the PHP script's JSON output.
My PHP Script:
It may be important to note that for now, this PHP script on a different domain from my application. Maybe my whole problem is cross-domain?
<?php
$domain = $_GET["domain_name"];
$ip = gethostbyname($domain);
// echo $ip;
$json = array(
'field' => 'website_ip_address',
'value' => $ip,
);
header('Content-Type: text/plain');
echo json_encode($json );
?>
My jQuery/JSON script:
Note this is written inside a Ruby On Rails application view.
:javascript
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name=" +$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
I really hope this isn't just a syntax error on my part. I've been writing/rewriting this for 2 days, based on answers I've found on StackOverflow, to no avail. I'm just missing something here.
You are currently attempting to output the JS object (that is formed from the parsed JSON response) to the field. You need to output a value from within it. So not:
$('#website_ip_address').val(data); //data is an object, not a string
but
$('#website_ip_address').val(data.someValue); //output a property of the object
With your code as it is, I would expect the field to be populated with the string representation of an object, which is [object Object]. You don't mention this, so I wonder whether a) your success function is even firing (check this - stick a console.log in it); b) your jQ selector is sound.
The problem can be with different domain. I had it like this before. Try in php to add header("Access-Control-Allow-Origin: *")
Put your jQuery code inside document ready, example: $(function(){ });
:javascript
$(function() {
$("#website_domain").bind("blur", function(e){
$.getJSON("http://exampledomain.com/temp_getIP.php?domain_name="+$("#website_domain").val(),
function(data){
$('#website_ip_address').val(data);
});
});
});
});
And you have a missing end })

Strange output in JSON that I make in my PHP after an AJAX call

I am a bit new at this and totally messing something up. I have a PHP result set through which I iterate like this:
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
and then I output it like this in jQuery code:
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
// Here can update the right side of the screen with the newly entered information
alert (json);
var ob = $.parseJSON(json);
alert (ob.creator_member_id);
alert (ob.problem_title);
alert (ob.problem_description);
alert (ob.problem_date);
}
But there is an error on the var ob = $.parseJSON(json); line it seems. My JS console gives this error:
Uncaught TypeError: Object function (D,E){return new n.fn.init(D,E)} has no method 'parseJSON'
What can this mean and how can I fix this?
Thanks!!
If you are getting JSON results via jQuery ajax call you don't need parsing resultant json - jQuery does it for you.
Just specify the
dataType: 'json'
[http://api.jquery.com/jQuery.ajax/], and your success handler will have the already parsed object.
If you want parsing JSON anywhay, try adding json2.js to your project. You'll have to call JSON.parse(json) then.
I'm new to Jquery, too. eval is just plain JS and it suits my needs. I don't see any evil with this code but of course it's possible to inject bad code into a response. Probably it's not very good practise. It can be exploited for a reverse shell for example.

Categories