how to attach ajax requests into symonfy2 controller - javascript

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...");
}
});

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

Recieve data sent in request via AJAX in HTTP Response from Node.js

I am sending multiple AJAX requests by looping through a split string. I need to associate the response with the request. I'm trying to receive the data provided in the AJAX request in the HTTP response. I need this because I am making multiple requests and the responses are coming back asynchronously. It appears the synchronous functionality of AJAX is deprecated.
My javascript:
var ingredientName = "";
var regExpNumber = /\d+/;
var inputRecipe = $('#addRecipe fieldset input#inputRecipeIngredients').val();
//split up the string into pieces for analysis and matching
var recStringArray = inputRecipe.split(/[ ,]+/);
//need to do some kind of error checking in the future
//step through each piece of the string
for(var i=0; i < recStringArray.length; i++) {
//check each array item for numbers
var volumeCheck = (recStringArray[i].match(regExpNumber));
//Check each array item that isn't a number to see if it is a unit of measure
if (volumeCheck == undefined) {
$.ajax({
type: 'POST',
url: '/recipes/uomsearch/' + recStringArray[i],
data: { 'key' : recStringArray[i]}
}).done(function( response1, response2 ) {
// Check for a successful (blank) response
if (response1.length == 0) {
console.log("didn't find UOM");
ingredientName += response2;
console.log(ingredientName);
}
else {
for(var y=0; y < response1.length; y++) {
var p = response1[y].root;
console.log(p);
}
}
});
}//end of uom check for non-number array items
}
My recipes.js code running on the server:
router.post('/uomsearch/:key', function(req, res, res2) {
var db = req.db;
var collection = db.get('uomlist');
var query = req.params.key
res2 = query;
console.log(res2);
collection.find({'key': query},{},function(e,docs){
res.json(docs);
});
});
Adding "async:false" to the code causes the code to block and wait for the response before continuing. This allowed me to capture the index of the array and store the data.
$.ajax({
type: 'POST',
url: '/recipes/uomsearch/' + recStringArray[i],
data: { 'key' : recStringArray[i]},
async: false
})

SharePoint 2013 ClientContext : How to DELETE specific list items by MULTIPLE CONDITION filter?

By using SP.ClientContext from Javascript end, below is the code i used to "UPDATE" a list item. Simply:
var clientContext = new SP.ClientContext( siteURL );
spList = clientContext.get_web().get_lists().getByTitle( myListName );
this.spList_ExistingItem = spList.getItemById( itemID );
spList_ExistingItem.set_item( 'FullName', myFullName );
spList_ExistingItem.set_item( 'Age', myAge );
spList_ExistingItem.update();
clientContext.executeQueryAsync(succeeded_handler, fail_handler);
This allows me to update an list item by querying it by ONE condition which is: getItemById(itemID) here.
Now let's say i want to delete any item which is:
Age = 30
Country = US
Then how do i do such query with multiple conditions. And then even to DELETE please?
UPDATED
According to the answer below, i found the REST API is more easier and cleaner to use for Client/Javascript end, compared to CSOM. (So then, of course i changed all my codes to the REST API way already.)
So the conclusion is, i suggest to use REST API rather than CSOM (SP.ClientContext).
Thanks! :)
This can be done in two different ways, either by using CSOM/JSOM or via the SharePoint REST API. Since you are using the CSOM/JSOM model in your question, I'll only show you how it's done using that method.
Using CSOM/JSOM
To filter SP.ListItem's on mulitple conditions, there are no single methods that take the arguments as multiple filter fields. Instead, you'll have to resort to using a CAML query to specify the list items you want, as below.
var clientContext = new SP.ClientContext( siteURL );
spList = clientContext.get_web().get_lists().getByTitle( myListName );
//Create a CAML-query with your filter conditions
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Age\'/>' +
'<Value Type=\'Number\'>30</Value></Eq>
<Eq><FieldRef Name=\'Country\'/>' +
'<Value Type=\'Text\'>US</Value></Eq></And></Where></Query><RowLimit>10</RowLimit></View>');
//The query will return a collection of items matching your conditions
this.collListItem = spList.getItems(camlQuery);
clientContext.load(collListItem);
//Execute the query
clientContext.executeQueryAsync(function () {
var itemCount = collListItem.get_count();
//For each list item in the collection, mark it to be deleted
for (var i = itemCount - 1; i >= 0; i--) {
var oListItem = collListItem.itemAt(i);
oListItem.deleteObject();
};
//Execute the delete operation
clientContext.executeQueryAsync(deleteSucceeded, deleteFailed);
}, fail_handler);
Using SharePoint REST API
This method assumes that you use jQuery to be able to do some simple $.ajax() calls and use the promise functionality, since you might have multiple items to delete. It also assumes that you understands how you can use jquery deferred objects to chain asynchronous functions to run in sequence.
The simple idea is to
Make a request to the REST api and get all the items matching your filter conditions
For each object in the collection returned, make another request that deletes the item, and add the request to an array of requests
When all requests are done, do whatever you want!
Note that you might have to modify the REST api call to match your columns. Just use the browser or Postman to check that your request is correct.
function getItemsToDelete () {
//You might have to modify this so it filters correctly on your columns
var requestUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle(" + myListName + ")/items?$filter=Age eq 30 and Country eq 'US'")
//Return and ajax request (promise)
return $.ajax({
url: requestUrl,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function(result) {
$.each(result.d.results, function(index, item){
//Note that we push the ajax-request to the array
//that has been declared a bit down
itemsToDelete.push(deleteItem(item));
});
},
error: function(error) {
//Something went wrong when retrieving the list items
}
});
}
function deleteItem (item) {
//All SP.ListItems holds metadata that can be accessed in the '__metadata' attribute
var requestUrl = item.__metadata.uri;
return $.ajax({
url: requestUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": item.__metadata.etag,
"X-HTTP-Method": "DELETE"
},
success: function() {
console.log("Item with ID " + item.__metadata.id + " successfully deleted!");
},
error: function(error) {
//Something went wrong when trying to delete the item
}
});
}
//Declare an array of deferred objects that hold a delete request
//for each item that is to be deleted
var itemsToDelete = [];
//First get the items to delete
$.when(getItemsToDelete()).then(function () {
$.when.apply($, itemsToDelete).then(function(){
console.log("All items are deleted!");
});
});
Some useful sources
jQuery Deferred object
CRUD operations on list items with SharePoint REST api

Ajax in JavaScript sends only the last data in array

I want to send data from my application with json ajax in JavaScript. I have more than one packet of data, but when I send my data through ajax it only sends the last data packet.
For example, I send two data packets, then ajax sends two data packets but they both contain the same data(the last data packet).
Here is my code.
for(var i=0;i<data.length;) {
/*var d = new Date();
d.setTime(data[i].updated);*/
var send2 = {};
send2.nama= data[i].name;
send2.rumahsakit = data[i].hospital;
//step 1
alert("step 1"+send2.nama);
var client = "coba";
var Idku = data[i].unik;
//clientID
var request2 = {};
request2.jsonrpc = "2.0";
request2.id = "load_reg"+Idku+"";
request2.method = "registrasi:loadByClientUnik";
request2.params = [client,Idku];
//request2.params = akun.value;
var postData = JSON.stringify(request2);
var postArray = {json:postData};
$.ajax({
type: 'POST',
url: 'service.php',
data: postArray,
dataType:'json',
//async: false,
success: function(result){
alert(send2.nama);
//alert step 2;
if(result.result == -1){
//alert("-1 cuk");
var requestx = {};
requestx.jsonrpc = "2.0";
requestx.id = "store_reg";
requestx.method = "registrasi:store";
requestx.params = [send];
var postDatax = JSON.stringify(requestx);
var postArrayx = {json:postDatax};
$.ajax({
type: 'POST',
url: '/service.php',
data: postArrayx,
dataType:'json',
//async: false,
success: function(result){
//alert("sukses");
},
error: function(e){
console.log(e);
alert(e);
} });
}else{
alert(send2.nama);
var request = {};
request.jsonrpc = "2.0";
request.id = "store_reg";
request.method = "registrasi:storeById";
request.params = [result.result,send2];
var postData2 = JSON.stringify(request);
var postArray2 = {json:postData2};
$.ajax({
type: 'POST',
url: '/service.php',
data: postArray2,
dataType:'json',
//async: false,
success: function(result){
//send2 = "";
//alert("sukses ID");
},
error: function(e){
console.log(e);
alert(e);
}
});
}
},
error: function(e){
console.log(e);
alert(e);
}
});
//return false;
i++;
}
getData();
}
Example behavior: I send 2 data packets, 1st has name = 1 and the 2nd has name = 2, then I send both packets:
output :
alert step 1 print 1
alert step 1 print 2
alert step 2 print 2
alert step 2 print 2
I want this output :
alert step 1 print 1
alert step 2 print 1
alert step 1 print 2
alert step 2 print 2
}else{
alert(send2.nama);
var request = {};
request.jsonrpc = "2.0";
request.id = "store_reg";
request.method = "registrasi:storeById";
request.params = [result.result,send2];
var postData2 = JSON.stringify(request);
var postArray2 = {json:postData2};
$.ajax({
type: 'POST',
url: 'http://10.126.14.116/portable_med_services/service.php',
data: postArray2,
dataType:'json',
//context set
context: { send2: send2 },
//async: false,
success: function(result){
//send2 = "";
//alert("sukses ID");
},
error: function(e){
console.log(e);
alert(e);
}
});
This is my updated code with adding context...am I right??
update :
I already fixed this issue following this issue... jQuery ajax inside a loop problem
Your code actually sends both requests one after another (step 1), in order, like you probably want it to.
You get the first debug output due to the asynchronous nature of $.ajax() calls. They send the request and continue with the code execution-- they don't block and they don't wait for the response from the server. That's why your outer/main for loop executes all the way to the end (2 times in your case) before any response is received and the code inside the success callbacks is executed.
When the 2 responses are received, the success callbacks are executed (2 times, once for each response), however at that point in time your local variable send2.nama has the value of "2". That's why you get the output "step 2 print 2" twice, instead of "step 2 print 1" and "step 2 print 2".
This will likely also be the error cause for other requests that you make from inside the success callbacks, since you are using local variables inside the callbacks. You should be using the context parameter instead:
$.ajax({
// ...
context: { send2: send2 },
success: function (result) {
// "this" has the value of the context object
alert(this.send2.nama);
// ...
}
});
I am not sure if your intention is really to send the 2nd request only after the 1st response is already received, but if it is, then you will have to refactor the code a bit and send the 2nd request from a function invoked from inside the success callback of the 1st request.

Create dynamic list of dates in jQuery

In javascript I need a plain list of dates like (for a jquery datepicker):
["16-5-2013", "24-5-2013", "25-5-2013", "26-5-2013"]
Because this list is dynamic I want to use this ajax call:
var disabledDays = $.ajax({
type: 'GET',
url: "/disabled-days",
});
In Django I wrote this test view which returns the data in json:
def disabled_days(request, soort):
from django.http import HttpResponse
import json
soort = ["16-5-2013", "24-5-2013", "25-5-2013", "26-5-2013", "27-5-2013"]
return HttpResponse(json.dumps(soort), mimetype="application/json")
Is json here the way to pass the data? I find the date list in the responsText, but I am unable to access this data.
For example I tried to iter over the items like:
for (i = 0; i < disabledDays1.length; i++) {
item = results[i];
disabledDays.push(item);
}
This results in an empty list.
The responsetext is (encoding is json):
["16-5-2013", "24-5-2013", "25-5-2013", "26-5-2013"]
When I do a console.log() I see this info:
GET http://localhost:8080/disabled-days
200 OK
39ms
jquery-1.9.1.js (regel 8526)
Object { readyState=1, getResponseHeader=function(), getAllResponseHeaders=function(), meer...}
Below is the solution Anh TĂș gave (not working yet):
var disabledDays1 = $.ajax({
type: 'GET',
url: "/disabled-days",
});
var disabledDays = []
for (i = 0; i < disabledDays1.length; i++) {
item = results[i];
if(typeof(responsetext)==string){responsetext= JSON.parse(responsetext);} $.each(responsetext,function(i,item){disabledDays.push(item);});
}
console.log(disabledDays);
I think you're handling the ajax request wrong. Normally you declare a callback function when the request success that and process the data received like this:
var disabledDays = []
$.ajax({
type: 'GET',
url: "/disabled-days",
success: function(data){
// data is the response json
disabledDays = data
// do whatever it needs to be done with disabledDays,
// it should be the array of dates.
// the process should be inside this method because of asynchronous
// javascript method execution
}
});
Hope it helps!

Categories

Resources