How to pass value from django templated html to ajax - html

I have been hacking away at this for too long, as I'm painstakingly introducing ajax to speed my django app. I have no prior experience so. I have a dropdown list that I'm using as a notification viewer and using the {%for loop%} to populate. They all share the same id but unique names - their record ids. I'm trying to click the notification and then load the corresponding records by passing's it's ID to my views.py file. Below is code for my hackish attempt which has failed to be fruitful and taken way to much time.
<script>
function openNotification(){
$('#ntfy').click(function(e) {
var acc = $(this).attr('name');
$.ajax({
type: "GET",
url: "{% url 'my_app:notifications' %}",
dataType: "json",
async: true,
data:{csrfmiddlewaretoken :'{{ csrf_token }}',
'acc':acc},
success: function(){
alert("yo yoyo");
if (data.status == "success"){
window.location.href = data.url;
}
else{
alert("error occured");
}
}
});
});
}
</script>
And the html looks like this.
<a href="#" onclick="openNotification()" name="{{alert.1.docnum}}_{{alert.0.accountid}}" id="#ntfy">
Please assist.

<a href="#" data-docnum="{{alert.1.docnum}}" data-accountid="{{alert.0.accountid}}" class="ntfy">
===========================================
<script>
$('.ntfy').on('click',function(e) {
var docnum = $(this).attr('data-docnum'); // or $(this).data('docnum')
var accountid = $(this).attr('data-accountid'); // or $(this).data('accountid')
data = {
"csrfmiddlewaretoken":$("input[name='csrfmiddlewaretoken']").val(),
"docnum":docnum,
"accountid":accountid
}
$.ajax({
type: "GET",
url: "{% url 'rznbldbt_app:notifications' %}",
dataType: "json",
async: true,
data:data,
success: function(data){
alert("yo yoyo");
if (data.status == "success"){
window.location.href = data.url;
}
else{
alert("error occured");
}
}
});
});
</script>
Another way is :
<a href="#" onclick="openNotification({{alert.1.docnum}},{{alert.0.accountid}});">
===========================================
<script>
function openNotification(docnum,accountid)
{
data = {
"csrfmiddlewaretoken":$("input[name='csrfmiddlewaretoken']").val(),
"docnum":docnum,
"accountid":accountid
}
$.ajax({
type: "GET",
url: "{% url 'rznbldbt_app:notifications' %}",
dataType: "json",
async: true,
data:data,
success: function(data){
alert("yo yoyo");
if (data.status == "success"){
window.location.href = data.url;
}
else{
alert("error occured");
}
}
});
}
</script>

Related

Display Json data with ajax in codeignitor 4

My JSON data is available in browser console. But i cannot display data in template.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '<?php echo_uri("clients/session_details") ?>',
type: 'GET',
dataType: 'json',
success: function(response) {
var data = JSON.parse(response);
$("#result").html(data[0].rx-byte);
}
});
});
</script>
Based on the JSON data you provided, it seems like you are trying to display the rx-byte value in the HTML template. Here's a code sample that will do that:
$(document).ready(function () {
$.ajax({
url: '<?php echo_uri("clients/session_details") ?>',
type: 'GET',
dataType: 'json',
success: function (response) {
$("#result").html(response[0]["rx-byte"]);
}
});
});

Website Redirect Code Error, how do I fix it?

Can anyone see why this script would fail to redirect?
$.ajax({
url: url,
data: JSON.stringify(viewModel),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
type: "POST",
success: function (result) {
if (result.success === true) {
showFullScreenLoadMask(false);
//var redirect = "/Login/Index";
//window.location.href = getUrlPath() + redirect;
var redirecturl = getUrlPath() + "/Login/Index";
/*F5_*/ F5_Deflate_location( /*_5F##*/ window /*F5_*/ ) /*_5F#.location#*/ .assign = redirecturl;
} else {
// hide any previous errors
$("#divPasswordHistoryError").hide();
$("#divFullNameError").hide();
$("#divCurrentPasswordError").hide();
if (result.vm.ShowPreviousPasswordFail === true) {
$("#divPasswordHistoryError").show();
$("#divPasswordHistoryError").removeClass("hidden");
}
if (result.vm.ShowFullNameError === true) {
$("#divFullNameError").show();
$("#divFullNameError").removeClass("hidden");
}
if (result.vm.ShowCurrentPasswordFail === true) {
$("#divCurrentPasswordError").show();
$("#divCurrentPasswordError").removeClass("hidden");
}
$("#Username").val(result.vm.Username);
$("#Password").val(result.vm.Password);
$("#NewPassword").val("");
}
},
error: function (responseText, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
Above is the code I have on my login script, but for the life of me, I cant get my head around as to why it would not be redirecting to the correct page after someone enters their password.

how to pass primary key value from JsonResponse to dynamic url in Django?

I face the problem to pass primary key value to the dynamic url using Ajax in Django. Thanks for any helps...
below is the JS code for click button's function:
$(function () {
$(".js-create-book").click(function () {
$.ajax({
url: '/supplier/**<int:pk>**/new/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});
the views.py got the function new_stok() as follows:
def new_stok(request, pk):
supplier = get_object_or_404(Supplier, pk=pk)
form = NewStokForm()
context = {'pk': supplier.pk, 'form': form}
html_form = render_to_string('includes/partial_stok_create.html',
context,
request=request,
)
return JsonResponse({'html_form': html_form})
You can use HTML5 data attributes:
<button class="js-create-book" data-id="{{ supplier.pk }}">Add new</button>
Then in javascript retrieve the attribute:
$(function () {
$(".js-create-book").click(function () {
var data_id = $(this).attr("data-id");
$.ajax({
url: '/supplier/' + data_id + '/new/',
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal-book").modal("show");
},
success: function (data) {
$("#modal-book .modal-content").html(data.html_form);
}
});
});
});

Passing Json from Controller to View

I have a database of movies, and I am looking to create a Json, and then access that json in my view. I have successfully created the json within the controller using the following code:
var movies = from m in db.Movies
select m;
string jsonData = JsonConvert.SerializeObject(movies);
This creates a json, which I have passed to the Console via writeline, and it generates the following JSON:
[{"ID":1,"Title":"When Harry Met Sally","ReleaseDate":"1989-01-11T00:00:00","Genre":"Romantic Comedy","Price":7.99,"Rating":"PG","Review":79.90},
{"ID":2,"Title":"Ghostbusters ","ReleaseDate":"1984-03-13T00:00:00","Genre":"Comedy","Price":8.99,"Rating":"PG","Review":94.90},
{"ID":3,"Title":"Ghostbusters 2","ReleaseDate":"1986-02-23T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"15","Review":89.90},
{"ID":4,"Title":"Rio Bravo","ReleaseDate":"1959-04-15T00:00:00","Genre":"Western","Price":3.99,"Rating":"U","Review":91.90},
{"ID":5,"Title":"The Hangover","ReleaseDate":"2008-01-01T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"18","Review":83.80},
{"ID":6,"Title":"Test","ReleaseDate":"2013-06-01T00:00:00","Genre":"Action","Price":10.00,"Rating":"18","Review":89.00}]
I then want to access that json in my view, and print it to my view. I have tried the following Ajax code, but I can't seem to get the json data to display.
<button id="test">Test</button>
<div class="inner"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" + jsonData + "</p>");
});
});
});
});
</script>
Any ideas? What am I doing wrong?
if we are talking about ASP.NET MVC then you can do this:
action code:
[HttpGet]
public JsonResult Index(int? PageId)
{
//other your code goes here
var movies = from m in db.Movies
select m;
return Json(new {result = movies}),JsonRequestBehavior.AllowGet);
}
client code:
$.ajax({
type: "GET",
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
content: "application/json",
cache : false
}).done(function (serverdata) {
if(result.result.length > 0)
{
$.each(result.result, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
}
else
{
alert("No movies in result");
}
}).fail(function (jqXHR, textStatus) {
alert("Internal server error." + "\n" + jqXHR.statusText );
});
try: -
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
method: 'GET',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
var jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
});
});
});
</script>

HTTP GET not getting

Trying this but getting nothig
function getWeather() {
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
On clicking button it should return the JSON
<body>
<button onclick="getWeather();">Get Weather</button>
</body>
Expected example JSON:
{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5168,"message":0.0287,"country":"GB","sunrise":1415603442,"sunset":1415636293},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":284.99,"pressure":1003,"humidity":76,"temp_min":283.75,"temp_max":286.15},"wind":{"speed":5.1,"deg":210},"clouds":{"all":75},"dt":1415624678,"id":2643743,"name":"London","cod":200}
I am not getting the mistake I have done.
EDIT
Tried with this from snippets given here:
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script language="javascript" type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
//alert(JSON.stringify(data));
data_Json = data;
//alert("Weather Report: "+data_Json);
},
error: function(e) {
alert(e.message);
}
});
return data_Json;
}
function temp() {
//getWeather();
var obj = JSON.stringify(getWeather());
//alert("Got"+JSON.stringify(obj));
//alert(JSON.stringify(getWeather()));
//document.getElementById("temp").innerHTML = obj.main.temp;
alert("Temp : "+obj);
}
</script>
</body>
<body>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
</html>
It returned {}
Not returned the JSON (the return defined in getWeather)
Not the temperature (in get element by id part)
Remove contentType from your request and it will work fine.
Since this is a cross origin request, you cannot set contentType.
Following is the error you will see in your console -
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/weather?q=London. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
Also the statement return data; will fail as variable data is not available in that context.
You can use the below code for your purpose -
function getWeather() {
weatherJson = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
weatherJson = data;
},
error: function(e) {
alert(e.message);
}
});
return weatherJson;
}
You can try this solution
function getWeather() {
data_Json = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
dataType: 'JSONP',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
data_Json = data;
},
error: function(e) {
alert(e.message);
}
});
return data_Json; }
For Edit Part:-
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function (data) {
data_Json = JSON.stringify(data);
},
error: function (e) {
alert(e.message);
}
});
alert(data_Json);
return data_Json;
}
function temp() {
var obj = getWeather();
alert("Temp : " +obj);
}
</script>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
Hi See this,
function getWeather() {
var returnData="";
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
returnData=data;
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
Do you actually have an element with id="jsonp-results" in your html?
Some hints to simplify:
You don't need to specify a jsonp callback if you are not using jsonp
Synchronous calls are not nice because they block, you should avoid that and they aren't even supported for cross-domain calls (which your case is)
Simplified example:
function getWeather() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e) {
alert(e.message);
}
});
}
<body>
<button onclick="getWeather();">Get Weather</button>
<div id="jsonp-results"></div>
</body>
After your comment: It certainly works:
http://codepen.io/anon/pen/MYgXzd
You must have something wrong in your setup.