I've faced with a next problem:
In our database we have objects with ids, like 4040956363970588323.
I'm writing some client-wizard on jQuery for interacting with such objects. Client receives base data about objects trough an Ajax request, like:
$.ajax({
url: "/api/pages/",
type: "get",
dataType: "json",
data: {"id": site_id},
success: function(data){
if (data.success){
for (var pidx in data.pages){
console.log(data.pages[pidx].id);
var li = $('<li class="ui-widget-content"></li>');
var idf = $('<input type="hidden" id="pid" value="{0}"/>'.format(data.pages[pidx].id))
var urlf = $('<input type="hidden" id="purl" value="{0}"/>'.format(data.pages[pidx].url))
li.text(data.pages[pidx].title);
li.append(idf);
li.append(urlf);
$("#selectable_pages_assign").append(li);
}
pages_was = $("#selectable_pages_assign>li");
}
else
updateTips(data.message);
},
error: function(){
updateTips("Internal erro!");
}
})
So, as you see I send data like JSON object (a bit of server code):
return HttpResponse(dumps({
"success": True,
"pages": [{"id": page.id, "title": page.title, "url": page.image} for page in Page.objects.filter(site = site)]
}))
According to Firebug, server send right ids in data, but console.log(..) instead of correct id (4040956363970588323), outputs id 4040956363970588000.
Why does this happen?
Without right ids, any chance, that my wizard will work correctly :)
My guess is something is going wrong in the conversion to JSON. When you write the value, you'll probably need to put quotes around it, to make sure it's treated as a string.
That looks like some kind of overflow problem to me.
According to this discussion here on SO, JavaScript can only handle INTs of size 2^64, which means the max INT is somewhere around
184467440737100000
which is much less than
4040956363970588323
EDIT: Sorry, the largest exact integer is 2^53, but the case is the same.
Related
I have a JsonResult returning 29833 records, of a CustomerID and a CustomerName. I am trying to load this into an AutoComplete, but I keep getting this error.
Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
I did some digging around on the subject and came across this link here
So I read over it and the answer provided didn't work out for me and then the next suggestion looked promising until I looked more at the code and came to the conclusion that it won't work for me because I am using JQuery Ajax to get the JsonResult. Now I am not sure what to do, here is the JQuery that I am using
function LoadCustomers() {
$.ajax({
type: "GET",
url: "/Test/GetAllCustomers",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, jqXHR) {
ShowCustomers(data);
}
});
}
function ShowCustomers(custdata) {
$("#acCustomers").kendoAutoComplete({
dataSource: custdata,
filter: "startswith",
placeholder: "Select Customer...",
dataTextField: "CustomerName"
});
}
I even tried just populating a grid but to no avail. Any idea's on how I can get this to work properly going about it the way I am going about it? I think as a last resort I would have to change my stored procedure around and pass in characters on every keyup event, I don't know if that would be a good idea or maybe it is, I don't know. Either way I sure could use some help or direction
EDIT
The reason that this is not a duplicate based on the supplied link is because I am not working server-side, I am working Client-Side.
EDIT 2
Here is my JsonResult
public JsonResult GetAllCustomers(string name)
{
PGDAL dal = new PGDAL();
List<Customer> lst = dal.GetAllCustomers();
return Json(lst, JsonRequestBehavior.AllowGet);
}
One thing I have learned from some experience is that it seems like ASP.net MVC ignores any JSON Max value you place in the Web.config file. I normally just do the following:
var JsonSerializer = new JavaScriptSerializer();
JsonSerializer.MaxJsonLength = Int32.MaxValue;
As Paul Swetz linked up top, you might find some more resources in managing the MAX value but I am pretty sure this will be the most widely accepted answer.
I am sorry if this is a duplicate question. I have searched for an answer but nothing seems to work.
I am trying to send quite a large JSON object to a PHP file via POST.
This is my JavaScript code :
var grid =
{
"user": 1,
"grid": JSON.stringify(hz),
"week": WEEK,
"AP": AP,
"X_VAL": X_VAL,
"Y_VAL": Y_VAL
};
grid = JSON.stringify(grid);
$.ajax({
url:"php/saveGrid.php",
type: "POST",
data : "g="+grid,
success: function (data, textStatus, jqXHR)
{
console.log(data);
}
});
This is my PHP code :
$g = stripslashes($_REQUEST["g"]);
echo $AP = $g->AP;
But this returns an error which says :
Trying to get property of non-object
What am I doing wrong?
Your primary problem is that you are trying to treat a string of JSON as if it were a PHP object.
You need to parse it first.
$g = stripslashes($_REQUEST["g"]);
$g = json_decode($g);
echo $AP = $g->AP;
You also have some secondary issues.
You failed to URL encode the JSON, so if it contains characters with special meaning in URLS, it will break.
data : "g="+grid,
should be:
data : { g: grid },
You should not need to run stripslashes over input from $_REQUEST/POST/GET.
If you don't have magic quotes turned on, then it could break the incoming data if it contains slashes.
If you do have magic quotes turned on, then you should turn them off or upgrade to a modern version of PHP (which wouldn't support them).
Nesting JSON inside JSON is silly. It bloats the data and makes it more work to read.
"grid": JSON.stringify(hz),
should be:
grid: hz,
$_REQUEST could get data from the query string, or the request body, or a cookie. You know it is coming in the request body so just use $_POST to remove the ambiguity.
You need to decode the json object then can use it as an array. Try, json_decode. Like,
$g = stripslashes($_REQUEST["g"]);
$json_de=json_decode($g);
echo $AP = $json_de['AP'];
Or if you want to see the full array then use,
print_r($json_de);
Hope this will help you.
I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.
Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});
Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH
I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}
I have added a google +1 button to a website, but I want to get it's counter so i can do some math over it. is it possible to enter the iframe created by the standard method of creating the +1 button or do I need to make some adjustment?
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<g:plusone></g:plusone>
I've tried this link:1 , but this is not very accurate
If you can access curl/file_get_contents/readfile/wget or some way to fetch an external URL, this is quite simple.
Load the following URL: https://plusone.google.com/_/+1/fastbutton?url=URLENCODED_URI (UPDATED URL, see note below *)
URLENCODED_URI is the site you wish to know the number of +1's for, e.g. http://www.google.com (http%3A%2F%2Fwww.google.com)
For example, fetch the URI https://plusone.google.com/_/+1/fastbutton?url=http://www.google.com/ (UPDATED URI) and locate the first occurance of window.__SSR = {'c': 32414.0 ,'si'. Preferably use regexp for this, but I'll leave the implementation to you and your chosen programming language (server side or client side).
The float number following 'c' is the number of +1's the site have. For google.com this is 32,414. Don't worry about the float, you can safely convert it to an integer.
* UPDATE: The URL has been updated as the old URL started to 404. Remember, this is expected as this is an unofficial method. There exist no official method (yet).
Could you use a callback function to grab the value of the div that displays the count?
function count() {
var count = $('#aggregateCount').html();
}
<g:plusone callback="count()"></g:plusone>
I'm basing this off the bubble annotation button, I haven't tested it but something like this should work.
A pure client-side solution that works for me to get the Google Plus counter is as follows. It does not need an API key.
var url = "http://www.yoursite-to-be-counted.com";
var data = {
"method":"pos.plusones.get",
"id": url,
"params":{
"nolog":true,
"id": url,
"source":"widget",
"userId":"#viewer",
"groupId":"#self"
},
"jsonrpc":"2.0",
"key":"p",
"apiVersion":"v1"
};
$.ajax({
type: "POST",
url: "https://clients6.google.com/rpc",
processData: true,
contentType: 'application/json',
data: JSON.stringify(data),
success: function(r){
setCount($(".google-plus-count"), r.result.metadata.globalCounts.count);
}
});
var setCount = function($item, count) {
if (count) {
$item.text(count);
}
};
Then I have some html with
<div class="google-plus-count"></div>
Credits here goes to this answer.