I am new to Ajax and want to make an Ajax Request to a view function in Django with jQuery, but I am stuck.
I started with a simple example to check if it works
var button = $('.any_button');
$(button).click(function() {
var button_value = $(this).val();
$.ajax({
type: "POST",
url: "/url-path/to-my/view-function/",
dataType: "json",
data: { "button_value": button_value },
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
});
I have inserted from https://docs.djangoproject.com/en/1.11/ref/csrf/
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
my view function:
from django.http import JsonResponse
def button_check(request):
data = {"message": "Message"}
return JsonResponse(data)
My url path refers to views.button_check
I get the beforeSend alert and the error alert, but I expect the success alert
What did I miss? Unfortunately I am not able to go ahead.
in jquery try like this,
$.ajax({
type: "POST",
url: "/button_check/",
method: "POST",
data: { "button_value": button_value },
contentType: "application/json",
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
url should be,
url(r'button_check/', 'views.button_check'),
if your request is "POST" or specific try,
def button_check(request):
if request.method == "POST":
data = {"message": "Message"}
return JsonResponse(data)
Your ajax setup is overwritten by values you pass to jQuery.ajax:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
//this will never happen because it is overridden later
alert("you will never see this.");
}
});
$.ajax({
type: "GET",
url: "/index.html",
beforeSend: function () {
console.log("another before send");
},
})
.then(x => console.log("success:",x))
.then(undefined,reject => console.error(reject));
This means you won't authenticate and get the csrf token missing.
As you told in comments; remove the boforesend in $.ajax
Related
So I am trying to create some basic search functionality to my Django project using Ajax. However, I keep getting an error about the CSRF token. Here is the javascript in my template:
<script type='text/javascript'>
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$('#search').keyup(function () {
var search_text = $(this).val();
console.log(search_text);
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text': search_text,
},
success: function (data) {
console.log('it worked');
},
});
});
</script>
Any ideas why this isn't working?
Try putting it in $(document).ready(function(){})
So like this:
$(document).ready(function(){
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$('#search').keyup(function () {
var search_text = $(this).val();
console.log(search_text);
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text': search_text,
},
success: function (data) {
console.log('it worked');
},
});
});
)}
I have a basic ajax function
setInterval(function() {
var action = '';
var status = '';
$('#php-data').load('../Data/Dashboard.Data.php');
$.ajax({type: 'POST', url: 'Data/Dashboard.Image.php', data: { json: action }, dataType: 'json' }).done(function(data) {
console.log('Ajax Data: ' + data);
status = JSON.parse(data);
**if(status === 'false') {**
console.log("script is NOT running");
drawPieChart();
} else {
console.log("script is running");
$('#php-image').load('../Data/Dashboard.Image.php'); //todo only load this is the ajax returned from Dashboard.image.php is true
}
});
}, 5000);
basically the only thing my ajax returns is "false" so when I compare status to false it should be true and drawPieChart(); but instead it always runs the jquery load() function even though my ajax data is returning false every single time.
ive also tried this:
setInterval(function() {
var action = '';
var status = '';
$('#php-data').load('../Data/Dashboard.Data.php');
$.ajax({type: 'POST', url: 'Data/Dashboard.Image.php', data: { json: action }, dataType: 'json' }).done(function(data) {
console.log('Ajax Data: ' + data);
status = data;
**if(status === 'false') {**
console.log("script is NOT running");
drawPieChart();
} else {
console.log("script is running");
$('#php-image').load('../Data/Dashboard.Image.php'); //todo only load this is the ajax returned from Dashboard.image.php is true
}
});
}, 5000);
and this :
setInterval(function() {
var action = '';
$('#php-data').load('../Data/Dashboard.Data.php');
$.ajax({type: 'POST', url: 'Data/Dashboard.Image.php', data: { json: action }, dataType: 'json' }).done(function(data) {
console.log('Ajax Data: ' + data);
**if(data == 'false') {**
console.log("script is NOT running");
drawPieChart();
} else {
console.log("script is running");
$('#php-image').load('../Data/Dashboard.Image.php'); //todo only load this is the ajax returned from Dashboard.image.php is true
}
});
}, 5000);
if(status === 'false')
This suggests a string. use this instead:
if(status == false)
you could simplify it even further like so:
if(!status)
i'm trying to make infinite scrolling so when scrolling i make an ajax request to the server to get data but when scrolling a multiple ajax request is made and return the same data so how can i cancel ajax request before sending if there one already exist i tried like this
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
all my code
var lock_load = '1';
var activeAjaxConnections = 1;
var PageNumber = 2;
$(window).scroll(function () {
if ((Math.ceil($(window).scrollTop() - $(window).height()) * -1) <= getHeight() + 550) {
if (lock_load === '1') {
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
alert(errorThrown);
n }
});
}
}
});
but it give an error xhr is undefined pleas any help and many thanks in advance.
Try flags
Before making ajax call set flag to true and after ajax call is made set flag to false, finally on completion of ajax request again set flag to ture
var ready = true;
$(window).scroll(function(){
if(ready == true){
ready = false;
$.ajax({
url: "/pagination",
cache: false,
success: function (response){
//response
}
}).always(function () {
ready = true; //Reset the flag here
});
}
});
use the below code, use a simple flag variable that will be set to false by the defualt, that is to say that ajax call is not occuring once if condition is met then it will set to true to say that ajax call has started, once the success: or error: call back fires the variable will be set to false so that another ajax call can be made.
startedAjax = false;
if (lock_load === '1') {
startedAjax = true;
var xhr = $.ajax({
type: "POST",
async: true,
dataType: "json",
url: ajaxurl,
data: ({
beforeSend: function (xhr) {
if (activeAjaxConnections != 1) {
xhr.abort();
}
activeAjaxConnections++;
//Show Loader....
$("#Ajax-Load-Image").css('visibility', 'visible');
},
type: "POST",
action: 'Ajax_Get_SpacesAndSponsors',
Page: PageNumber
}),
success: function (response) {
startedAjax = false //set is false
PageNumber++;
var Message = response.spaces.Message;
console.log(response);
console.log(Message);
Draw_SpacesAndSponsor(response);
lock_load = response.spaces.Lock_load;
activeAjaxConnections--;
},
error: function (errorThrown) {
startedAjax = false;
alert(errorThrown);
}
});
}
}
});
In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});
From the below javascript code i am trying to call a serverside method, but serververside method is not getting called. I am using jquery, ajax
<script type="text/javascript" src="JquryLib.js"></script>
<script type="text/javascript" language="javascript">
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var v1 = 'StateId: ' + StateId;
$.ajax(
{
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: '{' + v1 + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
</script>
This is my serverside method which i need to call.
private static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
It is giving me the following error: 500 (Internal Server Error)
I cannot figure out what is wrong. please help!
Stack Trace:
[ArgumentException: Unknown web method PopulateCities.Parameter name: methodName]
use this script:
function fnPopulateCities() {
debugger;
var State = $("#ddlState").val();
GetCities(State);
return false;
}
function GetCities(StateId) {
debugger;
var data = {
'StateId': StateId
};
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: JSON.stringify(data), // using from JSON.stringify is much better than to try stringify data manually
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and this code for your code behind:
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}
Use this script
function GetCities(StateId) {
debugger;
var v1 = "{'StateId': '" + StateId+"'}";
$.ajax({
type: "POST",
url: 'DropDownList_Cascade.aspx/PopulateCities',
data: v1,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result.status === "OK") {
alert('Success!!');
}
else {
fnDisplayCities(result);
}
},
error: function (req, status, error) {
alert("Sorry! Not able to retrieve cities");
}
});
}
and modify Code Behind
[System.Web.Services.WebMethod]
public static ArrayList PopulateCities(int StateId)
{
//this code returns Cities ArrayList from database.
}