json object directly from my view HTML - javascript

i'm using phonegap in order to make an application, then i'm using CodeIgniter as an API.
To get the data, i'm using a simple $.post from jQuery to a REST URL in CodeIgniter.
$.post(DIR+trad+"/format/json", function(data){
traducciones = jQuery.parseJSON(data);
}, json);
Based upon this, i got 2 questions, because i don't know if i should do it in different post methods.
The first question is, how do i get the data in json format?
The second question is, is there any way to call the json object directly from my view (HTML) ? or i need to do it using jquery or javascript?

how do i get the data in json format?
Searching for codeigniter+json gives me Output Class which has this example:
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
is there any way to call the json object directly from my view (HTML)?
Generally speaking, if you are generating the JSON yourself and you want to use it in HTML, then you will just skip generating JSON and use the data directly.
Generating JSON from a view only really becomes useful if you want to make the raw data available over a network.
If you want to fetch the data over HTTP for your view, then that is a job for the Model. See How to send a GET request from PHP?. This is useful if you have two different applications. One providing a web service for the data and one providing the user facing application.
If you want to update the page with new data after it has loaded, then this is a good usecase for JSON, but you can only do that with JavaScript (or another client side programming language).

If you want to using JSON as response format, just do like
$.post(url, {
"dataType" : "json",
"success" : function(response) {
// process your response here, it will be treated as JSON object
}
});

Related

Connecting DB and Ajax (no php)

I have to do a project as exam and I'm getting really troubled with this topic. My project is about a photoblog like Instagram. As in Instagram I want to get values from my DB and posting after the page has been loaded. So I've understood I need help from AJAX but every example I've found is about using PHP and I can't for my projects. Tools I can use are: HTML, CSS, XML, JQuery, AJAX, Servlet/JSP, DOM and JSON. I've found examples in PHP and I've tried to "translate" into Servlet/JSP but it (obviously) didn't work. This is my idea:
$.ajax({ type: "GET",
url: "Jspfile",
success : function()
{
// Here I would like to use the return value from db that I got by a servlet/jsp file
}
});
I'm using MySQL aS DB
You'll have to connect your Java applet to the database, then serialize the data from whatever object type your DB driver uses to JSON.
You then have to render the JSON in your "Jspfile" URL. Then, you just have to parse the JSON in your success / complete function in the jQuery request.

How to return JSON data from an Ajax call NO JQUERY

I am making calls to my server with Ajax. The data is returned and sent to a callback method. I want to have the response data formatted in data. How can I do this? I'm assuming it involves XML -> JSON conversion. I do not want to use the jQuery ajax method.
jQuery will not have anything to do with the process you must perform server side. Regardless of your server side technology, you will need to convert the result into the JSON format.
The process of conversion is known as "serialization"1. Use a serializer to convert your server side object into JSON format so that you may use it again when it is returned to your client side script.
1. Serialization - Wikipedia, the free encyclopedia
2 solutions :
put it in a global variable or use a callback
You cannot return a xmlhttp response (tried few days ago, used jQuery it saved my life.)

Unable to populate data from json to form in extjs 4

I have created a form panel and would like to populate json data into form.
I am sending url from tastypie.
{"EmailAddress": "aaaaa#gmail.com", "FirstName": "bbbbb", "HomePhone": "23333","resource_uri": "/api/xxxx/1/"}
Name of my form panel is formPanel.
When I am trying to run below the data is not populating by showing error.
formPanel.getForm().load({
method : 'GET',
url : '/api/xxx/1/?format=json',
});
Can any one please help me to load form.
#sreekanth, it is possible to load JSON data directly into a form (if the situation really calls for it). Take a look at the docs for Ext.form.action.Load. I'm not familiar with the tastypie API, but I suspect that the JSON response may not be exactly what ExtJS expects. From the ExtJS documentation:
Response Packet Criteria
A response packet must contain:
success property : Boolean
data property : Object
The data property contains the values of Fields to load. The
individual value object for each Field is passed to the Field's
setValue method.
All that said, #sha's suggestion is a good one: Getting familiar with the Store and Model objects in ExtJS will save you time and trouble in the long run.
I think you need read about ExtJs concepts for Stores and Models. You don't just load JSON object into ExtJs form. You actually need to create a store, load records to this store and load particular record into form.

Pass information from javascript to django app and back

So I'm trying to basically set up a webpage where a user chooses an id, the webpage then sends the id information to python, where python uses the id to query a database, and then returns the result to the webpage for display.
I'm not quite sure how to do this. I know how to use an ajax call to call the data generated by python, but I'm unsure of how to communicate the initial id information to the django app. Is it possible to say, query a url like ./app/id (IE /app/8), and then use the url information to give python the info? How would I go about editing urls.py and views.py to do that?
Thanks,
You're talking about AJAX. AJAX always requires 3 pieces (technically, just two: Javascript does double-duty).
Client (Javascript in this case) makes request
Server (Django view in this case) handles request and returns response
Client (again, Javascript) receives response and does something with it
You haven't specified a preferred framework, but you'd be insane to do AJAX without a Javascript framework of some sort, so I'm going to pick jQuery for you. The code can pretty easily be adapted to any Javascript framework:
$.getJSON('/url/to/ajax/view/', {foo: 'bar'}, function(data, jqXHR){
// do something with response
});
I'm using $.getJSON, which is a jQuery convenience method that sends a GET request to a URL and automatically parses the response as JSON, turning it into a Javascript object passed as data here. The first parameter is the URL the request will be sent to (more on that in a bit), the second parameter is a Javascript object containing data that should be sent along with the request (it can be omitted if you don't need to send any data), and the third parameter is a callback function to handle the response from the server on success. So this simple bit of code covers parts 1 and 3 listed above.
The next part is your handler, which will of course in this case be a Django view. The only requirement for the view is that it must return a JSON response:
from django.utils import simplejson
def my_ajax_view(request):
# do something
return HttpResponse(simplejson.dumps(some_data), mimetype='application/json')
Note that this view doesn't take any arguments other than the required request. This is a bit of a philosophical choice. IMHO, in true REST fashion, data should be passed with the request, not in the URL, but others can and do disagree. The ultimate choice is up to you.
Also, note that here I've used Django's simplejson library which is optimal for common Python data structures (lists, dicts, etc.). If you want to return a Django model instance or a queryset, you should use the serializers library instead.
from django.core import serializers
...
data = serializers.serialize('json', some_instance_or_queryset)
return HttpResponse(data, mimetype='application/json')
Now that you have a view, all you need to do is wire it up into Django's urlpatterns so Django will know how to route the request.
urlpatterns += patterns('',
(r'^/url/to/ajax/view/$', 'myapp.views.my_ajax_view'),
)
This is where that philosophical difference comes in. If you choose to pass data through the URL itself, you'll need to capture it in the urlpattern:
(r'^/url/to/ajax/view/(?P<some_data>[\w-]+)/$, 'myapp.views.my_ajax_view'),
Then, modify your view to accept it as an argument:
def my_ajax_view(request, some_data):
And finally, modify the Javascript AJAX method to include it in the URL:
$.getJSON('/url/to/ajax/view/'+some_data+'/', function(data, jqXHR){
If you go the route of passing the data with the request, then you need to take care to retreive it properly in the view:
def my_ajax_view(request):
some_data = request.GET.get('some_data')
if some_data is None:
return HttpResponseBadRequest()
That should give you enough to take on just about any AJAX functionality with Django. Anything else is all about how your view retrieves the data (creates it manually, queries the database, etc.) and how your Javascript callback method handles the JSON response. A few tips on that:
The data object will generally be a list, even if only one item is included. If you know there's only one item, you can just use data[0]. Otherwise, use a for loop to access each item:
form (var i=0; i<data.length; i++) {
// do something with data[i]
}
If data or data[i] is an object (AKA dictionary, hash, keyed-array, etc.), you can access the values for the keys by treating the keys as attributes, i.e.:
data[i].some_key
When dealing with JSON responses and AJAX in general, it's usually best to try it directly in a browser first so you can view the exact response and/or verify the structure of the response. To view JSON responses in your browser, you'll most likely need an exstention. JSONView (available for both Firefox and Chrome) will enable it to understand JSON and display it like a webpage. If the request is a GET, you can pass data to the URL in normal GET fashion using a querystring, i.e. http://mydomain.com/url/to/ajax/view/?some_data=foo. If it's a POST, you'll need some sort of REST test client. RESTClient is a good addon for Firefox. For Chrome you can try Postman. These are also great for learning 3rd-party APIs from Twitter, Facebook, etc.
Yes, it is possible. If you pass the id as a parameter to the view you will use inside your app, like:
def example_view (request,id)
and in urls.py, you can use something like this:
url(r'^example_view/(?P<id>\d+)/', 'App.views.example_view').
The id in the url /example_view_template/8 will get access to the result using the id which is related to the number 8. Like the 8th record of a specific table in your database, for example.
About how to capture info from ajax request/urls, Usually you can do that as in a normal django requests, check url dispatcher docs and read about django views from official docs.
About how to return response, just capture the parameters, process your request then give your response with appropriate mimitype.
Sometimes you have to serialize or convert your data to another format like json which can be processed more efficiently in a client-side/js

Request JSON object from server?

i have a JSON object in server side:
String jsonText = JSONValue.toJSONString(users);
and i want to send it to client side to be used in a javascript function, how to do that ?
I am using JSF 2 with Pure JavaScript with no other libraries.
In HTTP, the server doesnt send anything to client-side. The client-side asks for some resource using a request, and the response contains the resource.
Make the JavaScript function send an AJAX request to the server, and make the server answer with this JSON string in the response (by writing the JSON String to the response writer).
See http://api.jquery.com/jQuery.getJSON/ to get a JSON String from JavaScript. The server code is as simple as
response.getWriter().print(jsonText);
The easiest way is to let JSF print the string representation of the JSON object as a JS variable in the same view:
<script>var users = #{bean.usersAsJson};</script>
The correct way, however, is to use a fullworthy JSON web service for this. JSF is a component based MVC framework, not a JSON web service. For that the Java EE stack offers the JAX-RS API. Long answer short: Servlet vs RESTful. Use this preferably in combination with jQuery or whatever JS framework which is able to send Ajax requests and manipulate the HTML DOM tree in basically an oneliner. You only need to take into account that when used in combination with JSF, this can be used for pure presentation only.
The browser must request it, ie that string must sit somewhere in a request handling chain; set the response to that string and the browser will receive it.
I think you wanted to say response the json string.
It can be done by jQuery function getJSON.
It will get the json string and parse it inti hash, then you have to process it for your needs.
API documentation
send your json object to response and get the response in the javascript.
use eval function to evaluate json object.
var jsonObject = eval('(' + request.responseText + ')');

Categories