I want to pass arrays in the jquery $.post() request.
HTML:
<input type="checkbox" id="add-check-1e30">
<input type="checkbox" id="add-check-1230">
From the above example HTML the array should be like this = ['1e30', '1230']
jQuery for sending $.post():
$("#addbox-add").click(function(){
var ukeys = new Array();
$("input[type=checkbox]:checked").each( function() {
a = $(this).attr("id");
b = a.split('-').pop();
ukeys.push(b);
});
$(".addbox").remove();
$.post("/information/portfolio/add/", {'ukeys': ukeys }, function(data) {
for(i=0; i<data.length; i++)
{
ukey = data[i].ukey;
image = data[i].image;
service = data[i].service;
if(data[i].smallimage != "")
{
image = data[i].smallimage;
}
if (image == null)
{
$(".portfolio-preview").append('<li class="portfolio-item" id="portfolio-item-'+service+'-'+ukey+'"></li>');
}
else
{
$(".portfolio-preview").append('<li class="portfolio-item" id="portfolio-item-'+service+'-'+ukey+'"><img class="portfolio-image" src="'+image+'" width="150px" height="150px"></li>');
}
}
});
});
There is no problem with the array variable in jQuery, I don't know how to send it in the post request.
I'm supposed to get those two values 1e30 and 1230 in the server. But the values I'm getting in the server is null.
Here is the server code for fetching the values in Python/Django:
def portfolio_add(request):
ukeys = request.POST.get('ukeys', '')
.....etc.....etc......
Thanks!
You have to use:
request.POST.getlist('ukeys', '')
Related
I basically want to implement a django view that accepts some json data and then also posts a json data which would be displayed.The confirm group view accepts a list of people via json data , forms a group and then returns the group code back to display.
I was getting the Forbidden(403) CSRF token missing or incorrect Error
I am beginner in django and js so please answer accordingly. Thanking you in advance :)
view.py
import json
def confirm_group(request):
data = json.loads(request.body.decode("utf-8"))
grp = Group()
grp.group_code = group_code_generator()
grp.save()
for i in range(len(data)):
Player = Regplayer.objects.filter(pk=data[i]["pk"])
pl = Enteredplayer()
pl.regplayer = Player
pl.group = grp
pl.save()
return JsonResponse(grp.group_code, safe=False)
script.js
function confirm()
{
var i = 0;
var rows= document.getElementById("group").children;
var num= document.getElementById("group").childElementCount;
if(num==0)
{
}
else
{
// alert("Confirm grouping of "+num+" people?");
for(i=0; i < num; i++)
{
send_name=rows[i].children[0].children[0].innerHTML;
send_gender=rows[i].children[3].children[0].innerHTML;
send_clgname=rows[i].children[1].children[0].innerHTML;
send_sport=rows[i].children[2].children[0].innerHTML;
send_id=rows[i].children[5].innerHTML;
myObj["data"].push({"name":send_name, "gender":send_gender, "college":send_clgname, "sport": send_sport, "pk": send_id});
alert(JSON.stringify(myObj));
}
csrf_token = document.getElementById('csrf_token').innerHTML;
myObj["data"].push({"csrfmiddlewaretoken": csrf_token });
//POST TO BACKEND
// Sending and receiving data in JSON format using POST method
//
var ourRequest = new XMLHttpRequest();
var url = "/confirm_group/";
ourRequest.open("POST", url, true);
ourRequest.setRequestHeader("Content-type", "application/json");
// POST
var data = JSON.stringify(myObj);
ourRequest.send(data);
// Obtain
ourRequest.onreadystatechange = function () {
if (ourRequest.readyState === 4 && ourRequest.status === 200) {
var json = JSON.parse(ourRequest.responseText);
var groupCode = json.groupcode;
//json object received
new_group(groupCode);
}
};
// if success call new_group() else call error_handle()
// new_group();
//error_handle();
//empty json object now
}
}
index.html
<span id="csrf_token" style="display: none;">{{ csrf_token }}</span>
<div class="confirm-modal">
<div class="form">
<p id="modal-text"></p>
<button class="btn1" onclick="confirm()">Confirm</button>
<button class="btn2" onclick="close_modal()">Cancel</button>
</div>
</div>
Before customers can proceed to paypal, I have a quick check on the database to see if the items still available,. The problem im having is that while Ajax is executing. function check_availability continue executing and returns true to the Form onsubmit before the completion of Ajax. To fix that problem I kept calling the same function within. But I dont think that is the best possible option.
Here is the code:
<form onsubmit="return check_availability(0,0,1)" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="pp1">
function ajax_paypal(orders){
var htpr = new XMLHttpRequest();
var url = "Hi there";
var val = "orders="+orders;
htpr.open("POST", url, true);
htpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
htpr.onreadystatechange = function(){
if(htpr.readyState == 4 && htpr.status == 200){
var sold_out_ids = htpr.responseText;
check_availability("continue", sold_out_ids, 0);
}
};
htpr.send(val);
}
function check_availability(str, sold_out_ids, n) {
if (str === "continue") {
if (sold_out_ids > 0) {
alert("One of your items has sold out! Sorry for any inconvenience");
location.reload();
return false;
} else {
return true;
}
}else if(n === 1){
var orders = [];
var x = document.cookie.split(';'); // your array of cookies
var i = 0;
x.forEach(item => {
//to make sure that item contains "order"
if (item.indexOf('order') > -1) {
var val = item.split("=");
orders[i] = val[1]+"o";
i++;
}
});
ajax_paypal(orders);
}
check_availability(0, 0, 0);//I keep calling this until Ajax is completed
}
You can use following code snippet to solve. This will be called on submit but before actual submit happen if you return true from here form will get submit to paypal. If you return false form won't get submit.
$('#pp1').submit(function() {
var submitOrNot=await callcheck_availability();
return true; // return false to cancel form submit
});
async function callcheck_availability(){
//your function goes here
}
for more on async await read this page on MDN
Below is my ajax function which retrieves the data from servelt and shows it fine in the jps and the problem is every time a new ajax calls is submit the form just appends the data into the results received from previous calls, I need reset the current values stored in the table OrderResultContainer and then display it with new data.
I tried
document.getElementById("OrderResultContainer").reset = ();
but it's just reset the entire form data and not showing any data in the page.
function addData() {
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
var loading = document.getElementById("loading");
document.getElementById("loading").style.display = "";
document.getElementById("OrderResultContainer").style.display = "none";
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
xhttp.onreadystatechange=function() {
if ((xhttp.readyState == 4) && (xhttp.status == 200)) {
var jsonorderdata = JSON.parse(xhttp.responseText);
txt = "";
for (x in jsonorderdata) {
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";
}
document.getElementById("loading").style.display = "none";
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
document.getElementById("divOrderResultContainer").style.display = "";
}
};
}else
console.log('Ajax call is failed');
}
Can anyone help me on how to reset the data in the table OrderResultContainer alone after a new ajax response received from servlet.
You append the received data to the previous with following code:
document.getElementById("ViewOrderResultContainer").innerHTML = document.getElementById("ViewOrderResultContainer").innerHTML + txt;
So if you change it like following you would have only new data:
document.getElementById("ViewOrderResultContainer").innerHTML = txt;
It is kind of hard to see without the corresponding html but this looks like the problem:
document.getElementById("ViewOrderResultContainer").innerHTML =
document.getElementById("ViewOrderResultContainer").innerHTML + txt;
Your taking the innerHtml from the ViewOrderResultContainer and append the value from txt. If you do that more than once than it will keep growing. If you want to replace the text than replace it with
document.getElementById("ViewOrderResultContainer").innerHTML = txt;
p.s. the given javascript is not valid
txt += "<tr><td>" + jsonorderdata[x].ordernumber+"</td>""</tr>";
Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps
I have created the following JavaScript function to load images of a vehicle, or load the alternate image if it is not available. The problem is that this page is 1kb, meanwhile it has to load the entire jquery library at 85+kb just for this one function. So my question is, is there some way to accomplish the same without having to load the jQuery library?
function GetImages() {
var Query = location.search;
//If query exists
if ((Query != "") && (Query != "?")){
var chunks = Query.split("=");
//If passed the right parameter
if (chunks[0] == "?unit") {
var Unit = chunks[1];
for (var i=1; i<11; i++) {
var unitimageURL = "/pics/"+Unit+"-"+i+".png";
$.ajax({
type: 'HEAD',
url: unitimageURL,
async: false,
success: function() {
$('.pictures').append("<img src="+unitimageURL+" width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
},
error: function() {
$('.pictures').append("<img src=nopic2.png width=150 height=90 alt='Unit "+Unit+" Picture "+i+"'> ");
if ((i == 4) || (i ==8)) {
$('.pictures').append("<br>");
}
}
});
}
}
}
else {
alert("No query");
}
}
Yes, there is a way - the good old var oRequest = new XMLHttpRequest(); way!
Don't forget to to set all the needed callbacks, check response statuses and everything will be fine.
To create a HEAD request, just specify "HEAD" as parameter to .open() method.
You will also need document.createElement() to append the results to your page (or you may use .innerHTML property as well.
Also, documentation like this http://www.tutorialspoint.com/ajax/what_is_xmlhttprequest.htm may be handy.