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.
Related
I'm trying to create a js that send data to a php.
My first problem is that I get get back a html code if I insert this to the php.
This is only for understand the idea. So the js should send the "param" to the php and the php should return the result6 variable in this case, but I get a html code...
$('#f_field').change (function()
{
var param = 28;
$.post('check_mutet.php', param, function(result6) {
alert(result6);
});
});
while check_mutet.php contains this
<?php
$result6=666;
echo $result6;
Thank you for your help, as you can see I'm rather noob :)
param is a plain string (it starts out as a number, but will be converted to a string by the time it gets through to HTTP).
This will be available as STDIN in PHP, which you can read as described in answers to this question.
However, you should encode the data into a structured format that is easier to use.
The traditional format for this is application/x-www-form-urlencoded, which is the default format sent by HTML forms.
If you pass an object to jQuery post, it will encode the data in that format for you:
var param = 28;
var data = { example: param };
$.post('check_mutet.php', data, function(result6) {
Then you can read it through the POST superglobal in PHP:
<?php
$result = $_POST['example'];
I'm using $.post to return an array from a separate php file, and trying to access the values of the array in javascript by the keys, but am having trouble doing so.
Here's the post code:
$(document).ready(function(){
var limRefresh = setInterval(refreshLIM, 10000);
var dbAction = "feedRefresh";
var newestRow = <?php echo $newestRow ?>;
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
console.log(status);
console.log(newArr['status']);
console.log(newArr.status);
console.log(newArr[0]);
});
});
Here's the excerpt of how the response is being formatted in the external php file:
echo json_encode(array("status" => "success","actId" => $newActId));
And here's the respective console logs (just trying different options):
{"status":"success","actId":"585924418"}
undefined
undefined
{
Any ideas where I'm going wrong?
The response you get as status from $.post is a string. You need to parse it order to use it as you intend. Moreover, newArr is undefined because you have not defined it anywhere. This is probably because you have reused someone else's code and missed this part:
newArr = JSON.parse(status)
The response is coming as string, so you need to parse it before you can access it as JSON:
$.post("jsDb.php",{ action: dbAction,lastRow: newestRow },function(status){
var data = JSON.parse(status);
console.log(data['status'])
console.log(data['actId'])
}
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 })
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.
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.