Search Results

Search found 5856 results on 235 pages for 'json encode'.

Page 13/235 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • PHP: Retrieving JSON via jQuery ajax help

    - by iamjonesy
    Hey I have a script that is creating and echoing a JSON encoded array of magento products. I have a script that calls this script using jQuery's ajax function but I'm not getting a proper response. This is the script that creates the array: $collection = Mage::getModel('catalog/product')->getCollection(); $collection->addAttributeToSelect('name'); $collection->addAttributeToSelect('price'); $products = array(); foreach ($collection as $product){ $products[$product->getPrice()] = $product->getName(); } header('Content-Type: application/x-json; charset=utf-8'); echo(json_encode($products)); Here is my jQuery: <select id="products"> <option value="#">Select</option> </select> <script type="text/javascript"> jQuery.noConflict(); jQuery(document).ready(function(){ jQuery.ajax({ type: "GET", url: "http://localhost.com/magento/modules/products/get.php", dataType: "json", success: function(products) { jQuery.each(products,function(price,name) { var opt = jQuery('<option />'); opt.val(name); opt.text(price); jQuery('#products').append(opt); }); } }); }); </script> I'm getting a response from this but I'm not seeing a any JSON. I'm using firebug. I can see there has been a JSON encoded response but the response tab is emtyp and my select boxes have no options. Can anyone see and problems with my code? Here is the response I should get: {"82.9230":"Dummy","177.0098":"Dummy 2","76.0208":"Dummy 3","470.6054":"Dummy 4","357.0083":"Dummy Product 5"} Thanks, Billy

    Read the article

  • How to select this with JSON...

    - by Oscar Godson
    I actually have two questions, both are probably simple, but for some odd reason I cant figure it out... I've worked with JSON 100s of times before too! but here is the JSON in question: {"69256":{"streaminfo":{"stream_ID":"1025","sourceowner_ID":"2","sourceowner_avatar":"http:\/\/content.nozzlmedia.com\/images\/sourceowner_avatar2.jpg","sourceownertype_ID":"1","stream_name":"Twitter","streamtype":"Social media","appsarray":[]},"item":{"headline":"Charboy","main_image":"http:\/\/content.nozzlmedia.com\/images\/author_avatar173212.jpg","summary":"ate a tomato and avocado for dinner...","nozzl_captured":"2010-05-12 23:02:12","geoarray":[{"state":"OR","county":"Multnomah","city":"Portland","neighborhood":"Downtown","zip":"97205","street":"462 SW 11th Ave","latitude":"45.5219","longitude":"-122.682"}],"full_content":"ate a tomato and avocado for dinner tonight. such tasty foods. just enjoyable.","body_text":"ate a tomato and avocado for dinner tonight. such tasty foods. just enjoyable.","author_name":"Charboy","author_avatar":"http:\/\/content.nozzlmedia.com\/images\/author_avatar173212.jpg","fulltext_url":"http:\/\/twitter.com\/charboy\/statuses\/13889868936","leftovers":{"twitter_id":"tag:search.twitter.com,2005:13889868936","date":"2010-05-13T02:59:59Z","location":"iPhone: 45.521866,-122.682262"},"wordarray":{"0":"ate","1":"tomato","2":"avocado","3":"dinner","4":"tonight","5":"tasty","6":"foods","7":"just","8":"enjoyable","9":"Charboy","11":"Twitter","13":"state:OR","14":"county:Multnomah, OR","15":"city:Portland, OR","16":"neighborhood:Downtown","17":"zip:97205"}}}} Question 1: How do I loop through each item (69256) when the number is random? e.g. item 1 is 123, item2 is 646? Like, for example, a normal JSON feed would have something like: {'item':{'blah':'lorem'},'item':{'blah':'ipsum'}} the JS would be like console.log(item.blah) to return lorem then ipsum in a loop How do I do it when i dont know the first item of the object? Question 2: How do I select items from the geoarray object? I tried: json.test.item.geoarray.latitude and json.test.item.geoarray['latitude']

    Read the article

  • "dynamic" keyword and JSON data

    - by Peter Perhác
    An action method in my ASP.NET MVC2 application returns a JsonResult object and in my unit test I would like to check that the returned JSON object indeed contains the expected values. I tried this: 1. dynamic json = ((JsonResult)myActionResult).Data; 2. Assert.AreEqual(JsonMessagesHelper.ErrorLevel.ERROR.ToString(), json.ErrorLevel); But I get a RuntimeBinderException "'object' does not contain a definition for 'ErrorLevel'". However, when I place a breakpoint on line 2 and inspect the json dynamic variable (see picture below), it obviously does contain the ErrorLevel string and it has the expected value, so if the runtime binder wasn't playing funny the test would pass. What am I not getting? What am I doing wrong and how can I fix this? How can I make the assertion pass?

    Read the article

  • meaning of the returned list of python json

    - by fmsf
    Hey, I'm new to python so I really don't know the language very well. the following example was taken from here http://docs.python.org/library/json.html >>> import json >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]') [u'foo', {u'bar': [u'baz', None, 1.0, 2]}] what does the u mean? and how do i know which elements are available in the dictionary?

    Read the article

  • JSON documentation standard?

    - by Tina
    Is there a recognized, recommended, or standard form for representing the structure of JSON? E.g., my service returns a structure, effectively, represented as JSON. How do I describe what my service returns, such that another service can consume that JSON and program to its interface?

    Read the article

  • How can I send a json string to view as a json object?

    - by yapiskan
    I have a json string in an action of MVC controller. I want to send it to view as a JSON object. How can I solve this? public JsonResult Json() { ... some code here ... string jsonString = "{\"Success\":true, \"Msg\":null}"; return new JsonResult() { Data = jsonString, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; }

    Read the article

  • Parsing a dynamic value with Lift-JSON

    - by Surya Suravarapu
    Let me explain this question with an example. If I have a JSON like the following: {"person1":{"name": "Name One", "address": {"street": "Some Street","city": "Some City"}}, "person2":{"name": "Name Two", "address": {"street": "Some Other Street","city": "Some Other City"}}} [There is no restriction on the number of persons, the input JSON can have many more persons] I could extract this JSON to Persons object by doing var persons = parse(res).extract[T] Here are the related case classes: case class Address(street: String, city: String) case class Person(name: String, address: Address, children: List[Child]) case class Persons(person1: Person, person2: Person) Question: The above scenario works perfectly fine. However the need is that the keys are dynamic in the key/value pairs. So in the example JSON provided, person1 and person2 could be anything, I need to read them dynamically. What's the best possible structure for Persons class to account for that dynamic nature.

    Read the article

  • Jquery ajax load of JSON in unit tests

    - by wmitchell
    I'm trying to load a dataset in jasmine for my tests like such ... However as its a json call I cant seem to always get the test denoted by "it" to wait till the JSON call has finished before using its array. I tried using the ajaxStop function to no avail. Any ideas ? describe("simple checks", function() { var exampleArray = new Array(); beforeEach(function(){ $(document).ajaxStop(function() { $(this).unbind("ajaxStop"); $.getJSON('/jasmine/obj.json', function(data) { $.each( json.jsonattr, function(i, widgetElement) { exampleArray.push(new widget(widgetElement)); }); }); }); }); it("use the exampleArray", function() { doSomething(exampleArray[0]); // frequently this is coming up as undefined });

    Read the article

  • Flash crash on long JSON load time

    - by MooCow
    I have a Flex program that gets a JSON array from a PHP script. The PHP script doesn't contain just a simple JSON array but it grabs data from Activecollab and do some work on the data before encoding the data. The first test involve a small JSON array that took a short time to encode by PHP. However, when I try to scale up the test, the Flash movie will crash trying to load the JSON data from PHP. There's no code difference between the tests, just the amount of data and amount of time it takes PHP to encode. Am I looking at a memory problem or a time out problem?

    Read the article

  • How to add values to a JSON object?

    - by Damiano
    Hello everybody, I have created an array with: var msg = new Array(); then, I have a function that add values to this array, this function is: function add(time, user, text){ var message = [time, user, text]; if (msg.length >= 50) msg.shift(); msg.push(message); } As you can see, if the array has 50 or more elements I remove the first with .shift(). Then I add an array as element. Ok, the code works perfectly, but now I have to loop the msg array to create a JSON obj. The JSON object should has this format: var obj = [ {'time' : time, 'user' : user, 'text' : text}, {'time' : time, 'user' : user, 'text' : text}, {'time' : time, 'user' : user, 'text' : text} ] I mean...i have to loop msg array and then store all the values inside the JSON object. I do not know how to "concatenate" the element of the array inside json obj. Could you help me? Thank you very much in advance!

    Read the article

  • Making JSON Feed Work Server to Server

    - by Oscar Godson
    I have a JSON feed (which I don't directly control, I have to ask the server admins to update it), that is returning NULL, or otherwise not working when I try to access it from another server. The actual feed works fine, but I can't get it to work like a normal API. Why can I use Flickr, WhitePages, Twitter, etc's JSON APIs, but for: http://portlandoregon.gov/shared/cfm/json.cfm It returns NULL in the browser when using JS. If I call it on the same server, it's fine though. If this is a server issue, what do I ask the admins to change, and if this is a local (browser) based issue, what am I doing wrong for this one feed that works for every other JSON API?

    Read the article

  • Python json memory bloat

    - by Anoop
    import json import time from itertools import count def keygen(size): for i in count(1): s = str(i) yield '0' * (size - len(s)) + str(s) def jsontest(num): keys = keygen(20) kvjson = json.dumps(dict((keys.next(), '0' * 200) for i in range(num))) kvpairs = json.loads(kvjson) del kvpairs # Not required. Just to check if it makes any difference print 'load completed' jsontest(500000) while 1: time.sleep(1) Linux top indicates that the python process holds ~450Mb of RAM after completion of 'jsontest' function. If the call to 'json.loads' is omitted then this issue is not observed. A gc.collect after this function execution does releases the memory. Looks like the memory is not held in any caches or python's internal memory allocator as explicit call to gc.collect is releasing memory. Is this happening because the threshold for garbage collection (700, 10, 10) was never reached ? I did put some code after jsontest to simulate threshold. But it didn't help.

    Read the article

  • handle json request in PHP

    - by wo_shi_ni_ba_ba
    When making an ajax call, when contentType is set to application/json instead of the default x-www-form-urlencoded, server side (in PHP) can't get the post parameters. in the following working example, if I set the contentType to "application/json" in the ajax request, PHP $_POST would be empty. why does this happen? How can I handle a request where contentType is application/json properly in PHP? $.ajax({ cache: false, type: "POST", url: "xxx.php", //contentType: "application/json", processData: true, data: {my_params:123}, success: function(res){ }, complete: function(XMLHttpRequest, text_status) { } });

    Read the article

  • Can not get json response using $.getJSON

    - by Mellon
    I am currently developing a Ruby on rails 3 application. My server controller function render a json object as response: class DaysController < BaseController ... def the_days ... render :json => days end end In my javascript,I use the following code to get json response from server( that's from the_day function in controller) $.getJSON( url, {emp_id: emp_id}, function(data) { var result = data.response; alert(result) alert(data) }, "json" ); I use firefox browswer and checked with Firebug, in Firebug Net-XHR, I see the Get request is successful, and the response "days" is there. That's both request and response are successful. But I did not see the two alert window defined in the above $.getJSON function, why? Why I can not get the response "days" in $.getJSON function??

    Read the article

  • Safely turning a JSON string into an object

    - by Matt Sheppard
    Given a string of JSON data, how can you safely turn that string into a JavaScript object? Obviously you can do this unsafely with something like... var obj = eval("(" + json + ')'); ...but that leaves us vulnerable to the json string containing other code, which it seems very dangerous to simply eval.

    Read the article

  • Ajax BeginForm posting to an action that returns json, IE tries to download it

    - by ryanrdl
    Here is the code I am using to setup the form: <% using (Ajax.BeginForm("SaveCroppedPhoto", new { Id = Model.memberId.GetValueOrDefault() }, new AjaxOptions { OnBegin = "ProfileOnBegin", OnComplete = "ProfileOnComplete", OnFailure = "ProfileOnFailure", OnSuccess = "ProfileOnSuccess" }, new { id = "cropPhotoForm" })) {%> My action result returns a json result as follow: return Json(new { success }); In IE8 when the action returns, it tries to download the result. The content type coming back is application/json. Anyone have any idea how to stop IE from trying to download the result?

    Read the article

  • Dynamically add data stored in php to nested json

    - by HoGo
    I am trying to dynamicaly generate data in json for jQuery gantt chart. I know PHP but am totally green with JavaScript. I have read dozen of solutions on how dynamicaly add data to json, and tried few dozens of combinations and nothing. Here is the json format: var data = [{ name: "Sprint 0", desc: "Analysis", values: [{ from: "/Date(1320192000000)/", to: "/Date(1322401600000)/", label: "Requirement Gathering", customClass: "ganttRed" }] },{ name: " ", desc: "Scoping", values: [{ from: "/Date(1322611200000)/", to: "/Date(1323302400000)/", label: "Scoping", customClass: "ganttRed" }] }, <!-- Somoe more data--> }]; now I have all data in php db result. Here it goes: $rows=$db->fetchAllRows($result); $rowsNum=count($rows); And this is how I wanted to create json out of it: var data=''; <?php foreach ($rows as $row){ ?> data['name']="<?php echo $row['name'];?>"; data['desc']="<?php echo $row['desc'];?>"; data['values'] = {"from" : "/Date(<?php echo $row['from'];?>)/", "to" : "/Date(<?php echo $row['to'];?>)/", "label" : "<?php echo $row['label'];?>", "customClass" : "ganttOrange"}; } However this does not work. I have tried without loop and replacing php variables with plain text just to check, but it did not work either. Displays chart without added items. If I add new item by adding it to the list of values, it works. So there is no problem with the Gantt itself or paths. Based on all above I assume the problem is with adding plain data to json. Can anyone please help me to fix it?

    Read the article

  • returning JSON response to a ajax call prompts file download containing the response

    - by user200018
    i am submitting a from using jQuery ajax, and server is returning json response. but instead of the script, parsing the json result, the browser is prompting me to download the json response. I have had this problem before, where i forgot to return false at the end of the event handler. But this time im clueless why this is happening. anyone has experienced this problem.. thanks

    Read the article

  • jQuery AJAX PHP JSON problem

    - by Curro
    Hi Gurus I'm facing the problem of receiving an empty array when I do an AJAX request in the following way: This is the code I'm executing in JavaScript: <script type="text/javascript" src="lib/jquery.js"></script> <script type="text/javascript" src="lib/jquery.json.js"></script> <script type="text/javascript"> $(document).ready(function(){ /* Preparar JSON para el request */ var mJSON = new Object; mJSON.id_consulta = new Array; for (var i=0; i<3; i++){ mJSON.id_consulta[i] = new Object; mJSON.id_consulta[i].id = i; } var sJSON = $.toJSON(mJSON); $.ajax({ type: "POST", url: "getUbicaciones.php", data: sJSON, dataType: "json", contentType: "application/json; charset=utf-8", success: function(respuesta){ alert(respuesta); }, error: function (request,error){ alert("Error: " + request.statusText + ". " + error); } }); }); </script> And this is the code under PHP: <?php /* Decodificar JSON */ $m_decoded = $_POST; print_r($m_decoded); exit; ?> And all I get from this, using Chrome's Developer Tools is an empty array: Array ( ) Any clues on what am I doing wrong? The string sJSON is being encoded correctly, this is what I get when I do an "alert" on that one: {"id_consulta":[{"id":1},{"id":2},{"id":3}]} Thank you everyone in advance!

    Read the article

  • How to deal with JSON output that might be an array, or might be a value

    - by Summer
    Hi - I'm getting JSON-encoded output from another organization's API. In many cases, the output can be either an array of objects (if there are many) or an object (if there's just one). Right now I'm writing tortured code like this: if ( is_array($json['candidateList']['candidate'][0]) ) { foreach ($json['candidateList']['candidate'] as $candidate) { // do something to each object } } else { // do something to the single object } How can I handle it so the "do something" part of my code only appears once and uses a standard syntax?

    Read the article

  • how to extract information from JSON using jQuery

    - by Richard Reddy
    Hi, I have a JSON response that is formatted from my C# WebMethod using the JavascriptSerializer Class. I currently get the following JSON back from my query: {"d":"[{\"Lat\":\"51.85036\",\"Long\":\"-8.48901\"},{\"Lat\":\"51.89857\",\"Long\":\"-8.47229\"}]"} I'm having an issue with my code below that I'm hoping someone might be able to shed some light on. I can't seem to get at the information out of the values returned to me. Ideally I would like to be able to read in the Lat and Long values for each row returned to me. Below is what I currently have: $.ajax({ type: "POST", url: "page.aspx/LoadWayPoints", data: "{'args': '" + $('numJourneys').val() + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { if (msg.d != '[]') { var lat = ""; var long = ""; $.each(msg.d, function () { lat = this['MapLatPosition']; long = this['MapLongPosition']; }); alert('lat =' + lat + ', long =' + long); } } }); I think the issue is something to do with how the JSON is formatted but I might be incorrect. Any help would be great. Thanks, Rich

    Read the article

  • Simple Serialization Faster Than JSON? (in Ruby)

    - by Sinan Taifour
    I have an application written in ruby (that runs in the JRuby VM). When profiling it, I realized that it spends a lot (actually almost all of) its time converting some hashes into JSON. These hashes have keys of symbols, values of other similar hashes, arrays, strings, and numbers. Is there a serialization method that is suitable for such an input, and would typically run faster than JSON? It would preferable if it is has a Java or JRuby-compatible gem, too. I am currently using the jruby-json gem, which is the fastest JSON implementation in JRuby (as I am told), so the move will most likely be to a different serialization method rather than just a different library. Any help is appreciated! Thanks.

    Read the article

  • json returning string instead of object

    - by peter
    i have $age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11] $ww = json_encode($age); and then i retrieve it here var age = JSON.parse(<?php echo json_encode($ww); ?>); so if i make alert(typeof(<?php echo $age; ?>)) // object alert(typeof(age)) //string in my case JSON.parse retuned as string. how can i let json return as object? EDIT: var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error

    Read the article

  • Serialize Dictionary with a string key and List[] value to JSON

    - by Patrick
    How can I serialize a python Dictionary to JSON and pass back to javascript, which contains a string key, while the value is a List (i.e. []) if request.is_ajax() and request.method == 'GET': groupSet = GroupSet.objects.get(id=int(request.GET["groupSetId"])) groups = groupSet.groups.all() group_items = [] #list groups_and_items = {} #dictionary for group in groups: group_items.extend([group_item for group_item in group.group_items.all()]) #use group as Key name and group_items (LIST) as the value groups_and_items[group] = group_items data = serializers.serialize("json", groups_and_items) return HttpResponse(data, mimetype="application/json") the result: [{"pk": 5, "model": "myApp.group", "fields": {"name": "\u6fb4\u9584", "group_items": [13]}}] while the group_items should have many group_item and each group_item should have "name", rather than only the Id, in this case the Id is 13. I need to serialize the group name, as well as the group_item's Id and name as JSON and pass back to javascript. I am new to Python and Django, please advice me if you have a better way to do this, appreciate. Thank you so much. :)

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >