Search Results

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

Page 84/235 | < Previous Page | 80 81 82 83 84 85 86 87 88 89 90 91  | Next Page >

  • Create JavaScript array of function pointer, without calling it

    - by sibidiba
    I have the code below. I would like to have an array (buttons) with a single element pointing to the a function (closeFlag). <script type="text/javascript"> var closeFlag = new function() { alert('Clicked'); } var buttons = { 'OK': closeFlag } </script> However, when loading the page the alert immediately pops up. When the array is constructed, instead of using it as a pointer, JavaScript calls my function. Why? What mistake, misconception do I have?

    Read the article

  • Send a HTTP GET request to http with JSON

    - by asilloo
    Hi, I wanna create a Mashup. In this on the user will have a Text Filed that he/she can write the web link. After that the mashup will send the link to tagthe.net and list the results. How can I manage the codes. Source of API: http://www.tagthe.net/fordevelopers Thanks

    Read the article

  • How to reslove mysql_fetch_assoc(): problems!

    - by sky
    When i use the code below, im getting this error: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource when returning the data, anyone can fix it? Thanks! <?php $mysql_server_name="localhost"; $mysql_username=""; $mysql_password=""; $mysql_database=""; $conn=mysql_connect($mysql_server_name, $mysql_username, $mysql_password); ?> <?php $result = mysql_query("SELECT * FROM users"); $arrays = array(); while ($row = mysql_fetch_assoc($result)) { foreach ($row as $key => $val) { if (!array_contains_key($key)) { $arrays[$key] = array(); } $arrays[$key][] = $val; } } ?> <script type="text/javascript"> <?php foreach ($arrays as $key => $val) { print 'var ' . $key . ' = ' . json_encode($val) . ";\r\n"; } ?> </script>

    Read the article

  • jQuery and array of objects

    - by sepoto
    $(document).ready(function () { output = ""; $.ajax({ url: 'getevents.php', data: { ufirstname: 'ufirstname' }, type: 'post', success: function (output) { alert(output); var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,basicWeek,basicDay' }, editable: true, events: output }); } }); }); I have code like this and if I copy the text verbatim out of my alert box and replace events: output with events: [{ id: 1, title: 'Birthday', start: new Date(1355011200*1000), end: new Date(1355011200*1000), allDay: true, url: 'http://www.yahoo.com/'},{ id: 2, title: 'Birthday Hangover', start: new Date(1355097600*1000), end: new Date(1355097600*1000), allDay: false, url: 'http://www.yahoo.com'},{ id: 3, title: 'Sepotomus Maximus Christmas', start: new Date(1356393600*1000), end: new Date(1356393600*1000), allDay: false, url: 'http://www.yahoo.com/'},] Everything works just fine. What can I do to fix this problem? I though that using events: output would place the text in that location but it does not seem to be working. Thank you all kindly in advance for any comments or answers!

    Read the article

  • how to handle JavaScript objects with colons in key names?

    - by Ethan
    There is a syntax error in the following code: <!DOCTYPE html> <html> <body> Hello World! <script type="text/javascript"> var obj = {'a:b': '1'}; alert(obj.a:b); // syntax error </script> </body> </html> So how to handle JavaScript objects with colons in key names? I have to do this because I need to handle a feed in jsonp format from a remote server which I do not have control over, and there are colons in the key names of the returned jsonp (because the jsonp is converted from XML with namespaces in tags).

    Read the article

  • sending full form data to back end using jquery

    - by pradeep
    i have a form that is dynamically built. so the number of form elements arr not fixed. I wnat to send whole of $_POSt data from the form using jquery to back end for processing .i cant use jquery form plugin as the jquery version i am using is old. any other way ? i tied to do like this $.post('all_include_files/update_save.php',{variable:"<?php echo json_encode($_POST) ?>"},function(data) { alert(data); }) but did not work

    Read the article

  • Simple Sinatra Ajax Not Working

    - by proteantech
    I was trying make an AJAX call from a static file on my computer to a simple sinatra service. The ajax call was returning with an error and no details. The server logged no errors either. Another strange symptom was that the Origin in the request header was null. I turns out that you can't make cross domain ajax calls without a little extra effort. You can set the Access-Control-Allow-Origin header on your sinatra response to expose your service to external domains using a snippet like this: get '/hi' do response['Access-Control-Allow-Origin'] = '*' content_type 'text/plain' "Hello World" end There's also another header you can set to allow other HTTP Methods besides gets, Access-Control-Request-Method. You can find more information by searching around for CORS: Cross Origin Resource Sharing and the previously mentioned headers. Oh, and in case you want to do this in Rails as well you can do something like this in your controller: after_filter :set_access_control_headers def set_access_control_headers headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Request-Method'] = '*' end

    Read the article

  • Get next key-value pair in an object

    - by captainclam
    So, given a key, I want to find the next property in an object. Then, I want to return the value of the NEXT property. I can not rely on the keys to be ordered or sequential (they're uuids). Please see below for trivial example of what I want: var db ={ a: 1, b: 2, c: 3 } var next = function(db, key) { // ??? } next(db, 'a'); // I want 2 next(db, 'b'); // I want 3 I also want a prev() function, but I'm sure it will be the same solution. This seems like such a trivial problem but I can't for the life of me figure out how to do it. Happy for the solution to use underscore.js or be written in coffeescript :)

    Read the article

  • Best approach to developing a cross-browser javascript widget that populates from a MySQL database?

    - by MindSculpt
    I'm currently researching the best way to approach building a javascript widget someone can embed on their site, which would retrieve and display information from an external MySQL database. The gist of the widget would mimic the needs/functionality of Twitter's widget (http://twitter.com/about/resources/widgets), where it uses some combination of JS, PHP and/or AJAX and retrieves information from a MySQL DB with secure (or at least somewhat safe) cross-browser access. Thoughts or ideas on the best and most reliable way to approach something like this?

    Read the article

  • Creating a JSONRepresentation of my NSDictionary messes up the order?

    - by Lewion
    Hi all, To pass data to my webservice, I create an NSDictionary with the objects and keys I need, and use JSONRepresentation to format it nicely so I can post it to my service. It all worked fine with the previous version where only 2 parameters were required. An array with listitems, and a UDID. No I also need to pass a version number because we need to provide more data for people with the application at this new version. Only problem is when I create my JSONRepresentation now, the order of things are all messed up. NSMutableDictionary *rowDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:arrayDict,@"basketListV2",sharedData.udid,@"UDID",@"1.4",@"version",nil]; It prints out version first, then UDID and then basketListV2. Anyone know what I can do to maintain the order of my NSDict? I tried both NSDictionary and NSMutableDictionary (Probably doesn't have to do anything with it but for testing purposes I had to try it.) Thanks in advance. Lewion

    Read the article

  • Rails - Sending XML or JSON

    - by timWhit
    I'm new to Rails and trying to send a request to Chargify to cancel a subscription. Their API says I need to send the method DELETE to a xml URL. This isn't a Chargify based question but rather... how would I have a user click a button that then generates this request and sends it within my Rails app? You can view this url to see what I"m trying to do - http://docs.chargify.com/api-subscriptions#cancel. Also it's working fine when I run a command-line test so I know my code works, just now sure how to put it into my Rails app (view/controller). Thanks

    Read the article

  • Does GenerateScriptType support NonSerialized?

    - by BlueFox
    I have an object that's used both on the client and server side. GenerateScriptType(typeof(MyClass)) However, there are some fields that I don't need on the client, so my question is there any way to prevent those fields being serialized? (For example, Field2 and Field3 in MyClass) I tried marking the fields with [NonSerialized] but they still get serialized... public class MyClass { public string Field1; public string Field2 { get; set; } private string _field3; public string Field3 { get { return _field3 ?? (_field3 = "lala"); } } } Regards,

    Read the article

  • Simple iOS Get Request Not Pulling in Data

    - by user2793987
    I have a very simple get request that doesn't return data on my script. The script is fine when viewed in the web browser but the app does not pull in the data. Any other script works with this code in the app. I'm unsure of what to do because there shouldn't be a reason for this to not work. Please let me know if you need more information. Here's the script: https://shipstudent.com/complaint_desk/similarPosts.php?username=noah //retrieve saved username from user defaults (it's noah) NSUserDefaults *eUser = [NSUserDefaults standardUserDefaults]; savedUser = [eUser objectForKey:@"user"]; NSLog(@"%@",savedUser); in ViewDidLoad: NSString *categoryParam = [NSString stringWithFormat:@"https://shipstudent.com/complaint_desk/similarPosts.php?username=%@", savedUser]; NSURL *url = [NSURL URLWithString:categoryParam]; NSMutableURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0]; NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (connection==nil) { NSLog(@"Invalid request"); } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { postData = [[NSMutableData alloc]init]; NSLog(@"Response received"); } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [postData appendData:data]; NSLog(@"Data received"); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; similarPosts = [NSJSONSerialization JSONObjectWithData:postData options:kNilOptions error:nil]; [postsTbl reloadData]; for (id postObject in similarPosts) { NSLog(@"Relatable Post: %@",postObject); } }

    Read the article

  • Pulling Data out of an object in Javascript

    - by PerryCS
    I am having a problem retreiving data out of an object passed back from PHP. I've tried many different ways to access this data and none work. In Firebug I see the following... (it looks nicer in Firebug) - I tried to make this look as close to Firebug as possible results Object { data="{"formName":"form3","formData":"data goes here"}", phpLiveDebug="<...s: 198.91.215.227"} data "{"formName":"form3","formData":"data goes here"}" phpLiveDebug "<...s: 198.91.215.227" I can access phpLiveDebug no problem, but the data portion is an object. I have tried the following... success: function(results) { //$("#formName").val(results.data.formName); //$("#formName").val(results.data[0].formName); //$("#formName").val(results.data[0]); //$("#formName").val(results.data[1]); //$("#formName").val(results.data[0]["formName"]); var tmp = results.data[formName]; alert("!" + tmp + "!"); $("#formName").val(tmp); $("#jqueryPHPDebug").val(results.phpLiveDebug); } This line works in the example above... $("#jqueryPHPDebug").val(results.phpLiveDebug); but... I can't figure out how to get at the data inside the results.data portion... as you can see above, I have been trying different things and more not even listed there. I was really hoping this line would work :) var tmp = results.data[formName]; But it doesn't. So, after many days of reading, tinkering, my solution was to re-write it to return data similar to the phpLiveDebug but then I thought... it's gotta be something simple I'm overlooking... Thank you for your time. Please try and explain why my logic (my horrible attempts at trying to figure out the proper method) above is wrong if you can?

    Read the article

  • Removing a character from JSONObject?

    - by RandomlyKnighted
    My JSONObject has some random characters contained within the string so I'm trying to remove them. I've tried this but with no luck. String result = s.substring(1, s.length() - 2); JSONObject json_data = new JSONObject(result); if (json_data.has("[")) { json_data.remove("["); } if (json_data.has("]")) { json_data.remove("]"); } if (json_data.has(",")) { json_data.remove(","); } It's still not removing the characters from the JSONObject. Am I checking the JSONObject for the characters incorrectly?

    Read the article

  • How to cache on CloudFlare images that are served to client as JSON?

    - by Askar Ibragimov
    I am using a gallery on my website that gets list of images from a JSON sent by a php script. So, the javascript gallery calls PHP backend and it replies with complex JSON where images are specified as object fields. These fields not necessarily include full URLs, merely a path to needed images. I'd like to use Cloudflare and want these images to be cached there. How I could learn whether these are cached or not, and make sure that these would be cached and not considered some sort of dynamic content?

    Read the article

  • Move from JSON to Protobuf. Is it worth it?

    - by katit
    We have REST webservices that can serve XML or JSON (WCF). I'm toying with idea of implementing Protobufs. Why? PROS Less load on servers. Smaller message size - less traffic. It is easier to switch now than later. CONS Need to be implemented Going to be harder to troubleshoot/sniff messages for debugging. I can enable GZip on server and JSON will consume as much traffic What is your suggestion and/or experience on this?

    Read the article

  • how callback a function on 404 on JSON ajax request with Jquery?

    - by shingara
    I want made an Ajax request with response on JSON. So I made this Ajax request : $.ajax({ url: 'http://my_url', dataType: "json", success: function(data){ alert('success'); }, error: function(data){ alert('error'); }, complete: function(data) { alert('complete') }}) This code works good but when my url send me a HTTP code 404, no callbacks are used, even the complete callback. After research, it's because my dataType is 'json' so 404 return is HTML and the JSON parsing failed. So no callback. Have you a solution to call a callback function when a 404 is raised ? EDIT: complete callback don't call is return is 404. If you want an URL wit 404 you can call : http://twitter.com/status/user_timeline/jksqdlmjmsd.json?count=3&callback=jsonp1269278524295&_=1269278536697 it's with this URL I have my problem.

    Read the article

  • How to integrate an dynamically generated JSON Object into an other object?

    - by Marco Ciarfaglia
    How can I put this JSON Object in the function or object below? // this function generates an JSON Object dynamically $(".n_ListTitle").each(function(i, v) { var node = $(this); var nodeParent = node.parent(); var nodeText = node.text(); var nodePrice = node.siblings('.n_ListPrice'); var prodPrice = $(nodePrice).text(); var prodId = nodeParent.attr('id').replace('ric', ''); var prodTitle = nodeText; var json = { id : prodId, price : prodPrice, currency : "CHF", name : prodTitle }; return json; }); TDConf.Config = { products : [ // here should be inserted the JSON Object {id: "[product-id1]", price:"[price1]", currency:"[currency1]", name:"[product-name1]"}, {id: "[product-id2]", price:"[price2]", currency:"[currency2]", name:"[product-name2]"}, ... })], containerTagId :"..." }; If it is not understandable please ask :) Thanks in advance for helping me to figure out!

    Read the article

  • How to read the values returned by the Json?

    - by user281180
    I have the following code in my view: <% using (Ajax.BeginForm("JsonCreate", new AjaxOptions { OnComplete = "createCategoryComplete" })) { % Add new category <%=Html.TextBox("CategoryId")% <%=Html.TextBox("Test")% Name: <%= Html.TextBox("Name")% <%= Html.ValidationMessage("Name")% </p> <p> <input type="submit" value="Create" /> </p> </fieldset> </div> <% } % In the controller the code is as follows: [AcceptVerbs(HttpVerbs.Post)] public JsonResult JsonCreate(string Name) { if (ModelState.IsValid) { try { //Return a json object to the javascript return Json(new { CategoryId = 123, Test= "test successful" }); } catch { #region Log errors about the exception //Log error to administrator here #endregion } } //If we got this far, something failed, return an empty json object return Json(new { /* Empty object */ }); } What should be the code in the view for the following function to read the values returned by the Json and update the textboxes for CategoryId and Test? function createCategoryComplete() {....???}

    Read the article

  • Knockoutjs - stringify to handling observables and custom events

    - by Renso
    Goal: Once you viewmodel has been built and populated with data, at some point it goal of it all is to persist the data to the database (or some other media). Regardless of where you want to save it, your client-side viewmodel needs to be converted to a JSON string and sent back to the server. Environment considerations: jQuery 1.4.3+ Knockoutjs version 1.1.2   How to: So let’s set the stage, you are using Knockoutjs and you have a viewmodel with some Knockout dependencies. You want to make sure it is in the proper JSON format and via ajax post it to the server for persistence.   First order of business is to deal with the viewmodel (JSON) object. To most the JSON stringifier sounds familiar. The JSON stringifier converts JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. You may ask, is this the best way to do it? What about those observables and other Knockout properties that I don’t want to persist or want their actual value persisted and not their function, etc. Not sure if you were aware, but KO already has a method; ko.utils.stringifyJson() - it's mostly just a wrapper around JSON.stringify. (which is native in some browsers, and can be made available by referencing json2.js in others). What does it do that the regular stringify does not is that it automatically converts observable, dependentObservable, or observableArray to their underlying value to JSON. Hold on! There is a new feature in this version of Knockout, the ko.toJSON. It is part of the core library and it will clone the view model’s object graph, so you don’t mess it up after you have stringified  it and unwrap all its observables. It's smart enough to avoid reference cycles. Since you are using the MVVM pattern it would assume you are not trying to reference DOM nodes from your view. Wait a minute. I can already see this info on the http://knockoutjs.com/examples/contactsEditor.html website, why mention it all here? First of this is a much nicer blog, no orange ? At this time, you may want to have a look at the blog and see what I am talking about. See the save event, how they stringify the view model’s contacts only? That’s cool but what if your view model is a representation of your object you want to persist, meaning it has no property that represents the json object you want to persist, it is the view model itself. The example in http://knockoutjs.com/examples/contactsEditor.html assumes you have a list of contacts you may want to persist. In the example here, you want to persist the view model itself. The viewmodel here looks something like this:     var myViewmodel = {         accountName: ko.observable(""),         accountType: ko.observable("Active")     };     myViewmodel.isItActive = ko.dependentObservable(function () {         return myViewmodel.accountType() == "Active";     });     myViewmodel.clickToSaveMe = function() {         SaveTheAccount();     }; Here is the function in charge of saving the account: Function SaveTheAccount() {     $.ajax({         data: ko.toJSON(viewmodel),         url: $('#ajaxSaveAccountUrl').val(),         type: "POST",         dataType: "json",         async: false,         success: function (result) {             if (result && result.Success == true) {                 $('#accountMessage').html('<span class="fadeMyContainerSlowly">The account has been saved</span>').show();                 FadeContainerAwaySlowly();             }         },         error: function (xmlHttpRequest, textStatus, errorThrown) {             alert('An error occurred: ' + errorThrown);         }     }); //ajax }; Try run this and your browser will eventually freeze up or crash. Firebug will tell you that you have a repetitive call to the first function call in your model that keeps firing infinitely.  What is happening is that Knockout serializes the view model to a JSON string by traversing the object graph and firing off the functions, again-and-again. Not sure why it does that, but it does. So what is the work around: Nullify your function calls and then post it:         var lightweightModel = viewmodel.clickToSaveMe = null;         data: ko.toJSON(lightweightModel), So then I traced the JSON string on the server and found it having issues with primitive types. C#, by the way. So I changed ko.toJSON(model) to ko.toJS(model), and that solved my problem. Of course you could just create a property on the viewmodel for the account itself, so you only have to serialize the property and not the entire viewmodel. If that is an option then that would be the way to go. If your view model contains other properties in the view model that you also want to post then that would not be an option and then you’ll know what to watch out for. Hope this helps.

    Read the article

  • JSON: Jackson stream parser - is it really worth it?

    - by synic
    I'm making pretty heavy use of JSON parsing in an app I'm writing. Most of what I have done is already implemented using Android's built in JSONObject library (is it json-lib?). JSONObject appears to create instances of absolutely everything in the JSON string... even if I don't end up using all of them. My app currently runs pretty well, even on a G1. My question is this: are the speed and memory benefits from using a stream parser like Jackson worth all the trouble? By trouble, I mean this: As far as I can tell, there are three downsides to using Jackson instead of the built in library: Dependency on an external library. This makes your .apk bigger in the end. Not a huge deal. Your app is more fragile. Since the parsing is not done automatically, it is more vulnerable to changes in the JSON text that it's parsing. I'm extremely worried that malformed JSON will result in infinite loops (as pull parsing requires a lot of while loops). Writing code to parse JSON via a stream parser is ugly and tedious.

    Read the article

  • What is the proper way to URL encode Unicode characters?

    - by Josh Gibson
    I know of the non-standard %uxxxx scheme but that doesn't seem like a wise choice since the scheme has been rejected by the W3C. Some interesting examples: The heart character. If I type this into my browser: http://www.google.com/search?q=? Then copy and paste it, I see this URL http://www.google.com/search?q=%E2%99%A5 which makes it seem like Firefox (or Safari) is doing this. urllib.quote_plus(x.encode("latin-1")) '%E2%99%A5' which makes sense, except for things that can't be encoded in Latin-1, like the triple dot character. … If I type the URL http://www.google.com/search?q=… into my browser then copy and paste, I get http://www.google.com/search?q=%E2%80%A6 back. Which seems to be the result of doing urllib.quote_plus(x.encode("utf-8")) which makes sense since … can't be encoded with Latin-1. But then its not clear to me how the browser knows whether to decode with UTF-8 or Latin-1. Since this seems to be ambiguous: In [67]: u"…".encode('utf-8').decode('latin-1') Out[67]: u'\xc3\xa2\xc2\x80\xc2\xa6' works, so I don't know how the browser figures out whether to decode that with UTF-8 or Latin-1. What's the right thing to be doing with the special characters I need to deal with?

    Read the article

  • Why isn't this json/jquery function returning 10 results and why does it return 0 sometimes?

    - by Scarface
    Hey guys, quick question. I have a json function returning results from a php query but it is not working out because it seems to keep executing the query until all results are returned and sometimes returns 0 results (if I keep refreshing page, it returns 0 results sometimes). I want to limit results returned to 10 so I was wondering if anyone could point out the error of my code. Would really appreciate it. PS I am positive the query is returning the correct results and only 10 on its own. It just seems to be this one function that is not working out. SELECT time, user, comment FROM comments WHERE topic_id='$topic_id' ORDER BY time DESC LIMIT 10 var count=0; function prepare(response) { count++; var string = '<li class="list" id="list-'+count+'">' +'</li>'; return string; } $.getJSON(files+"comments.php?action=view&load=initial&topic_id="+topic_id+"&t=" + (new Date()), function(json) { if(json.length) { for(i=0; i < json.length; i++) { $('#shoutbox-list').prepend(prepare(json[i])); $('#list-' + count).fadeIn(1500); } var j = i-1; lastTime = json[j].time; } });

    Read the article

< Previous Page | 80 81 82 83 84 85 86 87 88 89 90 91  | Next Page >