Javascript post request one key and multiple values - javascript

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},

Related

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.

how to attach ajax requests into symonfy2 controller

My Javascript code:
$(document).ready(function() {
$('input[type="checkbox"]').change(function(){
var ids = ['filter_1','filter_2','filter_3','filter_4'];
for(var i = 0; i < ids.length; i++){
if(document.getElementById(ids[i]).checked === true){
var data = {request : $('#'+ ids[i]).val()};
}
}
$.ajax({
type: 'POST',
url: Routing.generate('listingpage'),
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function(result,status,xhr){
var inst_arr = JSON.parse(result);
console.log(inst_arr);
}
});
});
});
Here i have multiple check boxes with ids 'filter_1','filter_2','filter_3','filter_4' while sending ajax request it returns request individually. How can i attach multiple requests (like if i select two check boxes i want to show two requests into at a time) into single request.
My Controller Code:
if($request->isXmlHttpRequest()){
$data = $request->request->get('request');
// $this->container->get('logger')->addInfo('somesh'.$data);
$repository = $em->getRepository('EdufactionBundle:Institute');
$queryBuilder = $repository->createQueryBuilder('i');
$query = $queryBuilder
->innerJoin('i.instsummary', 's')
->innerJoin('i.address', 'a')
->innerJoin('i.insturl', 'u')
->select('s.instaffiliation')
->setParameter('instaffiliation', $data)
->getQuery()->getResult();
return $json = new Response(json_encode($query));
}
Here controller data if i select first checkbox it returns 1 and if i select checkbox 2 it returns 2. how can i post two checkbox data into single request and how can i bind multiple requests into single request.
Please help me anyone
One soulution for you is jQuery.when() to run multi ajax request one after another. working like this :
$.when( $.ajax( "Your first ajax request" ), $.ajax( "Your second ajax request" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the your two ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
//HERE Do something after all requests was done
console.log("Do Something...");
}
});

Sending function sent data to php file by ajax

I am trying to send data to a database.php file by ajax. My Index file has a form which will collect a 4 digit input then sends to a js function which sends the data to my db file. At the moment the Db file is being called because I get a result in the console but the 4 digit key is not being sent. I expect I have done something wrong with the ajax script.
Any help please
function addCode(key) {
var code = document.forms[0].code;
if (code.value.length < 4) {
code.value = code.value + key;
}
if (code.value.length == 4) {
document.getElementById("message").style.display = "block";
setTimeout(alarm, 1000, code.value);
}
}
function alarm(code) {
$.ajax({
method: "POST",
url: "alarm.php",
data: code,
cache: false,
success: function(responseText) {
console.log(responseText) // show returned text in console
}
})
emptyCode();
}
function emptyCode() {
document.forms[0].code.value = "";
}
The issue is because you're just sending the value by itself with no key. To fix this you could provide data with an object that will be form encoded when the request is sent:
data: { code: code },
Then in your PHP code you can retrieve the posted value by its key:
$code = $_POST['code'];

Sending Array Using Ajax to Django App

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.

jQuery post() with serialize and extra data

I'm trying to find out if it's possible to post serialize() and other data that's outside the form.
Here's what I thought would work, but it only sends 'wordlist' and not the form data.
$.post("page.php",( $('#myForm').serialize(), { 'wordlist': wordlist }));
Does anyone have any ideas?
You can use serializeArray [docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
Try $.param
$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));
An alternative solution, in case you are needing to do this on an ajax file upload:
var data = new FormData( $('#form')[0] ).append( 'name' , value );
OR even simpler.
$('form').on('submit',function(e){
e.preventDefault();
var data = new FormData( this ).append('name', value );
// ... your ajax code here ...
return false;
});
When you want to add a javascript object to the form data, you can use the following code
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
if (data.hasOwnProperty(key)) {
postData.push({name:key, value:data[key]});
}
}
$.post(url, postData, function(){});
Or if you add the method serializeObject(), you can do the following
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
In new version of jquery, could done it via following steps:
get param array via serializeArray()
call push() or similar methods to add additional params to the array,
call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.
Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}
$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});
You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.
Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:
var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);
I like to keep objects as objects and not do any crazy type-shifting. Here's my way
var post_vars = $('#my-form').serializeArray();
$.ajax({
url: '//site.com/script.php',
method: 'POST',
data: post_vars,
complete: function() {
$.ajax({
url: '//site.com/script2.php',
method: 'POST',
data: post_vars.concat({
name: 'EXTRA_VAR',
value: 'WOW THIS WORKS!'
})
});
}
});
if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!
Hope this helps.

Categories

Resources