Twitter Bootstrap Dropdown AJAX call - javascript

Trying to make drop down update a graph which is build by Google Chart API.
Few issues I have right now.
It is sending request to a wrong url, instead of /graph/ it is sending data to the page it is on right now which is /services/. So i cant continue debugging it, since it doesnt even send out POST to where it is needed. /graph/(ajax.py) is the one that contains data for AJAX
I know that right now it is not passing down any data, but I wasnt able to figure out even how to access correct view. If 1 is fixed, what would be the best way to pass down value from the drop down menu of twitter bootstrap
HTML
Cred goes to this
<form id="select-graph" name="select-graph" method="POST">
{% csrf_token %}
<div class="btn-group">
<button type="submit" class="btn btn-default dropdown-toggle" data-toggle="dropdown" formmethod="POST">
Action <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a onclick="$('#select-graph').submit()">Option 1</a></li>
<li>Option 2</li>
<li class="divider"></li>
<li>About</li>
</ul>
</div>
</form>
AJAX script
Cred goes to this
<script type="text/javascript">
var graphid = 1;
$('#select-graph').submit(function() {
$.ajax({
url: 'https://www.google.com/jsapi?callback',
cache: true,
dataType: 'script',
success: function(){
google.load('visualization', '1', {packages:['corechart'], 'callback' : function(){
$.ajax({
type: "POST",
dataType: "json",
url: '/graph/',
success: function(jsondata) {
var data = google.visualization.arrayToDataTable(jsondata);
var options = {title: 'My Daily Activities'};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
})
}
})
}
})
return true
})
</script>
/graph/ - ajax.py
def insider_graphs(request):
if request.method == 'POST' :
#code that works, this json.dumps with
#special encoder works in all others parts
#of the code and charts look fine
return HttpResponse({'array':json.dumps(data, cls=SpecialEncoder)}, content_type="application/json", context_instance=RequestContext(request))
Solution
Based on accepted solution, I had to make small modification to make it work:
jsondata item that was being passed had the item I needed inside, so rather than call jsondata I needed jsondata['jsondata'], where 'jsondata' is the object name i passed down from django
new line:
var data = google.visualization.arrayToDataTable(jsondata['jsondata']);

Actualy you are firering two submits: one posts to /graph/ (ajax) and the other posts to /services/ (not ajax). The second one reloads the page.
What you need to change is prevent second submit from triggering. You can archive it by calling preventDefault() method of event in submit callbak:
$('#select-graph').submit(function(event) {
event.preventDefault();
$.ajax({
url: 'https://www.google.com/jsapi?callback',
cache: true,
/* rest of your code */
....
});
UPDATE
jsfiddle
UPDATE 2: Valid Django view returning json
return HttpResponse(
json.dumps({'array': data}, cls=SpecialEncoder),
content_type="application/json",
context_instance=RequestContext(request)
)

Related

Icon not changing in ajax success handler

I'm trying to make a function 'add to my list' in my web application.
When user clicks on an icon, this fuction should change the color of the icon after sending data to server.
It doesn't throw any errors, it sends data to server successfully, but it never changes the icon. 'console.log' inside ajax success handler is working fine, so what is the problem here?
Thanks in advance!
<div class="buttons">
<button type="button" class="btn threeButtons" onclick="request_access(this)" id="{{ elem['isbn'].split()[0] }}">
<i class="fas fa-plus"></i>
</button>
</div>
function request_access($this){
console.log("button clicked");
var request_data = $this.id;
var me = $(this);
$.ajax({
url: "/admin_add_books",
type: "POST",
data: request_data,
success: function(){
console.log("data: " + request_data)
me.find('i').addClass('green');
}
})
}
If you want to do sthg just after data is sent but response is not sent from server, then you should do sthg like:
var response = $.ajax({
url: "/admin_add_books",
type: "POST",
data: request_data
});
// Change color just after data is sent
me.children("i").addClass("green");
response.done(function(result){
// Server returned result
me.children("i").addClass("green");
});
*Note:- success is depreciated in modern version of jquery. Link

How to generate a button with its own js function?

Well I have data retrieved from ajax, I need to parse it in order to generate inputs with different <input> values. While clicking on <a> that should get near standing input value and go to ajax
<script type="text/javascript">
function proceed() {
var ID = document.getElementById('btnid').value;//probably that`s the wort way, because all of `<a>` buttons would have same id
//ajax with ID to proceed further
}
$.ajax({
async: false,
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
complete: function (res) {
for(var i = 0; i < 10; i++) {
document.getElementById('nie').innerHTML = "
<ul class=\"somec\">
<li class=\"liclass\">
</input id=\"btnid\" value=\""+res.response[i].animal+"\" class=\"thatclass\" onclick=\"proceed();\"></input>//different values
<a id="clicker" onclick="proceed()"></a>//clickable link
</li>
</ul>
";
}
});
</script>
<html>
<div id="nie">
</div>
</html>
Any help or advises for solution ?
You cannot have more than one id in a single DOM -- only one unique id is allowed. Since jQuery is used here, you can take advantages of the other methods and API it provides.
First of all, I would move the loop to success handler of $.ajax because that ensures that I have data returned from the server.
As for "appending" input and anchor pairs, use $.append. What you're currently doing is just updating #nie with the last element's data in the loop.
For events, delegate the clicks on anchors. This is better because you might continue adding more elements, so you have to go through binding them to an event.
And please, don't set async to false in $.ajax settings. This has unexpected results and makes the browser slow to point that freezes and crashes. jQuery ajax async: false causes a strange warning?
$(function(){
var $nie = $('#nie');
// Delegate the click event
$(document).on('click', '.clicker' function(){
var id = $(this).siblings('input').val();
// Use id in upcoming AJAX request.
});
$.ajax({
type: "POST",
url: "../api/",
data: {'data': "mydata"},
dataType: 'JSON',
success: function (res){
$.each(res.response, function(i, r){
$nie.appeand('<ul class="somec">\
<li class="liclass">\
<input value="'+ r.animal+ '" class="thatclass"/>\
<a class="clicker"></a>\
</li>\
</ul>');
});
}
});
});

Why JQuery post is not transferring the data?

I have a navbar defined in a html file called slick.html. I am trying to pass the id of a clicked navbar tab to the untitled.php. The untitled.php has other data in it. I am trying to isolate navbar to slick.html. I am trying to use JQuery post to transfer the data and using $_POST to access it, but I am not getting the value. I understand that it is something related to client side and server side using. The following is the code. I tried using ajax post but I didn't get any results.
slick.html(relevant parts)
<body>
<ul class="nav nav-tabs ">
<li class="active">
<a id="soilProfile" href="#tab_default_1" data-toggle="tab">
Soil Profile </a>
</li>
<li>
<a id="productivityIndex" href="#tab_default_2" data-toggle="tab">
Productivity Index </a>
</li>
<li>
<a id="Wetlands" href="#tab_default_3" data-toggle="tab">
Wetlands </a>
</li>
</ul>
//More Code
</div>
<script>
$(function () {
$('[data-toggle="popover"]').popover()
$('#soilProfile').click(function(event) {
console.log("About to post");
var data = {id : event.target.id};
console.log(data);
var request = $.ajax({
url: "untitled.php",
method: "POST",
data: { id : data },
});
console.log("AFTER POST");
});
$('#productivityIndex').click( function(event) {
var data = {id : event.target.id};
$.post( "untitled.php", data );
});
$('#wetlands').click( function(event) {
var data = {id : event.target.id};
$.post( "untitled.php", data );
});
});
</script>
</body>
untitled.php
<?php
$var = $_POST['id'];
echo var_dump($var);
// this fetches your post action
echo "this is my variable: " . $var; // this outputs the variable
?>
<html>
<body>
<object width=100% data="slick.html"></object>
<script>
$(document).ready(function(){
$('[data-toggle="popover"]').popover();
});
</script>
</body>
</html>
I don't understand why it's not working. Please inform me why or suggest me a better solution to go about this problem.
Noticed the in the ajax request you are using "untitled.php", but the page is titled "Untitled.php". Case makes a difference on Linux.
Are you sure the slick.html isn't just refreshed by the click on the anchor before the javascript is executed? Don't you need to prevent the default event?
if you say u want to pass the id that clicked.
try this and se the console.log
$('#soilProfile').click(function() {
console.log("About to post");
var data = $(this).attr("id");
console.log(data);
$.ajax({
url: "untitled.php",
type: "POST",
data: { id : data }
});
console.log("AFTER POST");
});

javascript ajax and post value is working all together why

I am having a some problem in my java script and to get the request.
This is the HTML
<form method="post" id="searchform">
<div align="center" class="col-md-10">
<input type="text" id= "contentSearch" name="contentSearch" >
</div>
<div class="form-group"><button type="submit" class="btn btn-default" id="submitSearch">
<i class="fa fa-search"></i> Search
</button></div>
</form>
<----Scenario 1 ---->
This script works fine and post the value and as ajax it never reload the page
<script>
$(document).ready(function () {
$("#submitSearch").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
// Submit data via AJAX§
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
// do i need to do something here !!
}
});
});
});
</script>
When i check the POST value i can see the value is been POST.
The Problem is when i try to get the request data from controller like ---
$post_value = $request->request->get('contentSearch');
print_r($post_value);
OUTPUT : empty
<----Scenario 2 ---->
This script have a problem i think, because it reload the page for returning the result and displaying the value ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
e.preventDefault();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}),
return false;
});
});
</script>
than i am able to get the post value like so--
$post_value = $request->request->get('contentSearch');
But the problem is in the second script the page is always loading when return the request which is not a ajax behave.
And in the first script i think because of the **e.preventDefault();** i am not getting the POST value in my controller.
Expected result ---
Option 1 : Do something so i can get the POST value in my controller
Option 2 : Fix this script so the page do not load to return the result and display
I am working on symfony framework .
Can someone please help me to fix this problem, i am really getting sick of to solve this problem.
Thanks a lot on advanced.
Like I mentioned in the comments, you need to be targeting the submit on the form. Not a click event. When targeting the click you are firing both the click and submit events, hence the reload.
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}
});
return false;
});
});

how to retrieve data from database and place it into dropdown menu using javascript

I have wrote a simple Select SQL statement that will select all the data from the database, using this data i want it to display it on my drop down menu. This is my Ajax call:
var ajReq = new XMLHttpRequest();
$(document).ready(function () {
AjaxMethod();
});
function AjaxMethod() {
ajReq.abort();
ajReq = $.ajax({
type: "POST",
url: "Services/Page.asmx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {}
});
}
This is my dropdown menu:
<div class="dropdownBox">
<div class="btn-group">
<button type="button" id="something" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Please Select you Data:
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
</ul>
</div>
</div>
so the question is that how do i get Javascript to display data into my dropdown menu, i am calling my AjaxMethod when the page is loaded.
I have edited according to the answer but i get a error of: when i click on drop down menu i get drop down of [object Object], [object Object]... error . This applies to all the drop boxes i have. When i add a breakpoint to $each(data, function(i) - i get [object object] as message but when i click on + i can see all my data from the database but when i hoverover and click on + it says: Children could not be evaluated. What does that means
If data is an array of strings, you could do something like this untested example:
success: function (data) {
var opts = '';
$.each(data, function(i){
opts += '<option>' + this + '</option>';
};
$('.dropdown-menu').html(opts);
}
Make the ajax call
In the script, query the database to get the rows with the info needed
Return the resulting array of rows in json format
Inside the callback function, decode the json encoded response into an js array using $.parseJSON function.
Empty the ul element.
Create li elements for each items in js array.
Be aware that if you like to have a event handler attached to lis, it has to be attached to the ul tag instead, like $('ul').on('click', 'li', function(){...});

Categories

Resources