I am using a JSON API plugin for wordpress to allow me to work with the sites content in a phonegap application I'm building.
However due to the complexity of some of the content on the site (caused by shortcodes outputting graphs, sliders etc..) these aren't suitable to be displayed in the mobile app. I need to remove the shortcodes from the JSON output.
I have found that I can hook into the_content filter in wordpress and use remove_shortcode to take out the necessary shortcodes. But the problem is I can only do this when I access the json url via my browser.
For example, I may use http://example.com?json=1 to return recent posts. If I type this in my url bar I can parse the url, determine that json=1 is there and strip the shortcodes.
However when I am doing an ajax (JSONP) request from my mobile application, it doesn't appear to be able to check the url for the json parameter, thus my shortcodes are not being stripped. I can't even pass in any headers either as they won't make it because of the nature of JSONP requests I believe.
Has anyone got any ideas as to how I can figure out when a JSON request from my mobile application is received, so that I can then remove the shortcodes?
Something like
if(is_json()){
//remove shortcodes
}
And before it's brought up, I have asked this on the Wordpress Stackexchange but to no avail
Update:
Here is the code I use for the ajax request from the mobile app
$.ajax({
url: "http://www.example.com/?json=1",
dataType: "jsonp",
async: true,
success: function(result) {
app.populate(result)
},
error: function(request, error) {
alert('Network error has occurred please try again!');
}
});
Prompted by one of the comments, I found what I needed in the JSON-API plugin files.
If you look in json-api/models/post.php there's a function set_content_value() which shows where the plugin is pulling in the content. Here you can modify it as needed, in my case I used it to remove certain shortcodes with the Wordpress remove_shortcode() function
Can't you just use the remove_shortcode function anytime your plugin serves content to a client?
Could you also give us the name / url of your plugin?
Maybe a bit of code woudln't hurt either. Would you mind giving use your phonegap application's API request code snippet?
Thanks.
Related
I am following https://auth0.com/blog/secure-your-react-and-redux-app-with-jwt-authentication/ at the moment, and I pretty much did the same, yet I am still getting the following error:
Is http://localhost:3001/sessions/create down? If not, what may be the cause of the error?
Thank you in advance!
EDIT
I set up my Express to port 3000 as well, just like how it is shown in the tutorial and used the same API url.
Issue could be because you are not setting a base URL in the API calls.
For example, if you are using Auth0 as a service, then API URL in requests must be as below,
axios.post('https://your.auth0.url/sessions/create', data);
(Assuming that you are using axios)
I suppose the current configuration is as below,
axios.post('/sessions/create', data);
and it takes the relative URL and it will be from the app serving the rendering of base page, in your case that is localhost:3001
It is advised to keep the base url (http://auth0.your.url) as an environment variable and can be supplied while running the app.
If you are using webpack take a look at Webpack define plugin also.
I'm trying to call a homemade vb.net web service using jQuery+Ajax and I'm struggling with the specifics.
Here's a small function exposed as a web method:
<WebMethod()> <ScriptMethod(ResponseFormat:=ResponseFormat.Xml, UseHttpGet:=True)> _
Public Function GetAllVotes() As XmlDocument
Dim theVotes = getVotes()
Dim strResult As String = theVotes.XMLSerialize
Dim doc As XmlDocument = New XmlDocument()
doc.LoadXml(strResult)
Return doc
End Function
After looking the web I've added the ScriptMethod attributes since i was returning XML but feel free to tell me i don't need them if that's the case.
Then, on the client side, this is the code :
function getVotes() {
$.support.cors = true;
$.ajax({
type: "GET",
contentType: "application/json",
url: "http://nhrd635:8008/votingmanager.asmx/GetAllVotes",
data: {},
dataType: "xml text jsonp",
success: function(msg) {
// Hide the fake progress indicator graphic.
// Insert the returned HTML into the <div>.
$('#myPlaceHolder').html(msg);
},
error: function(msg) {
$('#myPlaceHolder').html(msg);
// alert(msg);
}
});
}
I've tried many .. many variations of this code, using post or get, changing the content-type, with or without charset=utf-8. with and without double quotes on data: {}.
i use firebug to trace the output my request. only when i set dataType to jsonp do i ever get a result, but in all instances, the code ends up on the "error" function, even when status give 200 OK. but i know that setting it to jsonp is wrong since that gets my xml treated as actual javascript...
I've read very useful blog entries from a guy on encosia.
(sample: http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/)
but even following his examples i am unable to get a proper return.
am i doing something wrong that's very obvious? is it the fact that i am returning an xml string rather than a json serialized string?
With more perusing of Stack Overflow and the help of Dave Ward from Encosia, I've managed to solve my problem. I've thought I should post my final solution here, in case that helps someone in the future.
First of all, Web Services were a bad way of doing it, I went with the HttpHandler solution, as suggested by Dave Ward in reply to my original question.
Returning XML was also a poor choice, that I wasn't really aware of. I added a reference to JSon.net to my project and used it to transform my object into a Json string.
I really wanted to stick to ".net only" to transform into a json string, as suggested in Dave's blog post, but somehow I struggled to learn how to instruct .net to automatically transform into Json as in Dave's example, so i took an easy way out with Json.net to "get it working"
Then, in my HttpHandler, I had the response string follow the instructions on this post from StackOverflow:
https://stackoverflow.com/a/3703221/1060133
in my case, it was :
context.Response.Write(String.Format("{0}({1});", context.Request("callback"), jsonVotes))
The jquery call also used the instructions in the above post.
Interesting note, even in a parameter-less call, you have to send empty data like so:
$.getJSON('http://url/httpHandler.ashx?callback=?', {},
function(data) {
alert(data);
}
);
Best of luck...
I think most of your trouble here probably stems from the cross-origin request (even making a request across different ports on the same machine counts). That's why you were able to get a glimmer of it working when you switched to JSONP. Unfortunately, ASMX "ScriptServices" don't support JSONP, so the data your WebMethod returned wouldn't be a valid parameter to the JSONP callback function that jQuery injects.
The best solution, if at all possible, is to get the service running on the same domain as the page that's calling it. There are various solutions to the cross-origin problem, but none of them are as widely compatible/reliable as a simple XHR request to the same domain that the page making the request resides on.
If you can't do that, consider enabling CORS support for the site serving up votingmanager.asmx. That doesn't work in most versions of IE, but will allow cross-origin requests in other browsers. More info on how to do that here: http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
Tangentially, I'd avoid the extra XML serialization layer if possible. If getVotes() returns something like a List, use that as your return type and let ASP.NET automatically serialize the collection as JSON and then jQuery will automatically convert that to a JavaScript array in your success handler. More info about that here: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
New here. I've searched quite a bit for a working solution to my problem, but even though I have found posts with promising titles, none of the solutions have worked.
I am deploying an MVC2 web app to a client's server.
I did my development on Win2k8 Server, but they are running Win2k3 sever.
The app's only purpose is to receive some record ID information as HTTP parameters, check in the database for the status of the given record or records, and then return the status information as a simple string such as "Completed" or "Incomplete" in JSON format.
This getJSON code works fine in the development environment.
Inexplicably to me, on the client's server, the getJSON request receives a null response from the application.
There is no cross-domain action AFAIK... the result is the same from the client's server or from my machine via VPN.
In the MVC model's Json code, a common solution for people is to add the "JsonRequestBehavior.AllowGet" attribute to the Json result being returned. I did this long before trying to deploy it, and as I said, it has worked fine in the dev environment.
Using Firebug, I have watched the same request URL get sent to both my local server and the client server - the response headers from both servers are the same, but the response content from my server is shown as:
{"Result":"No Data"}
Which is what I want.
There is literally no content shown in the response from the client's server..? But the request gets an HTTP 200 code and is recorded as a success in the reponse's status attribute.
The response header content type in both situations is "application/json"
But wait, there is more!
If I manually enter the request to each server in the Firefox nav bar, and hit enter, in both cases it responds with:
{"Result":"No Data"}
Which is what I want. So why can I get the result I want from the MVC app on the client's server only when I hand-enter the request URL in Firefox, but not from the Javascript code?
I have tried forcing different output content types ... using the jQuery ajaxSetup method...
$.ajaxSetup({
async: false,
dataType: 'text'
});
or
$.ajaxSetup({
async: false,
dataType: 'html'
});
and again wtih 'script', and 'json'. I also tried the conversion options such as 'text json' or 'html json' or 'json text' and so forth.
Some of the posts I'm reading, and my gut feeling, though, suggest the problem is not the jQuery code making the request that is at fault... I don't see how the same jQuery request point to a different server running the same app would suddenly cause that server to send back a 'null' value.
By null, I want to be clear... I mean nothing is sent. There is no {} or {null} or any sign of JSON... just blank whiteness of non-existence :P
Even if nobody knows the answer, I would love some input perhaps suggesting where I should focus my sleuthing ... client or server?
If the problem is the server, it seems hard to really know that the MVC stuff is running 100% on the IIS6 server, but in general it seems to work. I have a different MVC app running on the client server which responds to the virtual paths, and generally runs the same as on dev machine.
I have found one thing ... the request headers are somewhat different? The Request Headers sent to the IIS7 setup include an "X-Requested-With: XMLHttpRequest", "referrer" , and "cookie" field/value.
I could guess that the lack of the "X-requested-with: XMLHttpRequest" in the IIS6 request headers is a clue, but I do not see then how the same javascript code pointing at a different server can generate different request headers itself. So how else are those being generated?
The javascript is embedded in an ASP.NET page, btw.
Oooh.. frustration!
Thanks for any input.
Odd Progress ... apparently there is some sort of issue with IIS6 handling the query. Although I have not payed any attention to JSONP, a post elsewhere suggested that sometimes use the "&callback=?" parameter at the end of a .getJSON request URL would force it into GET mode and that worked frequently for problems getting data from the server. So I did that... and it did work, sort of. The proper {"Result":"No Data"} was returned in response to the request... which seems good. However, the way that the JSONP callback works, it generates its own script to do the calling and fetching and interpreting of the incoming JSON. In this case, it interprets the JSON to need a label which it does not have, thus an error is thrown "invalid label" ... there must be some way to hack things to just deliver the JSON, but the whole required use of JSONP callbacks suggests that the server configuration is wrong, right? Or why does it work without JSONP for IIS7 and not IIS6?
Despite my not liking the callback JSONP solution, it appears to work ok. The error is still returned about an invalid label, but that does not appear to stop the remaining javascript from running... and so the application is working with IIS6 now. I have not tested the fix of using the callbacks and JSONP against IIS7 yet, but I expect it will work well enough.
Here is a link to the discussion that lead me to my current solution. I do still hope to find a more elegant solution, however.
NeoWin.net
Are you certain that your App Extension Mappings are set up correct?
Follow this article for running MVC2 on IIS6 and ensure all the different configurations have been done, that's probably the first step before going further and investigating specifics.
I'm really inclined to believe it's related to HTTP Verbs.
Not a great title but I'm looking more for some guidance, have searched quite a bit. I'm building a web app with an MVC framework (but I think this is a more generic question). I'm trying to make many views that do a lot of AJAX style calls and say I have a site with users and they can add folders and files to their profile page. So the URL maybe like:
/profile/{id}
I have a Profile controller that returns a view with various information. I'd like files and folders listed on the profile to be dynamic so I want to populate it through AJAX calls. I was thinking I would have a URL like
/listFolders/{userId}
and
/listFiles/{folderId}
Is it reasonable to have these URLs return a JSON object for these two URLs and not even provide an HTML view (since, for the browser, the view will just be the whole profile page)? Also, what should I return for errors, say if the user/folder doesn't exist or the current logged in user doesn't have access the data? Is it reasonable to just set 404 or 403 HTTP error codes or do they need to return some kind of HTML? What if there are multiple reasons for it to fail and I'd like to pass that along? Should I arbitrarily choose HTTP error codes or define integer return codes like 0, 1, 2, etc? Also, should the URL specify that they are JSON, like listFoldersJSON instead of listFolders?
I have used JSON in my previous projects. For errors, we return error codes.
We decided to do so because we were dealing with API clients. So we want to deal with error codes (REST is based on HTTP, so it was appropriate to return error codes).
Since you are writing your own application, you can pretty much choose how you want to send your errors to the view. You can create a error json object and in the view you have to check whether this object is not null.
pretty much a if-else in the view. Else you can return error codes and check for the code before rendering the JSON into whatever view you want to.
I would go with error codes, because that complies with the REST philosophy.
Generally speaking, I handle this situation by throwing a 500 internal server error with a status message. Most client libraries such as jQuery provide built in error handling with a failure callback like:
jQuery.ajax({
success:function(response){
//do some success stuff
},
error:function (xhr, ajaxOptions, thrownError){
//handle error
alert(xhr.responseText);
}
});
It's entirely feasible to return JSON objects as opposed to actual views.
As far as the url, you can use listFolders and listFiles without taking on the JSON. However, I recommend you use lower case urls for the sake of how the server is setup. For instance, I know on Apache that sometimes listFiles would be fine, but listfiles would lead to missing page exception.
With regards to errors: You could setup a header of sorts in your JSON response and use whatever system you'd like. For instance, you could do something like
status_code: 0 //where 0 means successful
status_detail:success!
Where, if the status_code is something other than 0, you'd check the status_detail and know to ignore everything else inside the response.
Also, what should I return for errors, say if the user/folder doesn't exist or the current logged in user doesn't have access the data?
These are basic HTTP Error codes:
401 : Unauthorized
404 : Not found
There's a whole slew of error messages in the HTTP spec:
HTTP Status Code Definitions
Also, should the URL specify that they are JSON, like listFoldersJSON instead of listFolders?
Generally, a good way to handle this is for the client to set the 'accepts' header to something like 'text/json' or 'text/xml' and for the server to parse it out and respond with the correct response. This way you can use the same URL but send back different views of the data (if you ever wanted)
I'm trying to deal with: "Requests made from Javascript running on your web pages must be proxied to avoid same-origin policy conflicts."
I know how to work with the JSON once I've got it. But aside from copy-pasting the JSON results via my browser, I don't know how to localize it for use.
Did you tried
$.getJSON('url', function(data){
//do smth with data
})
?
After the request is complete, data will be an object with all JSON response and you can access it as regular js object: data.something and so on.