Sending Array Using Ajax to Django App - javascript

So I have some jquery and ajax that collects data from checkbox values. This part is working, I used alert to debug the array to see if the appropriate values are being collected when the checkboxes are ticked.
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type:'POST',
url:'createEvent/',
data:{
name: name,
myCheckboxes: myCheckboxes,
}
});
However on my receiving end I have:
def createEvent(request):
if request.method == "POST":
member = request.POST.getlist('myCheckboxes')
print(member)
Member is an empty array. What am I doing wrong? I can't seem to find the answer.

Related

Javascript post request one key and multiple values

I have a script to submit an array of id's to be deleted. The script is not tied to a form.
The data is in the form of {'id': [1,2]}.
When I run the script, the form data is changed to id[]: 1
I have tried $.param(), but that just creates a single string.
I could join 1,2 into a string (i.e. {id: "1,2"}, but would prefer to avoid that. Any suggestions?
function delete_messages(event){
let data = {id: [1,2]};
event.preventDefault();
let parameters = {
url: '/message/delete'
type: "POST",
data: data,
dataType: "html"
};
addcsrf();
$.ajax(parameters).done(function(data){
alert("successfully deleted");
})
.fail(function(data){
alert("failed to delete");
});
}
Flask Code
#bp.route('/message/delete', methods=['POST'])
#login_required
def message_delete():
message_ids = request.form.get('msg_id')
deleted = []
for id in message_ids:
msg = RecipientData.query.get(id)
if msg is not None and msg.user_id == current_user.id:
msg.update(status='trash')
return redirect(url_for('main.view_messages', folder="inbox"))
var ids=[];
ids[0] = 1;
ids[1] = 2;
In the ajax request, change the data as given below:
data: {ids:ids},

JQuery/Ajax post in Razor page and redirect to returned view from MVC Action (aka form submitting)

I post a json array to the MVC Action via either JQuery or AJax, and Action handles the request correctly. However, then MVC Action is returning a View and I need to redirect to this View (or replace a body with it) but I don't know how.
So, the action is working well except probably for the returning value:
[HttpPost]
public ActionResult CreateGet(List<string> itemIds)
{
List<TempItem> items = new List<TempItem>();
foreach (string item in itemIds)
{
items.Add(CallApi.Get(Request.Cookies["jwt"], "tempitems", item.ToString()).Content.ReadAsAsync<TempItem>().Result);
}
Invoice inv = new Invoice()
{
IsSupplement = items[0].IsSupplement,
Date = DateTime.Now,
Employee = CallApi.Get(Request.Cookies["jwt"], "employees/getprofile").Content.ReadAsAsync<Employee>().Result,
InvoiceItems = new List<InvoiceItem>()
};
foreach(TempItem item in items)
{
inv.InvoiceItems.Add(new InvoiceItem { Amount = item.Amount, ProductId = item.ProductId, Product = item.Product });
}
return View(inv);
}
And the script inside razor page, that collects selected ids and posts them to the action.
After the post nothing else happens, even the alert is not being called, even though the View page exists and I don't see fails in console.
function CreateInvoice(id) {
var selected = $('#' + id).DataTable().rows('.selected').data();
var items = [];
for (i = 0; i < selected.length; i++) {
items.push(selected[i][0]);
}
var postData = { itemIds: items };
$.ajax({
type: "POST",
url: "/Invoices/CreateGet",
data: postData,
success: function (data) {
alert("success");
window.location.href = data.url;
},
dataType: "json",
traditional: true
});
}
Update
Well, I gave up that nonsense and stuck to GET request that passes array of ids in the URL. I think I just doing things wrong.
You should change ActionResult to JsonResult.
And return like this:
return Json(new {url: "yoururl", inv: yourdata}, JsonRequestBehavior.AllowGet);
If you don't need to do nothing in actual page with data returned from ajax call, you shouldn't use ajax call. You can use submit request and redirect page in backend to new page.

PHP POST: Setting data variables dynamically from an array

Hi all I'm pretty new to PHP and AJAX and all that good stuff and I'm a little stumped on how to proceed from here in my code.
I have a form that is getting sent and I have an array (subcategories) which contains the form labels to retrieve the values of the fields. The fields and values are getting created dynamically based on a textfile that the user uploads so I don't have any way of knowing what they are.
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
var eachfield = subcategories[i];
//Do something
//#C: selector is working fine, cleaning input
var eachfield = $('#' + eachfield).val().trim();
//push the appropriate values with the fixed stuff to a new array
values.push(eachfield);
}
What I'm trying to do is now to set these variables to some name and send them through $data using AJAX and POST.
Something like the following if I was setting everything statically.
var data = {
dimitypedata: dimitype,
densitydata: density,
velocitydata: velocity,
temperaturedata: temperature,
submitbtnclicked: "submitted"
};
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
I'm not quite sure how to mix these two and it may be partially because of getting a confused and not yet being that great with POST and AJAX calls.
EDIT: It looks like my question was a bit unclear (sorry first post lol) I'm trying to dynamically push values that I take out of an HTML form field. The problem is that the form is generated depending on what the user chooses to upload to the site (so both the fields and the forms. My ultimate goal is to enable the user to edit the dynamically generated form based on a text file that they upload and be able to generate a new text file after editing it on the GUI after clicking on the submit button. I can do this if its static but I'm having trouble figuring out how to do the same if I don't know what the form will contain.
I'm trying to to my data object so I can use it in my AJAX call. Here's a little bit of the PHP code that I would use in the next step if the variables were static:
if(isset($_POST['submitbtnclicked']) && $_POST['submitbtnclicked'] == 'submitted') {
//new instance of model for use
$model = new model();
$dimitypedata = $_POST['dimitypedata'];
$densitydata = $_POST['densitydata'];
$velocitydata = $_POST['velocitydata'];
$temperaturedata = $_POST['temperaturedata'];
For an exact answer, we need to see what the "subcategories" array look like.
If I understood correctly, you would like to put the values in an object instead of an array (values). So the first part would look like:
var data = {};
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
//notice that now field name and field value go in separate variables
var fieldName = subcategories[i];
//#C: selector is working fine, cleaning input
var fieldValue = $('#'+eachfield).val().trim();
//push the appropriate values with the fixed stuff to a data object
data[fieldName] = fieldValue;
}
//and then you send your gathered data
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
If you want to generate your 'data' object using 'values' variable, you can do the next:
values = []; // here your values collected previously
var data = {};
for (var key in values){
data[key] = values[key];
}
//now you can use your data in AJAX

How to transfer data from view to controller action function using jquery in Web2py

I need some help in transferring data from a view to a controller action function. My case is as follows:
I have a table with checkboxes. Each table entry corresponds to a request with a request id. the user will select some checkboxes and then click the 'Approve' button. On clicking the button, the jQuery script must find all selected request ids and send them to a controller function.
Here is the jQuery code:
function get_selected_req(){
var ids = [];
jQuery('#sortTable1 tr').has(":checkbox:checked").each(function() {
var $row = $(this).closest("tr");// Finds the closest row<tr>
$tds = $row.find("td:nth-child(2)"); // Finds the 2nd <td> element
ids.push($tds.text());
$('#out').text(ids.join('|'));
});
}
I have to send the array 'ids' to a controller function that can then process the requests using the ids. But I don't know how to do that. Any help will be highly appreciated.
Update:
I have written the ajax code in the view. I am only sending one id at a time. The code is as follows:
$.ajax({
type: 'POST',
url: "{{=URL(r=request, c='admin',f='approve_request')}}",
data: $tds.text(),
success: function(data){ alert('yay');
tab_refresh();
check_resource(data);
}
});
i am bit stuck on how to parse the data in the controller. Here is the code:
def approve_request():
request_id=request.args[0]
enqueue_vm_request(request_id);
session.flash = 'Installation request added to queue'
redirect(URL(c='admin', f='list_all_pending_requests'))
Please guide me.
Use push to push a value to a array,join the array with a delimiter, split the resulting data in the serverside
ids.push($tds.text());
$('#out').text(ids.join('|'));
note: #out should be hidden input
You can pass any value to function by simply calling a function in javascript.
Client side:
$.ajax({
type: "POST",
url: "HomePage/HandleOperations",
data: {operations: operationCollection},
success: function (data) { alert("SUCCESS"); }
});
and declare a class server side like this:
public class Operation
{
public int Index[];
}
then you can have this action:
public void HandleOperations(Operation[] operations)
{
}
else you can try this option
var selectedCatId = $(this).val();
var details = baseUrl+"/controllername/controllerfunctionname/"+selectedCatId;
and in controller
public function controllerfunctionname(array of ids[] ){
}
When you post data to web2py, the resulting variables can be found in request.post_vars (also in request.vars, which is a combination of request.post_vars and request.get_vars). To send the data in the proper format, you should send a Javascript object rather than a single value or an array (the keys of the object will become the keys of request.post_vars).
If you want to send a single id at a time:
$.ajax({
...,
data: {id: $tds.text()},
...
});
Then in your web2py controller:
def approve_request():
request_id = request.post_vars.id
To send an array of ids:
$.ajax({
...,
data: {ids: ids},
...
});
Note, when you send an array via jQuery as above, jQuery converts the key from "ids" to "ids[]", so to retrieve the array in web2py:
def approve_request():
request_ids = request.post_vars['ids[]']

How do I send data from JS to Python with Flask?

I'm making a website with Flask and I'd like to be able to execute python code using data from the page. I know that I can simply use forms but it's a single page that is continually updated as it receives user input and it'd be a massive pain in the ass to have it reload the page every time something happens. I know I can do {{ function() }} inside the javascript but how do I do {{ function(args) }} inside the javascript using js variables? So far the only thing I can think of is to update an external database like MongoDB with the js then use Python to read from that, but this process will slow down the website quite a lot.
The jQuery needs to get a list of dictionary objects from the Python function which can then be used in the html. So I need to be able to do something like:
JS:
var dictlist = { getDictList(args) };
dictlist.each(function() {
$("<.Class>").text($(this)['Value']).appendTo("#element");
});
Python:
def getDictList(args):
return dictlistMadeFromArgs
To get data from Javascript to Python with Flask, you either make an AJAX POST request or AJAX GET request with your data.
Flask has six HTTP methods available, of which we only need the GET and POST. Both will take jsdata as a parameter, but get it in different ways. That's how two completely different languages in two different environments like Python and Javascript exchange data.
First, instantiate a GET route in Flask:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return jsdata
or a POST one:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return jsdata
The first one is accessed by /getmethod/<javascript_data> with an AJAX GET as follows:
$.get( "/getmethod/<javascript_data>" );
The second one by using an AJAX POST request:
$.post( "/postmethod", {
javascript_data: data
});
Where javascript_data is either a JSON dict or a simple value.
In case you choose JSON, make sure you convert it to a dict in Python:
json.loads(jsdata)[0]
Eg.
GET:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return json.loads(jsdata)[0]
POST:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return json.loads(jsdata)[0]
If you need to do it the other way around, pushing Python data down to Javascript, create a simple GET route without parameters that returns a JSON encoded dict:
#app.route('/getpythondata')
def get_python_data():
return json.dumps(pythondata)
Retrieve it from JQuery and decode it:
$.get("/getpythondata", function(data) {
console.log($.parseJSON(data))
})
The [0] in json.loads(jsdata)[0] is there because when you decode a JSON encoded dict in Python, you get a list with the single dict inside, stored at index 0, so your JSON decoded data looks like this:
[{'foo':'bar','baz':'jazz'}] #[0: {'foo':'bar','baz':'jazz'}]
Since what we need is the just the dict inside and not the list, we get the item stored at index 0 which is the dict.
Also, import json.
.html
... id="clickMe" onclick="doFunction();">
.js
function doFunction()
{
const name = document.getElementById("name_").innerHTML
$.ajax({
url: '{{ url_for('view.path') }}',
type: 'POST',
data: {
name: name
},
success: function (response) {
},
error: function (response) {
}
});
};
.py
#app.route("path", methods=['GET', 'POST'])
def view():
name = request.form.get('name')
...
im new in coding, but you can try this:
index.html
<script>
var w = window.innerWidth;
var h = window.innerHeight;
document.getElementById("width").value = w;
document.getElementById("height").value = h;
</script>
<html>
<head>
<!---Your Head--->
</head>
<body>
<form method = "POST" action = "/data">
<input type = "text" id = "InputType" name = "Text">
<input type = "hidden" id = "width" name = "Width">
<input type = "hidden" id = "height" name = "Height">
<input type = "button" onclick = "myFunction()">
</form>
</body>
</html>
.py
from flask import Flask, request
app = Flask(__name__)
html = open("index.html").read()
#app.route("/")
def hello():
return html
#app.route("/data", methods=["POST", "GET"])
def data():
if request.method == "GET":
return "The URL /data is accessed directly. Try going to '/form' to submit form"
if request.method == "POST":
text = request.form["Text"]
w = request.form["Width"]
h = request.form["Height"]
//process your code
return //value of your code

Categories

Resources