RESTful version of common Ajax request - javascript

I've used this "good old" way to fetch HTML formatted data via Ajax and inject it into the DOM.
http://localhost/ajax-controller/mobile-view/resource/1/
$mobile_view = new View('mobile-view'); // use mobile view
$mobile_view->data = $this->data_array; // add some data to view
$this->response->body($mobile_view); // return formatted HTML
http://localhost/ajax-controller/web-view/resource/1/
$web_view = new View('web-view'); // use normal web view
$web_view->data = $this->data_array; // add some data to view
$this->response->body($web_view); // return formatted HTML
Question is What is the RESTful version of this?
Should I fetch just JSON data via Ajax?
http://localhost/ajax-controller/resource/1/
$this->response->body(json_encode($this->data_array)); // return JSON data
How should I handle view / HTML formatting, another ajax request? Or am I missing something?

it is fine to have views in restful services, as determining how to return data. I would suggest passing a url parameter like
http://localhost/ajax-controller/resource/1/?view=mobile
and figuring out how to respond via that parameter

Related

Can't able to get the data using ajax in the MVC

I am using AJAX call in JS and calling a controller and action method with the url
I ran the code in my local it is working fine but when it was deployed in production the AJAX call didn't get the data and it is throwing a message in console
Could not load content for https://az416426.vo.msecnd.net/scripts/JavaScript/JavaScriptSDK/ajax/ajax.ts (HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE)
The data on local is limited but it has more data on production
I tried it by calling through AJAX and from the action method I am returning the data in the JSON format and the data i recieved is parsed and then it is sent to a hidden field it was running fine on my local all the data is there but when it was deployed on production after the page load the ajax will be called but I can't able to see the data and it shows the error which I mentioned above.
I will give you two recommendations that work better for me when dealing with passing JSON data from a controller.
First try this on your get data method:
[HttpGet]
public ContentResult Getsubscriptiondata()
{
var subdata = db.ExistingSubscriptionList.Where(substatus => substatus.OSCP_SubStatusId == "1").ToList();
return Content(JsonConvert.SerializeObject(subdata));
}
Second in your javascript change the line
document.getElementById('hdnExistingSubs').value = JSON.stringify(data)
to
document.getElementById('hdnExistingSubs').value = JSON.parse(data)
This gives me more consistent results when receiving data from the controller, hope this helps.
Clarification: I prefer this methods because passing a Json result sometimes haves quirks in the way the data is rendered on the javascript in the browser.

in Rails, How to make a query in javascript?

Given the id of an element I need to make a query in javascript, for example:
javascript:
var post_value = $(".post").val() # return a post ID;
var post = #{Post.find_by(id: post_value).to_json.html_safe};
But the post_value variable don't recognize it
If I manually pass a value to it, it recognizes it and asks me the query of the post, for example:
var post = #{Post.find_by(id: 181).to_json.html_safe}; # If work because I pass 181 as an ID value
I would be very grateful if you could help me
This line gets rendered in server side. It will not have any access to the browser's runtime context. As this gets executed before reaching the user.
var post = #{Post.find_by(id: post_value).to_json.html_safe};
Either use XHR (have another endpoint API purely for data objects like json) or query your Post object/s in controller, pass the object to the view and render the Post object inside the view. It is also a bad practice to have DB queries inside the view template files.
It's also weird to use javascript to render elements in the backend context. You generally use javascript with the context or assumption that it is to be executed in the user's side, separated with the backend context.

How to post and get javascript document into Database

I've a web page in which i've inserted a ACE- javascript Code Editor. I want to post javascript code into my database and then retrieve.
for example in case of JSON we use json.stringify and json.parse to post and retrieve data. I'm usieng SAPUI5 backend is in javascript.
var conf = model.getProperty("/automation-rule-body");
Is there any rule to post javascript code into database ?
If your backend supports REST API use create method of sap.ui.model.odata.ODataModel
var oDataModel = sap.ui.model.odata.ODataModel(sServiceUrl, mParameters);
oDataModel.create(sPath, oData, mParameters);

Calling an MVC controller action to return a view into a Wordpress website

A bit stumped... sorry if this is vague.
I have an MVC website. I wish to create a controller action that returns a value in JSON, which I can do.
For example, my MVC website will return today's weather as a string ("Today is sunny").
I wish to call this from a Wordpress website, which is where I'm stumped.
Should I modify the JSON action to create a html view, then use an iframe in the Wordpress site to show the view?
I'd rather find a way to use javascript in the wordpress website to retrieve the value as a string and insert it into the page.
How would I go about that!?
You should proceed as follows:
From your wordpress page, make a JS ajax request to your service (MVC website)
$.get(url, function(aJsonString){
....
})
Retrieve the JSON data and convert it to a JS Object:
$.get(url, function(aJsonString){
var obj = jQuery.parseJSON( aJsonString );
})
Manipulate your DOM to show the data contained in your JS Object
$.get(url, function(aJsonString){
var obj = jQuery.parseJSON( aJsonString );
$('#result').html(obj.message);
})
This can all be done with JQuery or more sophisticated libraries like Angular JS. Samples provided are in JQuery and code has not actually been tested.

Retrive post data back using javascript/jquery

I want to pass the object to the new page by using only client side script(javascript),
and I want to read the data back when the new page is loads, but I could not find any tutorial or method to get it.
function postToURL(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
The POST message sent to the server to retrieve the current page is not exposed, by the browser, to JavaScript in that page, so you cannot.
Pass the data via some other technique (such as through the URL, or localstorage).
Yeah, POST data is only handled and seen by the server side (ex. PHP). Javascript is on the client side so it will never be able to see that data unless the POST data first gets passed to server side and that server side in turn hands it off to the client side (ex. Javascript).
Consider using GET as your method in your code above so that you can pass the parameters inside the actual URL to make it accessible to the browser / client / Javascript.
parameters can be parsed from a JSON-encoded string. If you build your parameters programmically (in the previous step) like:
parameters = {};
parameters['USA'] = 'Washington DC';
parameters['UK'] = 'London';
You can create a flat JSON String representing your structured data by:
parametersString = JSON.stringify(parameters);
and end up with something like this:
"{'USA': 'Washington DC', 'UK': 'London'}"
You can store this string in a cookie, or in a query string or fragment part of the URL.
Your next page can read back this value on the following page, and re-create the structured parameters by decoding the JSON string like:
parameters = JSON.parse(parametersString);
and you're getting the original data back, on which you can run JQuery's each.

Categories

Resources