I'm practicing Ajax calls and am having issues accessing the returned JSON data.  I have the following code below  $('button').on('click', function() {    $.ajax({     url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&amp;filter[posts_per_page]=1',     success: function(data) {       console.log(data);     },     error: function() {       console.log('error occured');     },     cache: false   }); });   which outputs   [ { "ID": 1127, "title": "Paul Rand", "content": "&lt;p&gt;Good ideas rarely come in bunches. The designer who voluntarily presents his client with a batch of layouts does so not out prolificacy, but out of uncertainty or fear.  &lt;/p&gt;\n", "link": "https://quotesondesign.com/paul-rand-7/" } ]   I'm just trying to output the content and link properties of my JSON object. I've tried the following:  $('.message').html(JSON.stringify(data));   which outputs  [{"ID":2294,"title":"Josh Collinsworth","content":" You do not need to have a great idea before you can begin working; you need to begin working before you can have a great idea.  \n","link":"https://quotesondesign.com/josh-collinsworth-3/"}]   I'm trying to look for the standard way to manipulate JSON data, thanks for all the help!
2361
Given a string of JSON data, how can I safely turn that string into a JavaScript object?  Obviously I can do this unsafely with something like:  var obj = eval("(" + json + ')');   but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.
37551
I want to load the new entries without reloading the page. I found a great solution for: The ajax script:  &lt;script&gt;     $(document).ready(function() {     var refreshId = setInterval(function()     {         $('#content').fadeOut("fast").load('http://neocsatblog.mblx.hu/new.php').fadeIn("fast");     }, 10000);      }); &lt;/script&gt;   And the php:  &lt;?php require_once("wp-blog-header.php"); ?&gt; &lt;div id="content" &lt;?php cyberchimps_filter_content_class(); ?&gt;&gt;          &lt;?php do_action( 'cyberchimps_before_content'); ?&gt;          &lt;?php if ( have_posts() ) : ?&gt;              &lt;?php while ( have_posts() ) : the_post(); ?&gt;                  &lt;?php get_template_part( 'content', get_post_format() ); ?&gt;              &lt;?php endwhile; ?&gt;          &lt;?php elseif ( current_user_can( 'edit_posts' ) ) : ?&gt;              &lt;?php get_template_part( 'no-results', 'index' ); ?&gt;          &lt;?php endif; ?&gt;          &lt;?php do_action( 'cyberchimps_after_content'); ?&gt;      &lt;/div&gt;   However, this is a special feature that works perfectly here:  However, the main page refuses to load new entries, I do not understand the reason for this, as we use everything the same.
19020
One screenshot will explain it the best:    It shouldn't be there - appeared right after posting the comment. When reloading the page it disappears so something goes awry with the AJAX handling.  Clicking it is reloading the existing comment(s) and open the new comment text box.
16373
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?  client.js:  data = {tohex: 4919, sum: [1, 3, 5]}; // how would this script pass data to server.php and access the response?   server.php:  $tohex = ... ; // How would this be set to data.tohex? $sum = ...; // How would this be set to data.sum? // How would this be sent to client.js? array(base_convert($tohex, 16), array_sum($sum))
72968
I am attempting to create an AJAX call to pass custom taxonomy into my WP_Query but I am getting 400 (Bad Request). I believe my data array is built correctly so I am not sure what's causing it. Does anything look off here? Is there a way for me to get a more detailed error of why it is returning error 400?  $.ajax({     type:'POST',     url:ajaxUrl,     data: {         taxonomy: 'products',         slug: 'shirts'     },     beforeSend:function(xhr){      },     success:function(data){       $('#response').html(data); // insert data     } });   I console logged ajaxUrl and I am getting the correct path to admin-ajax.php so I know that's not the issue. I think it has to have something to do with data.
7083
I need to  an object to . I'm using . Is there a "standard" way to do this?  My specific situation: I have an array defined as shown below:  var countries = new Array(); countries[0] = 'ga'; countries[1] = 'cd'; ...   and I need to turn this into a string to pass to  like this:  $.ajax({     type: "POST",     url: "Concessions.aspx/GetConcessions",     data: "{'countries':['ga','cd']}", ...
109761
I have getting the below JSON on using JSON.serialize  [ {   "lname" : "Singh",   "hcpZipCode" : null,   "hcpState" : null,   "hcpEmail" : "test@test.com",   "hcpCity" : null,   "hcpAddLine1" : null,   "fname" : "Abhey",   "countryCode" : "AUS" } ]   I don't know why this '[' is coming at the begining.I don't need this '[' at the begining due to which I am getting System.JSONException: Malformed JSON: Expected '{' at the beginning of object  code     public PageReference step2() {         string JSONstr='';        List&lt;HCPRequest&gt; conWrapList = new List&lt;HCPRequest&gt;();        HCPRequest tempcontactWrapper = new HCPRequest();        tempcontactWrapper.fname='Abhey';        tempcontactWrapper.lname='Singh';        tempcontactWrapper.countryCode='AUS';        tempcontactWrapper.hcpEmail=contact.Email;         conWrapList.add(tempcontactWrapper);          JSONstr = JSON.serializePretty(conWrapList);         System.debug('\n******'+JSONstr +'\n******');          String clientId = 'xy';         String clientSecret = 'x';          //We can also store our username password in custom setting.         String username='x';//salesforce username          String password='x';//password+securitytoken         // Generating the Access Token         HttpRequest req = new HttpRequest();         req.setMethod('POST');         req.setEndpoint('https://test.salesforce.com/services/oauth2/token');// this is the OAuth endpoint where this request will be hit         req.setBody('grant_type=password&amp;client_id='+clientId+'&amp;client_secret='+clientSecret+'&amp;username='+username+'&amp;password='+password);          Http http = new Http();         HTTPResponse res = http.send(req);         String str = res.getBody();         wrapObj = (Wrapper)Json.deserialize(str,Wrapper.class);         accessToken = wrapObj.access_token;         instanceUrl = wrapObj.instance_url;          HttpRequest req1 = new HttpRequest();         string response='';         req1.setMethod('POST');         //req.setEndpoint(wrapObj.instance_url+'/services/apexrest/Account/getAccountById?name=champaKAli');         string EndPt = 'y';         string email='test@test.com';         req1.setEndpoint(EndPt);         req1.setHeader('Authorization', 'OAuth '+wrapObj.access_token);          req1.setHeader('Content-Type', 'application/json');          //req1.setBody('{"request":{"lname" : "Singh","hcpZipCode" : null,"hcpState" : null,"hcpEmail" : "test@test.com","hcpCity" : null,"hcpAddLine1" : null,"fname" : "Abhey","countryCode" : "AUS"}}');          req1.setBody('{"request":'+JSON.Serialize(conWrapList)+'}');          //req.setBody('{"request": {"countryCode": "AUS","hcpEmail" : ""+email}}');          //req.setTimeout(60000);             //req.setHeader('Content-Length', '0');         Http http1 = new Http();         HTTPResponse res1 = http1.send(req1);          System.debug('***Response***** ' + res1.getBody());         if(res1.getBody()!=null)         {             response=res1.getBody();             HCPResponse saj=(HCPResponse)JSON.deserialize(response,HCPResponse.class);           System.debug('***Response came full***** ' + saj);            System.debug('***Response came***** ' + saj.accList);             for(HCPResponseDetail s :saj.accList)            {            System.debug('***Response email***** ' + s.hcpEmail);            System.debug('***Response add2***** ' + s.hcpAddrLine2);            contact.Address1_Line2__c=s.hcpAddrLine2;            }           //return response;         //string methodcall=methodGet(JSONstr);               return Page.opptyStep2CustomReg;         }
42756
I followed the instructions and got success response but I didn't receive email.  Then I used the id to get Email Status and got 404 error.  Here is my json :  POST :   {     "To": {         "Address": "example@gmail.com",         "SubscriberKey": "example@gmail.com.tw"     },     "Options": {         "RequestType": "ASYNC"     } }   GET : {id}  Please let me know how I can resolve the issue.
2594
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, navigate to the  tag.  This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it.  I have a specific JSON structure in mind. I need to either deserialize this structure that's coming in from a web service, or I need to serialize data into this structure to transmit it to another system. How should I get started on this project in Apex?
57784
I'm working on a offline version of a website using jQuery and some xml files. I'm running in to a problem in jQuery when I do a $.ajax call on a xml file jQuery throws a error.  When I look at the error I can tell its loading the XML file because its in the error's responceText property. It seams to work just fine in Firefox.  This is how my call looks  $.ajax({     type: "GET",     url: "Modules/" + ModuleID + "/ModuleContent.xml",     dataType: "xml",     success: function(x) { xml = x; ProcessXML(); },     error: function(x) { alert(x.responceText); } });   When I run this on a web server it works just fine. Its only when I run it from the file its self when I have this problem.  Any ideas on how I can make this work in IE?  Edit: I found the answer to my problem.
100633
I have a website built on drupal with search functionality. When I search for example for "test" the link of the search is displayed like search/node/test  Is there any possibility that if I call search/node/test?json or search/node/test/json the returned page would be plain text in json format of node ids ?
80030
I'm working on a project in which I'm creating a custom post type and custom data entered via meta boxes associated with my custom post type. For whatever reason I decided to code the meta boxes in such a way that the inputs in each metabox are part of an array. For instance, I'm storing longitude and latitude:  &lt;p&gt;      &lt;label for="latitude"&gt;Latitude:&lt;/label&gt;&lt;br /&gt;      &lt;input type="text" id="latitude" name="coordinates[latitude]" class="full-width" value="" /&gt;  &lt;/p&gt;  &lt;p&gt;          &lt;label for="longitude"&gt;Longitude:&lt;/label&gt;&lt;br /&gt;      &lt;input type="text" id="longitude" name="coordinates[longitude]" class="full-width" value="" /&gt;  &lt;/p&gt;   For whatever reason, I liked the idea of having a singular postmeta entry for each metabox. On the save_post hook, I save the data like so:  update_post_meta($post_id, '_coordinates', $_POST['coordinates']);   I did this because I have three metaboxes and I like just having 3 postmeta values for each post; however, I've now realized a potential issue with this. I may want to use WP_Query to only pull out certain posts based these meta values. For instance, I may want to get all posts that have latitude values above 50. If I had this data in the database individually, perhaps using the key latitude, I would do something like:  $args = array(     'post_type' =&gt; 'my-post-type',     'meta_query' =&gt; array(         array(             'key' =&gt; 'latitude',             'value' =&gt; '50',             'compare' =&gt; '&gt;'         )     )  ); $query = new WP_Query( $args );   Since I have the latitude as part of the _coordinates postmeta, this would not work.  So, my question is, is there a way to utilize meta_query to query a serialized array like I have in this scenario?
83765
This AJAX function gets called on a click:  $.ajax({             url: 'site/ajax.php',             data: {id: $('section#single article input:last-of-type').attr('value'), cote: 'like'}         }).done(function(html) {}   It passes the ID of the post (which is contained in a hidden input) for function get_post_meta() that is located in ajax.php. This is what AJAX.php looks like:  $cote = get_post_meta($_GET['id'], 'cote', true); if($_GET['cote'] == 'like') {     $newCote = $cote++;     update_post_meta($_GET['id'], 'cote', $newCote); } else {     $newCote = $cote--;     update_post_meta($_GET['id'], 'cote', $newCote); }   It is suppose to update the custom post's "cote" field, but the problem is that function get_post_meta() is undefined in ajax.php. This is the error message:  Fatal error: Call to undefined function get_post_meta() in /home2/electro/public_html/beta... on line 2
646
For the longest time I have been using System.debug(JSON.Serialize(o)) to output objects to the debug log for troubleshooting purposes. This has worked up until my most recent project. Even existing code seems to be having this behavior.  I've tested API versions 41-45 with no luck. The actual line of code I'm using is:  system.debug(json.serialize(accountsToInsert)); // This is a map   I have also tried:  system.debug(json.serialize(accountsToInsert.get(Key)));   AND   Account test = accountsToInsert.get(Key); system.debug(json.serialize(test));   The code is called from a method defined in a VF page action attribute.  Is this just a thing that we have to live with now? Is there another way to get a  full look into the state of an object at run time?
120639
I'm trying to put search results into a div with ajax. The issue is I'm getting errors saying undefined function have_posts() when the the search template is accessed. It also took issue with get_header() which was in the search-results.php but I took it out. Here's how I have it setup.    &lt;div id="my_search"&gt;    &lt;form role="search" method="get" id="searchform" action="http://myurl.com/" &gt;     &lt;input type="text" value="" name="s" id="s" /&gt;     &lt;input type="submit" id="searchsubmit" value="Search" /&gt;    &lt;/form&gt;   &lt;/div&gt;   &lt;div id="results"&gt;&lt;/div&gt;   &lt;script type="text/javascript"&gt;     $(document).ready(function(){     $("#searchsubmit").click(function(e){      e.preventDefault();      var search_val=$("#s").val();       $.post('http://mysite.com/wp-content/themes/beta/search-results.php',{search_string:search_val},function(data){         if(data.length&gt;0){             $("#results").html(data);         }      });     });       });   &lt;/script&gt;   And here is the search-results.php template. I'm wondering if maybe I'm not passing the search results to the template.  &lt;ul&gt;  &lt;?php if (have_posts()) : while (have_posts()) : the_post();  ?&gt;   &lt;li&gt;&lt;a title="Permalink to this post" href="&lt;?php echo get_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt;   &lt;?php endwhile; endif; ?&gt;  &lt;?php if (!have_posts()) { echo('&lt;li&gt;No results to show.&lt;/li&gt;'); } ?&gt; &lt;/ul&gt;
119666
I'm making an AJAX call in drupal 7 via the standard AJAX Framework. My  problem is that when a status message is set by the AJAX callback, it is simply lost (or displayed at the next reload of the page). How can I display the status messages right after the AJAX callback has finished running, without reloading the page? Is there a module for that?
45659
After an AJAX request, sometimes my application may return an empty object, like:  var a = {};   How can I check whether that's the case?