Search Results

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

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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • 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

  • Expose JSON as queryable for jQuery

    - by Ted
    I am trying to expose some data, user names, as json format on my server. I want to use jQuery.getJSOn() method to query data. I can get my data converted to json with newtonsoft.dll on server and save it in a file. But as far as I know it is not queryable. I want something like http://search.twitter.com/search.json?callback=?&q=abc Can anyone help me out to expose my data ion the above format.

    Read the article

  • How to get at JSON in grails 2.0

    - by Mikey
    I am sending myself JSON like so with jQuery: $.ajax ({ type: "POST", url: 'http://localhost:8080/myproject/myController/myAction', dataType: 'json', async: false, //json object to sent to the authentication url data: {"stuff":"yes", "listThing":[1,2,3], "listObjects":[{"one":"thing"},{"two":"thing2"}]}, success: function () { alert("Thanks!"); } }) I send this to a controller and do println params And I know I'm already in trouble... [stuff:yes, listObjects[1][two]:thing2, listObjects[0][one]:thing, listThing[]:[1, 2, 3], action:myAction, controller:myController] I cannot figure out how to get at most of these values... I can get "yes" with params.stuff, but I cant do params.listThing.each{} or params.listObjects.each{} What am I doing wrong? UPDATE: I make the controller do this to try the two suggestions so far: println params println params.stuff println params.list('listObjects') println params.listThing def thisWontWork = JSON.parse(params.listThing) render("omg l2json") look how weird the parameters look at the end of the null pointer exception when I try the answers: [stuff:yes, listObjects[1][two]:thing2, listObjects[0][one]:thing, listThing[]:[1, 2, 3], action:l2json, controller:rateAPI] yes [] null | Error 2012-03-25 22:16:13,950 ["http-bio-8080"-exec-7] ERROR errors.GrailsExceptionResolver - NullPointerException occurred when processing request: [POST] /myproject/myController/myAction - parameters: stuff: yes listObjects[1][two]: thing2 listObjects[0][one]: thing listThing[]: 1 listThing[]: 2 listThing[]: 3 UPDATE 2 I am learning things, but this can't be right: println params['listThing[]'] println params['listObjects[0][one]'] prints [1, 2, 3] thing It seems like this is some part of grails new JSON marshaling. This is somewhat inconvenient for my purposes of hacking around with the values. How would I get all these individual params back into a big groovy object of nested maps and lists? Maybe I am not doing what I want with jQuery?

    Read the article

  • Returning JSON in CFFunction and appending it to layer is causing an error

    - by Mel
    I'm using the qTip jQuery plugin to generate a dynamic tooltip. I'm getting an error in my JS, and I'm unsure if its source is the JSON or the JS. The tooltip calls the following function: (sorry about all this code, but it's necessary) <cffunction name="fGameDetails" access="remote" returnType="any" returnformat="JSON" output="false" hint="This grabs game details for the games.cfm page"> <!---Argument, which is the game ID---> <cfargument name="gameID" type="numeric" required="true" hint="CFC will look for GameID and retrieve its details"> <!---Local var---> <cfset var qGameDetails = ""> <!---Database query---> <cfquery name="qGameDetails" datasource="#REQUEST.datasource#"> SELECT titles.titleName AS tName, titles.titleBrief AS tBrief, games.gameID, games.titleID, games.releaseDate AS rDate, genres.genreName AS gName, platforms.platformAbbr AS pAbbr, platforms.platformName AS pName, creviews.cReviewScore AS rScore, ratings.ratingName AS rName FROM games Inner Join platforms ON platforms.platformID = games.platformID Inner Join titles ON titles.titleID = games.titleID Inner Join genres ON genres.genreID = games.genreID Inner Join creviews ON games.gameID = creviews.gameID Inner Join ratings ON ratings.ratingID = games.ratingID WHERE (games.gameID = #ARGUMENTS.gameID#); </cfquery> <cfreturn qGameDetails> </cffunction> This function returns the following JSON: { "COLUMNS": [ "TNAME", "TBRIEF", "GAMEID", "TITLEID", "RDATE", "GNAME", "PABBR", "PNAME", "RSCORE", "RNAME" ], "DATA": [ [ "Dark Void", "Ancient gods known as 'The Watchers,' once banished from our world by superhuman Adepts, have returned with a vengeance.", 154, 54, "January, 19 2010 00:00:00", "Action & Adventure", "PS3", "Playstation 3", 3.3, "14 Anos" ] ] } The problem I'm having is every time I try to append the JSON to the layer #catalog, I get a syntax error that says "missing parenthetical." This is the JavaScript I'm using: $(document).ready(function() { $('#catalog a[href]').each(function() { $(this).qtip( { content: { url: '/gamezilla/resources/components/viewgames.cfc?method=fGameDetails', data: { gameID: $(this).attr('href').match(/gameID=([0-9]+)$/)[1] }, method: 'get' }, api: { beforeContentUpdate: function(content) { var json = eval('(' + content + ')'); content = $('<div />').append( $('<h1 />', { html: json.TNAME })); return content; } }, style: { width: 300, height: 300, padding: 0, name: 'light', tip: { corner: 'leftMiddle', size: { x: 40, y : 40 } } }, position: { corner: { target: 'rightMiddle', tooltip: 'leftMiddle' } } }); }); }); Any ideas where I'm going wrong? I tried many things for several days and I can't find the issue. Many thanks!

    Read the article

  • form_for with json return

    - by Lowgain
    I currently have a form like this: <% form_for @stem, :html => {:multipart => true} do |f| %> <%= f.file_field :sound %> <% end %> This outputs (essentially): <form method="post" id="new_stem" class="new_stem" action="/stems"> <input type="file" size="30" name="stem[sound]" id="stem_sound"> </form> However I'm planning to use jQuery's ajaxForm plugin here and would like the new stem to be returned in JSON format. I know if the form's action was "/stems.json" this would work, but is there a parameter I can put into the form_for call to ask it to return JSON? I tried doing <% form_for @stem, :html => {:multipart => true, :action => '/stems.json'} do |f| %> but this didn't appear to work.

    Read the article

  • JSON is not nested in rails view

    - by SeanGeneva
    I have a several models in a heirarchy, 1:many at each level. Each class is associated only with the class above it and the one below it, ie: L1 course, L2 unit, L3 unit layout, L4 layout fields, L5 table fields (not in code, but a sibling of layout fields) I am trying to build a JSON response of the entire hierarchy. def show @course = Course.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json do @course = Course.find(params[:id]) @units = @course.units.all @unit_layouts = UnitLayout.where(:unit_id => @units) @layout_fields = LayoutField.where(:unit_layout_id => @unit_layouts) response = {:course => @course, :units => @units, :unit_layouts => @unit_layouts, :layout_fields => @layout_fields} respond_to do |format| format.json {render :json => response } end end end end The code is bring back the correct values, but the units, unit_layouts and layout_fields are all nested at the same level under course. I would like them to be nested inside their parent.

    Read the article

  • In the JSON spec, what does "Since the first two characters of a JSON text will always be ASCII characters" mean?

    - by dan gibson
    The spec is http://www.ietf.org/rfc/rfc4627.txt?number=4627 It contains this: Encoding JSON text SHALL be encoded in Unicode. The default encoding is UTF-8. Since the first two characters of a JSON text will always be ASCII characters [RFC0020], it is possible to determine whether an octet stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking at the pattern of nulls in the first four octets. What does it mean "Since the first two characters of a JSON text will always be ASCII characters [RFC0020]"? I've looked at RFC0020 but couldn't find anything about it. JSON could be {" or { " (ie whitespace before the quote.

    Read the article

  • select2: "text is undefined" when getting json using ajax

    - by user3046715
    I'm having an issue when getting json results back to select2. My json does not return a result that has a "text" field so need to format the result so that select2 accepts "Name". This code works if the text field in the json is set to "text" but in this case, I cannot change the formatting of the json result (code outside my control). $("#e1").select2({ formatNoMatches: function(term) {return term +" does not match any items." }, ajax: { // instead of writing the function to execute the request we use Select2's convenient helper url: "localhost:1111/Items.json", dataType: 'jsonp', cache: true, quietMillis: 200, data: function (term, page) { return { q: term, // search term p: page, s: 15 }; }, results: function (data, page) { // parse the results into the format expected by Select2. var numPages = Math.ceil(data.total / 15); return {results: data.Data, numPages: numPages}; } } }); I have looked into the documentation and found some statements you can put into the results such as text: 'Name', but I am still getting "text is undefined". Thanks for any help.

    Read the article

  • How can I [simply] consume JSON Data in a Line of Business Web Application

    - by Atomiton
    I usually use JSON with jQuery to just return a string with html. However, I want to start to use Javascript objects in my code. What's the simplest way to get started using json objects on my page? Here's a sample Ajax call ( after $(document).ready( { ... }) of course: $('#btn').click(function(event) { event.preventDefault(); var out = $('#result'); $.ajax({ url: "CustomerServices.asmx/GetCustomersByInvoiceCount", success: function(msg) { // // Iterate through the json results and spit them out to a page? // }, data: "{ 'invoiceCount' : 100 }" }); }); My WebMethod: [WebMethod(Description="Gets customers with more than n invoices")] public List<Customer> GetCustomersByInvoiceCount(int? invoiceCount) { using (dbDataContext db = new dbDataContext()) { return db.Customers.Where(c => c.InvoiceCount >= invoiceCount); } } What gets returned: {"d":[{"__type":"Customer","Account":"1116317","Name":"SOME COMPANY","Address":"UNit 1 , 392 JOHN ST. ","LastTransaction":"\/Date(1268294400000)\/","HighestBalance":13922.34},{"__type":"Customer","Account":"1116318","Name":"ANOTHER COMPANY","Address":"UNIT #345 , 392 JOHN ST. ","LastTransaction":"\/Date(1265097600000)\/","HighestBalance":549.42}]} What I'd LIKE to know, is what are people generally doing with this returned json? Do you iterate through the properties and create an html table on the fly? Is there way to "bind" JSON data using a javascript version of reflection ( something like the .Net GridView Control ) Do you throw this returned data into a Javascript Object and then do something with it? An example of what I want to achieve is to have an plain ol' html page ( on a mobile device )with a list of a Salesperson's Customers. When one of those customers are clicked, the customer id gets sent to a webservice which retrieves the customer details that are relevant to a sales person. I know the SO talent pool is quite deep so I figured you all here would be able to guide in the right direction and give me a few ideas on the best way to approach this.

    Read the article

  • Serialize an object using DataContractJsonSerializer as a json array

    - by rekna
    I have a class which contains a list of items. I want to serialize an instance of this class to json using the DataContractJsonSerializer as a json array. eg. class MyClass { List<MyItem> _items; } class MyItem { public string Name {get;set;} public string Description {get;set;} } When serialized to json it should be like this : [{"Name":"one","Description":"desc1"},{"Name":"two","Description":"desc2"}]

    Read the article

  • Using a JSON web service from a Java client application

    - by user383341
    I am developing a client-side Java application that has a bit of functionality that requires getting data from some web services that transmit in JSON (some RESTful, some not). No JavaScript, no web browser, just a plain JAR file that will run locally with Swing for the GUI. This is not a new or unique problem; surely there must be some open source libraries out there that will handle the JSON data transmission over HTTP. I've already found some that will parse JSON, but I'm having trouble finding any that will handle the HTTP communication to consume the JSON web service. So far I've found Apache Axis2 apparently which might have at least part of the solution, but I don't see enough documentation for it to know if it will do what I need, or how to use it. Maybe part of the problem is that I don't have experience with web services so I'm not able to know a solution when I see it. I hope some of you can point me in the right direction. Examples would be helpful.

    Read the article

  • JSON image viewer not working in firefox

    - by jarga
    I have tried to find out why JSON is not working in Firefox all over this forum and the internet. It works on tablets, ie, safari. It works on my desktop in firefox. It only does not work after uploading I've tried a few things (commented out), such as mimeType with no solution. I have tried using the $.ajax with no better luck. Firefox had no javascript errors. I'm using jQuery 1.7. Console.log is printing out the data. $(document).ready(function(){ jQuery.support.cors = true; //$.ajaxSetup({ mimeType: "application/json" }); /*$.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"}); */ // loading pictures $.getJSON("intro.json?format=json", function(data){ var links = ''; var imageload = ''; var title = ''; console.log(data) $.each(data, function(key, item){ links += ' <a href=' + item.image + '>' + key + '</a>'; imageload += '<img src="' + item.image + ' " />'; title += item.alt; }); $('.introCon').html(imageload); $('.introCon img').hide(); $('.introCon img:last').fadeIn(500); $('.introCon img').fadeIn(1000); rotatePics(2); }); }); function rotatePics(currentPhoto) { var numberOfPhotos = $('.introCon img').length; currentPhoto = currentPhoto % numberOfPhotos; $('.introCon img').eq(currentPhoto).fadeOut( function() { // re-order the z-index $('.introCon img').each(function(i) { $(this).css( 'zIndex', ((numberOfPhotos - i) + currentPhoto) % numberOfPhotos ); }); $(this).show(); setTimeout(function() {rotatePics(++currentPhoto);}, 3000); }); } Here is the simple JSON from a separate file. { "1" : { "image" : "portfolio/chrpic.png", "alt" : "Blah.", "detail": "Quartz"}, "2" : { "image" : "portfolio/mysspic.png", "alt" : "Landing page.", "detail": "Container"}, "3" : { "image" : "portfolio/decode-pic3.png", "alt" : "Decode this.", "detail": "Landing page 2"}, "4" : { "image" : "portfolio/simple-think-pic.png", "alt" : "Simple Think", "detail": "simpilify your life"} }

    Read the article

  • How to evaluate json member using variable ?

    - by Miftah
    Hi i've got a problem evaluating json. My goal is to insert json member value to a function variable, take a look at this function func_load_session(svar){ var id = ''; $.getJSON('data/session.php?load='+svar, function(json){ eval('id = json.'+svar); }); return id; } this code i load session from php file that i've store beforehand. i store that session variable using dynamic var. <?php /* * format ?var=[nama_var]&val=[nilai_nama_var] */ $var = $_GET['var']; $val = $_GET['val']; $load = $_GET['load']; session_start(); if($var){ $_SESSION["$var"] = $val; echo "Store SESSION[\"$var\"] = '".$_SESSION["$var"]."'"; }else if($load){ echo $_SESSION["$load"]; } ?> using firebug, i get expected response but i also received error uncaught exception: Syntax error, unrecognized expression: ) pointing at this eval('id = json.'+svar); i wonder how to solve this

    Read the article

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