How to use ajax in dropdown to select items, when I am working with the django framework? - ajax

I am working on a Django framework and I am very much new to both Django and Ajax. I have used a drop down list and I need to select an item from that and accordingly display its details in a table like format. Can someone help me with an Ajax code for this. Also, it would be great if you could suggest how should I build the corresponding view for it.
The code that I tried to write is something like below:
<script type="text/javascript">
$(function() {
$('#profession').change(function() {
$.ajax({
url: '/fdp/instance_creation/(\d+)',
dataType: 'json',
type: 'GET',
// This is query string i.e. country_id=123
data: {instance_id : $('#profession').val()},
success: function(data) {
if(data == null || data ==""){
}
else{
document.getElementById("mytablebody").innerHTML="";
var srno=1;
for (var i = 0; i < data.length; i++) {
var table = document.getElementsByName("tablebody")[0];
var row = document.createElement('tr');
var cell1 = document.createElement('td');
var cell2 = document.createElement('td');
var cell3 = document.createElement('td');
var cell4 = document.createElement('td');
// var cell5 = document.createElement('td');
var text1 = document.createTextNode({{forloop.counter}});
var text2 = document.createTextNode(data[i].{{workshopid}});
var text3 = document.createTextNode(data[i].{{startdate}});
var text4 = document.createTextNode(data[i].{{enddate}});
// var text5 = document.createTextNode("");
cell1.appendChild(text1);
cell2.appendChild(text2);
cell3.appendChild(text3);
cell4.appendChild(text4);
//cell5.appendChild(text5);
row.appendChild(cell1);
row.appendChild(cell2);
row.appendChild(cell3);
row.appendChild(cell4);
//row.appendChild(cell5);
table.appendChild(row);
srno++;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
I am completely new in this field so it would be nice if you could pardon me for small mistakes.

What do you want to happen with this URL?
url: '/fdp/instance_creation/(\d+)',
Do you want something to be substituted at the end? You will have to do that beforehand. Do you want this:
url: '/fdp/instance_creation/' + $('#profession').val(),
Also, what did you mean by this code:
var text1 = document.createTextNode({{forloop.counter}});
var text2 = document.createTextNode(data[i].{{workshopid}});
var text3 = document.createTextNode(data[i].{{startdate}});
var text4 = document.createTextNode(data[i].{{enddate}});
The {{}} would be filled in on the Django side as templates. It really feels like you'd at least want:
var text1 = document.createTextNode(i);
The other ones could work if they resolve to field names in the JSON.
As for a view, you just need to respond with JSON data. To test, just make a view function that returns a hard-coded string like "[{'fld': 'val', 'fld2': 'val2'}]" (I don't know your real field names, but fill them in correctly)

Related

How do I access every index of a specific Array inside an AJAX object

I'm calling an ajax for giphy, with this code:
$.ajax({
url: queryURL,
method: "GET"
}). then(function(response) {
console.log(response);
when I look at the console log there's an object with the first property being data. Each index of data is another object, inside this object are two properties i'm trying to pull, rating and url. I want to be able to list the rating and url not just of a specific index, but every index in that data array. What would be the best way to do that? Currently I've tried a for loop
for (var i = 0; i<response.data.length;i++){
var dataIndex = response.data[i];
}
then <creating a variable something like>
var imgURL = response.data[dataIndex].url
but its not working.
Here's the entire code
function displayTopicGif() {
var topic = $(this).attr("data-name");
// query url
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&limit=20&rating=r&api_key=";
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
// for loop to create a variable for the index of the objects data
for (var i = 0; i < response.data.length; i++) {
var dataIndex = response.data[i];
}
// where the gif's will be dumped
var topicDiv = $("<div class='topic'>");
// rating of gif
var rating = response.data[0].rating;
console.log(rating);
// Creating an element to have the rating displayed
var pOne = $("<p>").text("Rating: " + rating);
// add to the rating element
topicDiv.append(pOne);
// retrieve the IMG of the gif
var imgURL = response.data[0].url;
var image = $("<img>").attr("src", imgURL);
topicDiv.append(image);
// put gif into topic-view div
$("#topic-view").prepend(topicDiv);
});
}
You can check that something is an object using $.isPlainObject and then read through its properties via:
for (key in object) {
var value = object[key];
//log
}
Or you can get the keys using Object.getOwnPropertyNames();. See this sample excerpt from MDN:
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

Ignore a word in AJAX template using API

I'm using an api to create a quiz. The code that fetches the gif from the app Loopcam and then puts the loop title in the div #answer looks like this:
APP = {
refresh: function(limit, interval) {
APP.index(limit);
setInterval(function () {APP.index(limit)}, interval)
},
index: function(limit) {
var url = 'https://api.loopc.am/v1/loops/search?q=moviecharades'
$.ajax({
url: url,
dataType: "json",
success: function(data) {
var data = data
, html
, templatedata
, template = '{{#loops}}<div id="answer">{{title}}</div><div class="loop-tumbnail"><img src="{{file_url}}" {{loop_url}}/></div>{{/loops}}'
, offset = Math.round(Math.random() * (data.length - 1))
TITLE = data[0].title
console.log(offset)
if (data.length > 0) {
data = data.slice(offset, offset + limit);
templatedata = {loops: data}
html = Mustache.to_html(template, templatedata)
$('#loops').html(html)
}
}
})
What I need is the word "#moviecharades" to be deleted from the div #answer, which is always in the title that is fetched from the API. In short: if the title that is fetched is "#moviecharades big fish", I want it to only say "big fish" in the #answer-div.
I've tried to put it as a rule for the #answer-div, such as:
$("#answer").text($("#answer").text().replace("#moviecharades", ""));
But it doesn't work...
Try this:
var answerText = $("#answer").text();
$("#answer").text( answerText.replace("#moviecharades", ""));
Hope that helps.

Reploting a JQplot chart using ajax

I have been trying to solve this in different ways, but haven't make it work as expected, I feel it isn't so big deal (I really hope so) but my experience and skills with Ajax and jQuery are kind of limited that's why I am appealing to your expertise!
I am working on a chart similar to the one here http://www.jqplot.com/tests/data-renderers.php. but in my case the json file is generated depending on a value that the user choses from a select box. I am using 2 files and ajax calls to accomplish this:
-AnnualB.html is the file where the select box is located and the chart should be displayed.
-Index.php is the file where the query to the database is made (using the value obtained from the selectbox in AnnualB.html) and the json array is generated.
In AnnualB.html I use the GET method to retrieve the value from the selectbox and send it to Index.php, which generates the json data. Based on that json data the chart has to be created in AnnualB... Here is where my problem comes. The function to generate the chart is working fine and the call to send the select value and return the json is also working (have checked with Firebug), but I know am missing something (but don't know what yet) because I don't manage to pass the json data to the function that generates the chart.
My codes in AnnualB.html goes like this (abbreviating some irrelevant information with ...):
Function to generate the chart (Is working ok if the json data is passed)
function CreateGraph() {
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data; }
});
return ret; };
$.jqplot.config.enablePlugins = true;
var jsonurl = "./index.php";
var plotData = ajaxDataRenderer(jsonurl);
var series = ...
plot1 = $.jqplot('Chart1', series,{...}}
Ajax Call (PROBABLY WHERE MY MISTAKE/OMISSION IS)
function LoadGraph(int)
{
if (window.XMLHttpRequest)
{xmlhttp=new XMLHttpRequest();}
else
{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.open("GET","index.php?tasel="+int,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
CreateGraph(int)
}
}
Select box
<select name="tasel" size="1" onchange="LoadGraph(this.value)">
<option value="">Select accounts type:</option>
<option value="3">Tuloslaskelma</option>
<option value="2">Tasevastattava</option>
<option value="1">Tasevastaava</option>
</select>
The related code in Index.php goes like this (Is working ok when the value of the select box (tasel) is passed)):
$tasel = $_REQUEST['tasel'];
if ($tasel == ...2)
{...}
.
.
.
echo "[",$selite, ",";// These 2 variables create the json array
echo $finaljson, "]";
Thanks in advance for your patience and help!
I realized the answer to this question was simpler than what I was expecting.
Instead of making the whole function LoadGraph(int) ajax call, I just needed to call the tasel value ?tasel="+int in the function to generate the chart like this (which is already doing an ajax call):
function CreateGraph() {
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:'json',
success: function(data) {
ret = data;
}
});
return ret;
};
$.jqplot.config.enablePlugins = true;
var jsonurl = "./index.php?tasel="+int;
var plotData = ajaxDataRenderer(jsonurl);
var series = ...
plot1 = $.jqplot('Chart1', series,{...}
}
var plot1 = undefined;
var plotOptions = undefined;
function CreateGraph() {
$.ajax({
async: false,
url: "./index.php",
dataType:'json',
success: function(data) {
var series = fn... // Convert your json Data to array
if(plot1 != undefined)
{
plot1.destroy();
}
plot1 = $.jqplot('Chart1', series, plotOptions);
}
});
}
$(function(){
$.jqplot.config.enablePlugins = true;
plotOptions = {...}; // jqPlot options
CreateGraph();
});
Hope this might help you..

Reduce Repetitiion with AJAX JSON Calls to an API

I have about 15 copies of the following code on my site. The only things changing are the url, longitude, latitude, and the marker variable title. How can I chop this up and reduce the repetition?
$.ajax({
url: "http://api.wunderground.com/api/<api_key>/conditions/q/pws:KCASANFR128.json",
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['current_observation']['observation_location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather = parsed_json['current_observation']['weather'].toLowerCase();
var iconUrl = parsed_json['current_observation']['icon_url'];
var iconPic = new MyIcon(iconUrl);
var markerRichmond = new L.Marker(new L.LatLng(37.779806, -122.471895), {icon: iconPic});
markerRichmond.bindPopup("Current temperature in " +location+ " is: " +temp_f+ " and it is " + weather);
map.addLayer(markerRichmond);
}});
You could make a function which takes in those variables and feeds them to the ajax call. Then you would only need one copy of this ajax block, which you could call by calling the getWeather function
function getWeather(url, lat, long, title){
$.ajax({
url: url,
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['current_observation']['observation_location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather = parsed_json['current_observation']['weather'].toLowerCase();
var iconUrl = parsed_json['current_observation']['icon_url'];
var iconPic = new MyIcon(iconUrl);
var markerRichmond = new L.Marker(new L.LatLng(lat, long), {icon: iconPic});
markerRichmond.bindPopup(title);
map.addLayer(markerRichmond);
}
});
}
I am not sure if I handled the title correctly here, but you get the idea. If you give an idea of how the title may change, I can fix the code accordingly.
Hope this helps.
var current_observation = parsed_json['current_observation'];
This also shortens amount of times parsed. Then you can refer to your variable as
current_observation['observation_location']['city'];

jQuery mobile cascading dropdown list do not update properly

I'm using cascading drop down lists in my MVC application, and it works fine.
I have added the jQuery mobile library to make it look better in mobile devices browser and I have kind of bug.
An example:
if I choose first time Chevrolet it populate child drop down with Chevrolet models. - as expected
if I choose second time another make I still see the models from previous make, but if I select it I see the new model. It looks like it cashing the models from previous make.
Here is my code:
$(document).ready(function () {
$('select#Makes').change(function () {
getModels();
});
});
function getModels() {
var make = $('#Makes').val();
var myselect2 = $("select#Models");
myselect2[0].selectedIndex = 3;
myselect2.selectmenu("refresh");
$.ajax({
type: "POST",
url: "/Services/CarService.asmx/Models",
data: "{makeId: '" + make + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var models = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#Models').attr('disabled', false).removeOption(/./); //.addOption('', ' -- Select Model -- ');
var select = document.getElementById("Models");
for (var i = 0; i < models.length; i++) {
var val = models[i];
var text = models[i];
$('select#Models').addOption(val, text, true);
}
var myselect = $("select#Models");
myselect[0].selectedIndex = 3;
myselect.selectmenu("refresh");
}
});
}
#Html.DropDownList("Makes", "Please select make")
#Html.DropDownListFor(x => x.Models, new SelectList(Enumerable.Empty<SelectListItem>(), "value", "text"), "Select a Model", new { id = "Models" })

Resources