passing an javascript object from cakephp view to controller - javascript

I am developing a website using cakephp, and I'd like to pass a javascript object in view back to the controller. I know that using a form could be easier but I need to do this customized.
So here's the object ('annotation' and 'article_id' are real column names in the database, annotation and article_id are both variables containing data):
var postdata = {
'annotation' : annotation,
'article_id' : article_id
};
What method in the view should I use? Is it .post?
And how should I program the corresponding controller to correctly receive the object and extract data from it?

You probably want to do an ajax request.

Related

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 save Json in the django database from Javascript

I will generate a json and save it in a string variable, and I need to save the whole json in my database.
I have a view
class DashboardView(TemplateView):
template_name = 'votes/dashboard.html'
in this template, I have javascript, and in this javascript I'm generating Json and saving it in a js variable, and I want to put the json in the variable into the DB.
As I'm gonna create a object for the jsons, I'll change templateview to CreateView as It's gonna save.
But how is this json going to become available for the view to be saved ?
brief instruction
using jquery ajax:
$.post( "/your/url/for/store/json/data", { jsonField: jsonData } );
in your view:
def save_json_data(request):
...
data = request.POST.get("jsonField", "")
model = YourModel(json_field=data)
model.save()
...

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.

passing JSON data and getting it back

I'm new to passing objects through AJAX, and since I am unsure of both the passing and retrieving, I am having trouble debugging.
Basically, I am making an AJAX request to a PHP controller, and echoing data out to a page. I can't be sure I'm passing my object successfully. I am getting null when printing to my page view.
This is my js:
// creating a js filters object with sub arrays for each kind
var filters = {};
// specify arrays within the object to hold the the list of elements that need filtering
// names match the input name of the checkbox group the element belongs to
filters['countries'] = ["mexico", "usa", "nigeria"];
filters['stations'] = ["station1", "station2"];
filters['subjects'] = ["math", "science"];
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// send my object to server
$.ajax({
type: 'POST',
url: '/results/search_filter',
success: function(response) {
// inject the results
$('#search_results').html(response);
},
data: JSON.stringify({filters: filters})
}); // end ajax setup
});
My PHP controller:
public function search_filter() {
// create an instance of the view
$filtered_results = View::instance('v_results_search_filter');
$filtered_results->filters = $_POST['filters'];
echo $filtered_results;
}
My PHP view:
<?php var_dump($filters);?>
Perhaps I need to use a jsondecode PHP function, but I'm not sure that my object is getting passed in the first place.
IIRC the data attribute of the $.ajax jQuery method accepts json data directly, no need to use JSON.stringify here :
data: {filters: filters}
This way, you're receiving your json data as regular key/value pairs suitable for reading in PHP through the $_POST superglobal array, as you would expect.
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
When you use ajax the page is not reloaded so the php variable isn't of use.
You may want to look for a tutorial to help. I put one at the beginning as I don't see how to format this on my tablet
you will need to json_encode your response as the tutorial shows
you may want to print to a log on the server when you are in the php function and make it world readable so you can access it via a browser
I like to use the developer tools in Chrome to see what is actually returned from the server

JSTL in javascript (get list of jbean)

I'm developing a shortned url project . And I would use a javascript function to display a pie diagram .
I want to know if it's possible to pass a list of Javabean (jst , jsp ) to a javascript function ( array , table..) ?
One efficient way to achieve this is to create a JSON structure on server side and pass it on to the client side. I suppose your chart data will be in an array or tabular format.
There are various JSON libraries available like Jackson. Refer to Jackson example.
Once you have constructed appropriate JSON object on Server side, you can refer to it on JSP by assigning the value in one line call.
<script type="text/javascript">
var jsonObj = '<c:out value="${jsonObject}"/>';
// you can refer to jsonObj in rest of the script
// including external JavaScript file
</script>
In above example jsonObject is constructed on server side in Servlet or controller etc.

Categories

Resources