How to build entire dataset prior to sending AJAX -Jquery - javascript

I have a system that allows an admin to add managers to a campaign from a table. The table looks something along the lines of
<tr>
<td>Checkbox</td>
<td>Last name, First name</td>
<td>Employee Id #</td>
</tr>
Currently, when the "Add Manager" button is hit, I pass the manager's id and a "checked" value using this function
<script>
function addMgrs(){
dict = {}
$('#potentialReviewers tr').each(function() {
var userPid = $(this).find('td').eq(2).text()
var addMgrBox = $(this).find('.addMgrBox').attr('value')
if (addMgrBox == 'checked') {
dict[userPid] = addMgrBox }
// Create the Post request, pass the csrf_token in the header of the request
$.ajax({
url: '/campaign-view/' + '{{ campaign.id }}' + "/",
type: 'POST',
headers: {'X-CSRFtoken': '{{ csrf_token }}'},
data: dict,
dataType: 'json'
})
})
}
</script>
What this does is iterate through the table, build the JSON response and pass it back to the Django view to do the backend processing. My problem is this, for each row it sends a POST request and that drastically increases the time it takes for the process to complete. I'd like it to build the entire dictionary prior to sending the response, but just can't wrap my head around how to do that. Any help would be appreciated.

Alright, so as n1md7 pointed out in the comments, I simply needed to move the AJAX request outside of the loop. Here is what the code block looks like now:
<script>
function addMgrs(){
dict = {}
$('#potentialReviewers tr').each(function() {
var userPid = $(this).find('td').eq(2).text()
var addMgrBox = $(this).find('.addMgrBox').attr('value')
if (addMgrBox == 'checked') {
dict[userPid] = addMgrBox }
})
// Create the Post request, pass the csrf_token in the header of the request
$.ajax({
url: '/campaign-view/' + '{{ campaign.id }}' + "/",
type: 'POST',
headers: {'X-CSRFtoken': '{{ csrf_token }}'},
data: dict,
dataType: 'json'
})
}
</script>
As you can see, I now close the loop prior to making the request and it went from a 4+ minute process to almost instantaneous. Thank you n1md7

Related

Javascript Equivalent of Swift HTTPbody

I am looking for a way to put variables in to a AJAX get call, now i know the obvious way to do it would just be to add it too "data" like so
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication', favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});
But this goes to an api and the api also handles request from an iOS app which put the data into httpBody like so
let json: [String: Any] = ["userid":userID, "message":applicationtext.text, "favourid":selectedFavour]
let jsondatatosend = try? JSONSerialization.data(withJSONObject: json)
// create post request
let url = "myurl";
var request = URLRequest(url: url)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsondatatosend
I believe the reason i did this origionally was it was messing up because of having strange characters in the URL so i had to send it through the body which all worked well, but now im trying to get a website to follow the same method on my api i would like it to be sent in the body from ajax so my php can do this function
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
I understand there are many ways for me to get around it in my php just use $_GET[' var '] instead of file_get_contents when it is sent from the AJAX of my website but i was wondering if there was a way of sending it into the body via ajax so i dont have to change the php file and then it is not sent through url's
so what i want to be able to do is something like this
$.ajax({
type: "get",
url: "api.php",
data: {sessionkey: sessionkey, request: 'createapplication'},
httpBody: {favourid: favourid, userid: userid, message:message },
success: function(data) {
console.log(data);
}
});

MethodNotAllowedHttpException when trying to post data to controller via ajax in laravel

I'm trying to send dynamically generated data to controller via ajax in laravel. When user select an option from the dropdown then along with selected option and other data should be sent to controller.
I've tried to send data to controller when an option from dropdown is selected. But every time i try this error,
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
and in the error
REQUEST_METHOD is GET
This is the where i call the ajax function
$(document).on('change', '.route-code-selector', function() {
var selectorID = $(this).attr('id');
addRoutePlanDetails(selectorID);
});
AJAX function
function addRoutePlanDetails(selectorID) {
var routePlanCode = document.getElementById("routeplanno").value;
var driver = $("#selectDriver").val().split('|');
var salesman = $("#selectSalesman").val().split('|');
var router_01 = $("#selectRouter01").val().split('|');
var router_02 = $("#selectRouter02").val().split('|');
var vehicle_no = document.getElementById("enterVehicleNo").value;
var route_code = document.getElementById(selectorID).value;
var date = document.getElementById("date").value;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: 'addNewRoute',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
}
Route
Route::group(['prefix' => 'admin'], function () {
Voyager::routes();
Route::get ('route-plan', 'RoutePlanController#index');
Route::get ('excludePorterRes', 'RoutePlanController#excludePorterRes');
Route::get ('retreiveRouteData', 'RoutePlanController#retrieveRouteCodeData');
Route::get ('retreiveUserData', 'RoutePlanController#retreiveUserData');
Route::get ('retreiveNewRouteData', 'RoutePlanController#retreiveNewRouteData');
Route::post('addNewRoute', [
'uses' => 'RoutePlanController#insertNewRoute',
'as' => 'addNewRoute'
]);
});
controller
public function insertNewRoute(){
$routeplan = new Routeplan;
$user_email = auth()->user()->email;
$routeplan->RouteplanCode = Input::get('routePlanCode');
$routeplan->RouteCode = Input::get('route_code');
$routeplan->DriverID = Input::get('driver');
$routeplan->SalesmanID = Input::get('salesman');
$routeplan->Routercode1 = Input::get('router_01');
$routeplan->Routercode2 = Input::get('router_02');
$routeplan->VehicleNo = Input::get('vehicle_no');
$routeplan->Date = Input::get('date');
$routeplan->Createuser = $user_email;
$routeplan->Status = 'TEMP';
$routeplan->save();
}
when user select an option all the data should be stored in the db.
Try it once
url: '{{ route('addNewRoute') }}',
The issue is here:
url: 'addNewRoute',
here you are calling the route in a wrong manner, use it like:
url: '{{ url('admin/addNewRoute') }}',
you have to call the url() method so that it can create the right url format and don't forget the addNewRoute is grouped under admin, so you have to append that to while calling it.
If ajax method is runs in external javascript file, you should define a url variable in the blade (generally it layout blade.) that using as ajax request url on the ajax call method. (before .js file is loaded);
Example var url = '{{ route('addNewRoute') }}'
$.ajax({
url: url',
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
If you using ajax in the blade, you can use directly route as ajax request url.
$.ajax({
url: "{{ route('addNewRoute') }}",
method: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
You forgot / in your routes.
Route::group(['prefix' => 'admin'], function () {
Add / in admin/
Route::group(['prefix' => 'admin/'], function () {
Then you can try this in your ajax
url: '{{ url('admin/addNewRoute') }}',
or
url: 'admin/addNewRoute',
Try if this will work.
You have used prefix for your routes. So all your route in group will be prefix/uri.
So in ajax call you should url: '{{ url('admin/addNewRoute') }}', and change method to type
$.ajax({
url: '{{ url('admin/addNewRoute') }}',
type: 'POST',
dataType: 'json',
data: {
routePlanCode: routePlanCode,
driver: driver[1],
salesman: salesman[1],
router_01: router_01[1],
router_02: router_02[1],
vehicle_no: vehicle_no,
route_code: route_code,
date: date
},
success: function() {
console.log("success");
}
});
In ajax for specifying HTTP Verb use type not method.
if your script is in blade file then use route() to set url in ajax:
$.ajax({
url: '{{route('addNewRoute')}}',
method: 'POST',
dataType: 'json',
...
});
Try this:
Please use url: '{{ route('addNewRoute') }}' instead of url: 'addNewRoute'.
As many of you said.. I changed method to type.. And it still didn't work. But then i looked at laravel logs (storage/logs) and from the logs i found that some of my controller syntax are incorrect. And that's why it still gave me the 500 error. After I changed the syntax and do the corrections. It worked !! Anyways thanks for helping guys! If anyone is getting this error even if your ajax is correct take a look at laravel logs.. Hope this helps someone.

Laravel Ajax Post returns 500

I built an ajax post which sends each slider value (I am using jquery ui slider) to my controller.
The Ajax code:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
contentType: "application/json",
url: "{{ Route('editProductPost', $product->id) }}",
headers: {
'X-Requested-With': 'XMLHttpRequest'
},
data: JSON.stringify({
value: getSliderVal,
productId : getPrId
}),
datatype: 'json',
success: function(response) {
// get response
console.log(response.sliderValue)
}
});
And in my Controller I am doing this:
public function editProductPost(Request $request)
{
Log::info($request->get('value'));
return view('product.edit', [
'sliderValue' => $request->get('value')
]);
}
This returns me the correct slider value,
Log::info($request->get('value'));
But I get this error message in my browser console:
POST http://localhost/myApp/public/product/edit/98 500 (Internal
Server Error)
Later on I want to call this sliderValue inside of a php loop in my view.
Edit
I do have a csrf token:
<meta name="csrf-token" content="{{ csrf_token() }}">
Edit
I have done this:
$sliderValue = $request->get('value');
$route = 'updateProduct';
return view('product.edit', compact(['sliderValue', 'route']))->render();
The console print me undefined and if I do this {{ sliderValue }} I get an error that sliderValue is not defined
Little change of your code:
public function editProductPost(Request $request)
{
Log::info($request->get('value'));
$sliderValue = $request->get('value';
return view('product.edit', compact('sliderValue'))->render();
}
The problem here is that you're returning a view in your controller. If your view used {{ $sliderValue }} inside it, it should work. But there's no way for javascript to get the sliderValue variable.
If you wanted the sliderValue as is, you can return this array
return [
'view' => view('product.edit', compact(['sliderValue', 'route']))->render(),
'sliderValue' => $sliderValue
];
That way you're sending to javascript an object with 2 properties, one should contain the view and the second one will only contain the value.

Django returning None after request.POST.get

I'm new to Django and AJAX and I'm trying to send the ID of a dropdown list to the Django View with an ajax POST. This ID is then used in a queryset filter to return with AJAX the row, based off the ID. I'm getting stuck with applying the filter to the query set, as it seems to be posting the ID and then a variable with None. When I print to console the variable sent in the POST I get the ID, followed by none, e.g.:
1748
None
My HTML is:
<select id="drugSet">
{% for dose in dose_set %}
<option id="{{ dose.pubmed_id }}">{{ dose.drug_name }}</option>
{% endfor %}
</select>
<span id="drugName"></span>
Javascript:
function NeedDrugInformation() {
var elementID = document.getElementById("drugSet");
var strUser = elementID.options[elementID.selectedIndex].id;
$.ajax({
type: "POST",
url: "drugsanddoses/",
dataType: "text",
async: true,
data: { csrfmiddlewaretoken: '{{ csrf_token }}', drugID: strUser },
});
$.ajax({
type: "GET",
url: "drugsanddoses",
dataType: "text",
async: true,
data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
success: function (json) {
$('#drugName').html(json.drugInfo);
// $('.ajaxProgress').hide();
}
})
}
views.py:
def drugsanddoses(request):
drugIdentifier = request.POST.get('drugID')
print(drugIdentifier)
drugInfo = RiskCalculator.objects.values('drug_name', 'l_dose', 'h_dose', 'risk', 'pubmed_id', 'updated')
response_data = {}
try:
response_data['drugInfo'] = str(drugInfo)
except:
response_data['result'] = 'No details found'
response_data['message'] = 'There is currently no information in the database for this drug.'
return HttpResponse(json.dumps(response_data), content_type="application/json")
You're making two Ajax requests; one a POST, where the ID is present, and one a GET, where the ID is absent so it prints None. I don't really understand why you're making two requests, but that is what you are doing.

Passing Parameters of AJAX POST to Grails Controller

I´m building a social network with Grails and got stucked
on giving users inner their editprofile
page the chance to paste an youtube-Url into a textfield and by clicking a button a JS regexxes the id out of the URL pasted, an ajax post is fired updating a div with a preview image of the youtube video
the html looks like :
<g:textField name="videoinput" class="videoinput reLef" value="" />
<span class="daten_videouploadbtn reLef" ></span>
<g:render template="/forms/storedVideos" />
the JS looks like :
$('.daten_videouploadbtn').click(function() {
var string = document.editProfileForm.videoinput.value;
var neu = string.replace(/http[s]?:\/\/(?:[^\.]+\.)*(?:youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)|youtu.be\/)([\w\-\_]+)/i, '$1');
var id = RegExp.$1;
jQuery.ajax({
type:'POST',
data:RegExp.$1,
url:'${createLink(action: 'addVideo')}',
success:function(data,textStatus){jQuery('#storedvideos').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
});
the controller looks like :
def addVideo() {
def videoitems = !!%%-- HOW TO PARSE YOUTUBE-ID HERE -%%!!
render(template:"/forms/storedVideos", model: [newVideo:videoitems])
}
and stored videos looks :
<div id="storedvideos"><span><img src="http://img.youtube.com/vi/${newVideo}/default.jpg" width="225px" height="130px"/></span></div>
i just dont get it how to catch the data of the Ajax Post and update the div with the preview image with the id inside,
can someone give a hint ? it is killing me
You should post the data like this:
jQuery.ajax({
type: 'POST',
data: { value: RegExp.$1 },
...
After that you can access the posted data inside your grails controller with params.value.
I got this working on Grails 2.0.4:
Javascript/Ajax
var data =
{requestId: 12456,
node: "node1",
host: "mynode.com"};
$.ajax({
url: '/myurl',
data: JSON.stringify(data),
type: 'post',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() ...
},
error: function() ...
}
});
In Grails....
def service(){
def jsonObj = request.JSON
}
I like this approach because request.JSON parses the data and returns a ready to use object.

Categories