Search Results

Search found 4865 results on 195 pages for 'json'.

Page 17/195 | < Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >

  • Add JSON support to Rails app

    - by Meltemi
    I am experimenting with Rails and was wondering what's needed to allow/add support for JSON requests? I have a vanilla installation of Rails 2.3.5 and the default scaffolding seem to provide support for HTML & XML requests but not JSON. class EventsController < ApplicationController # GET /events # GET /events.xml def index @events = Event.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @events } end end # GET /events/1 # GET /events/1.xml def show @event = Event.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @event } end end ... I'm new to this but it would appear as though i would need to add a format line in each method along the lines of: format.js { render :js => @event.json } couldn't this be done automatically? perhaps there's a template somewhere i need to update...or a flag i can set? Or perhaps, and most likely, I've missed the boat entirely?!?

    Read the article

  • Convert JSON String to Java Object or HashMap

    - by Priyank
    Hi. I am writing an android app. I want to pass some data across the intents/activities and I feel that a conversion to and from JSON is probably a more optimal way at this point. I am able to convert a java hashmap to a json string successfully using JSONObject support. However i need to convert back this JSON string to a java object or a hashmap. What is the best way to go about it. Is parcelable really a change worth doing; if I have simple 5 field object? What are the other ways to transfer data between intents. Cheers

    Read the article

  • How can I force asp.net webapi to always decode POST data as JSON

    - by Nathan Reed
    I getting some json data posted to my asp.net webapi, but the post parameter is always coming up null - the data is not being serialized correctly. The method looks something like this: public HttpResponseMessage Post(string id, RegistrationData registerData) It seems the problem is that the client (which I have no control over) is always sending the content-type as x-www-form-urlencoded, even though the content is actually json. This causes mvc to try to deserialize as form data, which fails. Is there anyway to get webapi to always deserialize as json, and to ignore the content-type header?

    Read the article

  • PHP JSON encode output number as string

    - by mitch
    I am trying to output a JSON string using PHP and MySQL but the latitude and longitude is outputting as a string with quotes around the values. This causes an issue when I am trying to add the markers to a google map. Here is my code: $sql = mysql_query('SELECT * FROM markers WHERE address !=""'); $results = array(); while($row = mysql_fetch_array($sql)) { $results[] = array( 'latitude' =>$row['lat'], 'longitude' => $row['lng'], 'address' => $row['address'], 'project_ID' => $row['project_ID'], 'marker_id' => $row['marker_id'] ); } $json = json_encode($results); echo "{\"markers\":"; echo $json; echo "}"; Here is the expected output: {"markers":[{"latitude":0.000000,"longitude":0.000000,"address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]} Here is the output that I am getting: {"markers":[{"latitude":"0.000000","longitude":"0.000000","address":"2234 2nd Ave, Seattle, WA","project_ID":"7","marker_id":"21"}]} Notice the quotes around the latitude and longitude values.

    Read the article

  • Convert data retrieved from MySQL database into JSON object using Python/Django

    - by rohanbk
    I have a MySQL database called People which contains the following schema <id,name,foodchoice1,foodchoice2>. The database contains a list of people and the two choices of food they wish to have at a party (for example). I want to create some kind of Python web-service that will output a JSON object. An example of output should be like: { "guestlist": [ {"id":1,"name":"Bob","choice1":"chicken","choice2":"pasta"},{"id":2,"name":"Alice","choice1":"pasta","choice2":"chicken"} ], "partyname": "My awesome party", "day": "1", "month": "June", "2010": "null" } Basically every guest is stored into a dictionary 'guestlist' along with their choices of food. At the end of the JSON object is just some additional information that only needs to be mentioned once. The question that I have is regarding the method that I need to utilize to grab the data from my database, and create the JSON object. Do I need to use a standard Model/View structure of Django or can I get away with something that is much simpler since what I need to do is really simple?

    Read the article

  • issue with parsing JSON string

    - by bgosalci
    I have this object which I use as a list of objects: var objList = new Object(); This is then serialized using JSON serialize. If there are no object added or all objects have been removed from the list and the blank objList is serialized, parsing the objList using JSON parser in IE, it will occasionally fail to evaluate the objList as a JavaScript object. This causes the Object doesn't support this property or method error when tying to add an object to the objList: objList['idx']=objData; Does anyone know why does IE occasionally fail to evaluate objList:{} to an object and has someone else come across this issue. The actual JSON string when the objList is '{}' The objList is initialised: objList = g_objList.parseJSON();

    Read the article

  • Jquery each loop with json array

    - by Ben
    I'm trying to use Jquery's each loop to go through this Json and add it to a div named #contentHere. The Json is as follows: { "justIn": [ { "textId": "123", "text": "Hello", "textType": "Greeting" }, { "textId": "514", "text":"What's up?", "textType": "Question" }, { "textId": "122", "text":"Come over here", "textType": "Order" } ], "recent": [ { "textId": "1255", "text": "Hello", "textType": "Greeting" }, { "textId": "6564", "text":"What's up?", "textType": "Question" }, { "textId": "0192", "text":"Come over here", "textType": "Order" } ], "old": [ { "textId": "5213", "text": "Hello", "textType": "Greeting" }, { "textId": "9758", "text":"What's up?", "textType": "Question" }, { "textId": "7655", "text":"Come over here", "textType": "Order" } ] } I'm getting this Json through use of this code: $.get("data.php", function(data){ }) Any solutions?

    Read the article

  • Trying to get a json result back from method in another namespace, having issues

    - by Blankman
    I have a seperate .js file and namespace for json requests. I have another .js file and namespace for the actual logic. I can't seem to get the result back in my logic layer. var jsonResult = Blah.Data.LoadAggregates(); alert(jsonResult); alert(jsonResult.d.length); alert(jsonResult.length); all of the above calls are returning undefined. Blah.RegisterNamespace("Blah.Data"); (function(Data) { Data.LoadAggregates = function() { $.ajax({ type: "POST", url: "asdf.asmx/GetAggregates", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(data) { ??????? }, error: function(msg) { alert("error" + msg); } }); }; })(Blah.Data);

    Read the article

  • Dynamically add new HTML elements on page load after getting JSON data from Web API

    - by Luis D Urraca
    I'm building an hybrid Android App using Phonegap/Apache Cordova. My app should get data from my web api. I'm using JSON to serve the data to the APP. So i got a the following code: function init() { document.addEventListener('deviceready', onDeviceReady, false); var url = "http://23.21.128.153:3000/regions.json";var jsonresults; $.getJSON(url,function(data){ jsonresults = data; $.each(jsonresults, function(i,v){ $('#main-content').append('<li>'+jsonresults[i].name+'</li>'); }); }); } and also on the body of the html i have a div called main-content. Everythings works fine in the Eclipse browser, but on the Android Emulator is not working. Not sure if there's another way to pull data from Web API using JSON and dinamically create HMTL elements after getting the data. https://gist.github.com/2956660

    Read the article

  • Reading JSON with JQuery

    - by user70192
    Hello, I am using JQuery to execute an operation within a web service. After writing data back to my databaes, the service returns a JSON response. My request looks like the following: $.ajax({ url: "/services/myService.svc/PostMessage", type: "POST", contentType: "application/json; charset=utf-8", data: '{"message":"testing","comments":"test"}', dataType: "json", success: function (response) { if ((response.d != null) && (response.d.length > 0)) { // Parse the status code here } else { alert("error!"); } }, error: function (req, msg, obj) { alert("error: " + req.responseText); } }); When my response is returned, response.d contains the following: [{"StatusCode":1}] How do I parse out the value of the StatusCode?

    Read the article

  • Using JSON, passing variable from php to javascript

    - by Ryan Fung
    I wonder why it is not working? check_login.php <?php session_start(); $data = array("username" => "true"); echo json_encode($data); ?> my js file var linkName; $.ajax({ type: "POST", url: "check_login.php", dataType: "json", success: function(json){ if(json.username != "true") { //do something } } }); I am trying to get the username after checking whether or not the user has signed in yet in the php file, something like passing a session variable. But currently passing a string seems to already have a problem. Any know what I did wrong here? Still not working the code above. Anyone want to help me out here?

    Read the article

  • Loop through JSON data Associatively

    - by Abs
    Hello all, How can I loop through this json data without referring to the data items by a number. I would like to use it as an associative array. I have this so far: $.post('/controlpanel/search', { type: type, string: string }, function(data){ $.each(data, function() { $.each(this, function(index, itemData) { //alert(data.id) something like this //currently returns undefined }); }); }, 'json'); Example Json Code: [{"id":"1","title":"","link":"http:\/\/www.msn.com","date_added":"0000-00-00 00:00:00", "privacy_type":"0","user_id":"8","field2":"","field3":"","bookmark_id":"70","tag":"clean"}] Thanks all for any help

    Read the article

  • Parsing Serialized JSON DataSet using Jquery

    - by Zachary Carter
    Hello all, and thanks for reading. I wrote a web service which is called through jsonp, and returns a .Net 3.5 DataSet which I then want to parse using jquery. It appears that the getJson() method is working fine as far as parsing the json goes. The following request - $.getJSON("http://localhost:80/ws.asmx/Example?format=json&callback=?", function(data) { alert(data.d); }); results in - {"Tables": [ { "Rows": [ { "CASE_TYP_CD": "M", "CASE_TYP_DESC": "MOVING VIOLATION", "AUTO_GENERATE": "Y", "CONFIDENTIAL_FLG": "N" }, { "CASE_TYP_CD": "T", "CASE_TYP_DESC": "TRUANCY/FAILURE TO ATTEND SCHOOL", "AUTO_GENERATE": "Y", "CONFIDENTIAL_FLG": "N" }, { "CASE_TYP_CD": "J", "CASE_TYP_DESC": "JUVENILE", "AUTO_GENERATE": "Y", "CONFIDENTIAL_FLG": "N" }... Well I'm kind of new at this whole json thing and I can't figure out how to gain access to the values held in the nodes. I was thinking it would be something like - $.each("CASE_TYP_CD", function() { //code goes here }); But that doesn't seem to be working. Could anyone help me out with this? Thanks in advance!

    Read the article

  • Making of JSON Webservice using C# .NET

    - by Parth_90
    I am trying to make JSON webservice in C# .NET. A json string is returning by web method but it contains xml structure like: <string xmlns="http://tempuri.org/"> {"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]} </string> I saw this article before it wasn't much helpful for me. So my problem is, that json string is not returned in its pure format. I do not want that xml version and xmlns string. I plan to consume the web service on Android later. Can anyone help me? Thanks

    Read the article

  • Web-based JSON editor that works like property explorer with AJAXy input form

    - by dreftymac
    Background: This is a request for something that may not exist yet, but I've been meaning to build one for a long time. First I will ask if anyone has seen anything like it yet. Suppose you have an arbitrary JSON structure like the following: { 'str_title':'My Employee List' ,'str_lastmod': '2009-June-15' ,'arr_list':[ {'firstname':'john','lastname':'doe','age':'33',} ,{'firstname':'jane','lastname':'doe','age':'34',} ,{'firstname':'samuel','lastname':'doe','age':'35',} ] } Question: Is there a web-based JSON editor that could take a structure like this, and automatically allow the user to modify this in a user-friendly GUI? Example: Imagine an auto-generated HTML form that displays 2 input-type-text controls for both title and lastmod, and a table of input-type-text controls with three columns and three rows for arr_list ... with the ability to delete or add additional rows by clicking on a [+][X] next to each row in the table. Big Idea: The "big idea" behind this is that the user would be able to specify any arbitrary (non-recursive) JSON structure and then also be able to edit the structure with a GUI-based interaction (this would be similar to the "XML Editor Grid View" in XML Spy).

    Read the article

  • cannot display json data returned from jquery ajax call

    - by amby
    Hi, can somebody please tell me, how can I display json data returning from the ajax call. I am new to this. $.ajax({ type: "POST", dataType: 'JSON', //data: "{'ntid':'john'}", //contentType: "application/json; charset=utf-8", //processData: false, url: "Testing.aspx/SendMessage", error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); }, success: function(result, txtStatus, httpRequest) { alert(txtStatus); the_object = result; $('#status').html(concatObject(the_object)); } above is the js file. should i need to do something on asp file directly to display it. if yes, then how? please reply me soon. i m stuck here and unable to display data here

    Read the article

  • PHP and JSON comment help..

    - by jay
    hi, guys thanks for looking my problem is that i cant seem to get jquery to display my generated data. here is my JSON output ("posts":[{"id":"1-2","time":"0","name":"dash","avatar":"http:\/\/www.gravatar.com\/avatar\/9ff30cc2646099e31a4ee4c0376091b0?s=182&d=identicon&r=PG","comment":"rtetretrete tet rt uh utert"},{"id":"2-2","time":"0","name":"james","avatar":"http:\/\/www.gravatar.com\/avatar\/d41d8cd98f00b204e9800998ecf8427e?s=182&d=identicon&r=PG","comment":"fsdfdfsdf\r\n"}]) and here is my jquery $(document).ready(function(){ var url="comments.php"; $.getJSON(url,function(json){ $.each(json.posts,function(i,post){ $("#content").append( '<div class="post">'+ '<h1>'+post.name+'</h1>'+ '<p>'+post.comment+'</p>'+ '<p>added: <em>'+post.time+'</em></p>'+ '<p>posted by: <strong>'+post.name+'</strong></p>'+ '<p>avatar: <strong>'+post.avatar+'</strong></p>'+ '</div>' ); }); }); });

    Read the article

  • treating json like an array

    - by tawheed
    I was doing some test with json and ran into serveral issues. hope somebody on this mailing list can help out. localStorage[LOC] = JSON.stringify(track); var boy = localStorage[LOC]; alert(boy); This is the data I get back [{"lat":42.5877511,"lng":-71.7873177,"acc":67,"date":"Sat Apr 14 2012 01:03:46 GMT-0400 (EDT)"}] I was wondering how I could access the json objects like we do in a regular array. For debugging purposes I did something like, alert(boy[0].lat); But the result I got back was undefined

    Read the article

  • Returning Json object from controller action to jQuery

    - by PsychoCoder
    I'm attempting to get this working properly (2 days now). I'm working on a log in where I'm calling the controller action from jQuery, passing it a JSON object (utilizing json2.js) and returning a Json object from the controller. I'm able to call the action fine, but instead of being able to put the response where I want it it just opens a new window with this printed on the screen: {"Message":"Invalid username/password combination"} And the URL looks like http://localhost:13719/Account/LogOn so instead of calling the action and not reloading the page it's taking the user to the controller, which isn't good. So now for some code, first the controller code [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl = "") { if (ModelState.IsValid) { var login = ObjectFactory.GetInstance<IRepository<PhotographerLogin>>(); var user = login.FindOne(x => x.Login == model.Username && x.Pwd == model.Password); if (user == null) return Json(new FailedLoginViewModel { Message = "Invalid username/password combination" }); else { if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); else return RedirectToAction("Index", "Home"); } } return RedirectToAction("Index", "Home"); } And the jQuery code $("#signin_submit").click(function () { var login = getLogin(); $.ajax({ type: "POST", url: "../Account/LogOn", data: JSON.stringify(login), dataType: 'json', contentType: 'application/json; charset=utf-8', error: function (xhr) { $("#message").text(xhr.statusText); }, success: function (result) { } }); }); function getLogin() { var un = $("#username").val(); var pwd = $("#password").val(); var rememberMe = $("#rememberme").val(); return (un == "") ? null : { Username: un, Password: pwd, RememberMe: rememberMe }; } In case you need to see the actual login form here that is as well <fieldset id="signin_menu"> <div> <span id="message"></span> </div> <% Html.EnableClientValidation(); %> <% using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { @id = "signin" })) {%> <% ViewContext.FormContext.ValidationSummaryId = "valLogOnContainer"; %> <%= Html.LabelFor(m => m.Username) %> <%= Html.TextBoxFor(m => m.Username, new { @class = "inputbox", @tabindex = "4", @id = "username" })%><%= Html.ValidationMessageFor(m => m.Username, "*")%> <p> <%= Html.LabelFor(m=>m.Password) %> <%= Html.PasswordFor(m => m.Password, new { @class = "inputbox", @tabindex = "5", @id = "password" })%><%= Html.ValidationMessageFor(m => m.Password, "*")%> </p> <p class="remember"> <input id="signin_submit" value="Sign in" tabindex="6" type="submit"/> <%= Html.CheckBoxFor(m => m.RememberMe, new { @class = "inputbox", @tabindex = "7", @id = "rememberme" })%> <%= Html.LabelFor(m => m.RememberMe) %> <p class="forgot"> <a href="#" id="forgot_password_link" title="Click here to reset your password.">Forgot your password?</a> </p> <p class="forgot-username"> <a href="#" id="forgot_username_link" title="Fogot your login name? We can help with that">Forgot your username?</a> </p> </p> <%= Html.ValidationSummaryJQuery("Please fix the following errors.", new Dictionary<string, object> { { "id", "valLogOnContainer" } })%> <% } %> </fieldset> The login form is loaded on the main page with <% Html.RenderPartial("LogonControl");%> Not sure if that has any bearing on this or not but thought I'd mention it. EDIT: The login form is loaded similar to the Twitter login, click a link and the form loads with the help of jQuery & CSS

    Read the article

  • How to upload file via the JSON interface in Rails

    - by akafazov
    Hi, I have a web service in Rails which among all else should provide file upload functionality to the clients. The clients all use JSON to talk to the webservice. I use the Paperclip plugin for upload management. The problem is I do not know how to upload a file via JSON. All works in the web formular, but I cannot find information on how to consctruct my JSON Request to send files to the server. Can somebody help out? Regards, Angel Kafazov

    Read the article

  • Django json serialization problem

    - by codingJoe
    I am having difficulty serializing a django object. The problem is that there are foreign keys. I want the serialization to have data from the referenced object, not just the index. For example, I would like the sponsor data field to say "sponsor.last_name, sponsor.first_name" rather than "13". How can I fix my serialization? json data: {"totalCount":"2","activities":[{"pk": 1, "model": "app.activity", "fields": {"activity_date": "2010-12-20", "description": "my activity", "sponsor": 13, "location": 1, .... model code: class Activity(models.Model): activity_date = models.DateField() description = models.CharField(max_length=200) sponsor = models.ForeignKey(Sponsor) location = models.ForeignKey(Location) class Sponsor(models.Model): last_name = models.CharField(max_length=20) first_name= models.CharField(max_length=20) specialty = models.CharField(max_length=100) class Location(models.Model): location_num = models.IntegerField(primary_key=True) location_name = models.CharField(max_length=100) def activityJSON(request): activities = Activity.objects.all() total = activities.count() activities_json = serializers.serialize("json", activities) data = "{\"totalCount\":\"%s\",\"activities\":%s}" % (total, activities_json) return HttpResponse(data, mimetype="application/json")

    Read the article

  • Benefit of outputting JSON as opposed to plain HTML

    - by Franco
    Hey guys, Just wondering which is best here. I want to output data from a table in my DB then put a lot of this data into a html table on the fly on my page. Im working with Java on the server side. Basically I pull the results form the DB and have the raw data..just what next? There is a chance I may want to take data from multiple tables in order to combine it into one table for my site. I retrieve the results of the query from the DB, now do i create a text from it in the form of json which i can parse as json using jquery upon the return of the object to my browser?(kind of a sub question of this question: Is just using a stringbuilder the correct way to make a json object to output?) Or.. Should i build the HTML as a string and output that to the browser instead? Which is better and why? Thanks in advance!

    Read the article

  • MySql products and categories tables using php and json

    - by Romina Mora
    I have just started learning all this coding language and the teacher is asking us to do the following. I know it may sound really easy for people who do this full time or have more time coding. The teacher is always telling us to GOOGLE everything and I have tried too many sites but I haven't found anything that helps me at all. I need to write two JSON documents (products and categories) using PHP that will dynamically read values from my MySQL database. When each document is called upon, it will return perfectly formatted JSON that will validate using http://jsonlint.com/ Honestly I don't know what to do. I don't understand PHP and now this JSON thing is making it more confusing.

    Read the article

  • How to access fields in JSON object by index

    - by Stefan
    I know this isn't the best way to do it, but I have no other choice :( I have to access the items in JSONObject by their index. The standard way to access objects is to just wirte this[objectName] or this.objectName. I also found a method to get all the fields inside a json object: (for (var key in p) { if (p.hasOwnProperty(key)) { alert(key + " -> " + p[key]); } } (Soruce : Loop through Json object). However there is no way of accessing the JSONfields directly by a index. The only way I see right now, is to create an array, with the function above, get the fieldname by index and then get the value by fieldname. As far as I see it, the p (in our case the JSON file must be an iteratable array to, or else the foreach loop wouldn't work. How can I access this array directly? Or is it some kind of unsorted list? Regards, Stefan

    Read the article

  • IE7 not digesting JSON: "parse error"

    - by Kenny Leu
    While trying to GET a JSON, my callback function is NOT firing. $.ajax({ type:"GET", dataType:'json', url: myLocalURL, data: myData, success: function(returned_data){alert('success');} }); The strangest part of this is that my JSON(s) validates on JSONlint this ONLY fails on IE7...it works in Safari, Chrome, and all versions of Firefox. If I use 'error', then it reports "parseError"...even though it validates! Is there anything that I'm missing? Does IE7 not process certain characters, data structures (my data doesn't have anything non-alphanumeric, but it DOES have nested JSONs)? I have used tons of other AJAX calls that all work (even in IE7), but with the exception of THIS call. An example data return here is: {"question":{ "question_id":"19", "question_text":"testing", "other_crap":"none" }, "timestamp":{ "response":"answer", "response_text":"the text here" } } I am completely at a loss. Hopefully someone has some insight into what's going on...thank you!

    Read the article

< Previous Page | 13 14 15 16 17 18 19 20 21 22 23 24  | Next Page >