Pass an ID from Ajax to a Django view - django

I have a Django view that accepts an ID and returns a Json Response. Now on Ajax, I want to call the django view with an ID.
Here is my AJAX:
$(document).ready(function () {
$("#button").click(function () {
var id = 25;
$.ajax({
type: "POST", # Added here. Now error message changed
url: "/account/check_id/"
data: {
id: id,
},
dataType: "json",
success: function (data) {
if (data.is_taken) {
alert("ID is available");
}
},
});
});
});
Additional Data:
url:
path('check_id/<int:id>/', hrViews.check_id, name='check_id'),
view:
def check_id(request, id, *args, **kwargs):
However, when I click on button, I get error message
GET http://localhost:8000/account/check_id/?id=25 404 (Not Found). The ?id= is causing the error. How to remove it?
EDIT
After adding type: "POST", got message
POST http://localhost:8000/account/check_id/
How to pass ID here?
Note. Based on w3schools, the data{} is used to pass information to server. So I think that I should pass my ID here. However, my url does not get the ID from data. Please correct me on this if my assumption is wrong.

So I made some changes and this is what worked for me.
$(document).ready(function () {
$("#hold").click(function () {
var id = 25;
$.ajax({
url: "/account/check_id/" + id,
dataType: "json",
success: function (data) {
if (data.is_taken) {
alert("ID is available");
}
},
});
});
});
Removed the type: "POST", then concatinate on URL with my ID. It works so I will go with this based on my use case.

Related

Prevent page refresh when submitting Django form

Is there any way to stop refreshing of the form page after hitting submit button?
I am looking for doing this in front end using javascript.
Yes it's possible. jQuery Ajax is good idea
$(document).ready(function(){
$("#submit").on("click", function(){
var form = $("#form").serialize();
$.ajax({
type:"POST",
url:"{% url 'url to view' %}",
data: form,
success:function(data){
// Something success
},
error:function(data){
//When error occurred
},
});
});
});
I was able to achieve this by the following:
var formImage = $("#form_image");
formImage.submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (msg, status, jqXHR) {
console.log(msg);
console.log(status);
console.log(jqXHR);
},
cache: false,
contentType: false,
processData: false
});
});

Get data from one site collection into another site collection in same web application sharepoint 2016

I am using SharePoint 2016 on premise. I am having one web application in which i am having 2 site collections.
site 1 and site 2.
I want to show data from site collection 1 list on site collection 2 Page, using rest or java script or J query. My environment is not configured with apps so i can't use apps and even server side code as well.
Please suggest any alternatives for doing this.
Thanks in advance.
Share the script here in case someone have similar requirement.
<script>
$(function () {
getDataFromSite1();
getDataFromSite2();
})
function getDataFromSite1() {
var url = "http://sp:12001/_api/web/lists/GetByTitle('MyList')/items";
$.ajax({
async: false,
url: url,
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
console.log(data)
},
error: function (data) {
}
});
}
function getDataFromSite2() {
var url = "http://sp:12001/sites/team/_api/web/lists/GetByTitle('MyList')/items";
$.ajax({
async: false,
url: url,
method: "GET",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose"
},
success: function (data) {
console.log(data)
},
error: function (data) {
}
});
}
</script>

How to update the model from the ajax by rest framework(csrf problem??)

I want to update the table row by from ajax
From auto generated form (by rest framweorks) posting and updating works correctly.
However from ajax it shows
"POST /api/issues/372/ HTTP/1.1" 403 58 error
I googled around and found that this is related with csrt.
However How can I send correct json???
var json = {
"id": 37;
"name": "This is my new name",
"color": "#dddddd"
};
$.ajax({
type:"POST",
url: "{% url 'issues-detail' 372 %}",
data:JSON.stringify(json),
contentType: 'application/JSON',
dataType: "JSON",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
},
complete: function() {
console.log("complete");
}
});
you can add this code to your js file in document.ready function
$(document).ready(function() {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url)))
{
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
}
}
});
});
For sending POST request we need to set csrf-token.

Writing to DynamoDB table using API Gateway and Lambda from a Web page

Part of the project, I want to write data entered into my web page from onto to a DynamoDB database, for this, I have written a Node.js code in AWS lambda to write items into a DynamoDB table. Created a web page form with more than one entries for users to fill required information and created an API Gateway to connect Lambda and HTML web page. Below are the codes for Lambda, API gateway, and HTML form. Please go through them.
Lambda My code:
exports.handler = function (e,ctx,callback) {
"use strict";
var params = {
Item : {
marchp : e.stepno,
Prev_step_no :e.prevstepno,
Next_step_no: e.nextstepno,
Inputdata : e.inputdata,
Acknowledgement: e.acknowledgement,
Condition: e.condition,
},
TableName : 'MARCHPevents'
};
API Gateway Body Mapping Templates:
{
"stepno": $input.json("$.stepno"),
"prevstepno": $input.json("$.prevstepno"),
"nextstepno": $input.json("$.nextstepno"),
"inputdata": $input.json("$.inputdata"),
"acknowledgement": $input.json("$.acknowledgement"),
"condition": $input.json("$.condition")
}
HTML Code pasing data to API gateway:
url:API_URL,
success: function(data){
$('#entries').html('');
data.Items.forEach(function(MARCHPreventsItem){
$('#entries').append('<p>' + MARCHPreventsItem.InputData + '</p>');
})
}
});
});
$('#submitButton').on('click', function () {
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify({ "stepno": $('#s1').val() }),
data: JSON.stringify({ "prevstepno": $('#p1').val() }),
data: JSON.stringify({ "nextstepno": $('#n1').val() }),
data: JSON.stringify({ "inputdata": $('#msg').val() }),
data: JSON.stringify({ "acknowledgement": $('#ack').val() }),
data: JSON.stringify({ "condition": $('#con').val() }),
contentType: "application/json",
success: function (data) {
location.reload();
}
});
return false;
});
If on passed one value from HTMLwebpage form to API gateway to passing to perfectly to Lambda which writing that one value to DynamoDB.
Problem Facing is passing more than one value from HTML web page form to API gateway this time it is having an invocation error at Lambda
Any Help?
Your JavaScript looks incorrect - you are overwriting the data parameter. You need to set the properties on the data object, i.e.
var obj = {
stepno : ${'#s1'}.val(),
prevstepno : ${'#s2'}.val(),
...
}
$.ajax({
type: 'POST',
url: API_URL,
data: obj,
contentType: "application/json",
success: function (data) {
location.reload();
}
});

No params in route for ajax post

When I post data to a Scalatra route, no params are seen.
On the client:
$.ajax({
type: 'POST',
url: window.location.origin + '/move',
contentType: 'application/octet-stream; charset=utf-8',
data: {gameId: 1, from: from.toUpperCase(), to: to.toUpperCase()},
success: function(result) {
console.log('ok posting move', result);
},
error: function(e) {
console.log('error posting move', e);
}
});
In dev tools network view:
Payload
gameId=1&from=B1&to=C3
In Scalatra route:
params("gameId") // -> java.util.NoSuchElementException: key not found: gameId
However, if I change the ajax call by removing the data field and setting the url to:
type: 'POST',
url: window.location.origin + '/move?gameId=1&from=' +
from.toUpperCase() + '&to=' + to.toUpperCase(),
Then Scalatra can see the params OK, even though it seems wrong to put params in the query string for a post.
Why can't Scalatra see any params when posting data?
You need to use application/x-www-form-urlencoded as content type:
script(type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js")
:javascript
$(function() {
$("#btn").click(function() {
$.ajax({
type: 'POST',
url: window.location.origin + '/form',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: {gameId: 1, from: "FROM", to: "TO"}
});
});
});
span#btn hello
In your Scalatra application:
post("/form") {
val payload = for {
gameId <- params.getAs[Int]("gameId")
from <- params.getAs[String]("from")
to <- params.getAs[String]("to")
} yield (gameId, from, to)
payload
}
For details please take a look at the Servlet specification.