Converting array variable back to string for ajax post - javascript

Someone helped me with this yesterday but it's now messed up how I send a string query to my endpoint in the AJAX call.
Functionally, this script works but by converting searchResult to an array, it screwed up my ajax call and what I send as a string query to an endpoint.
How can I modify this to make sure it sends searchResult as a string again to my ajax?
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let searchResult = [];
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
$("#groupName").val(searchResult[$(foundOption).attr('srindex')]._source);
$("#groupNum").val(searchResult[$(foundOption).attr('srindex')]._source);
} else {
$.ajax({ url: '/account/autocomplete',
data: {
search_result: searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
let searchResult = response.hits.hits;
console.log(searchResult);
$("#returnedProducts").empty();
for(let i = 0; i < response.hits.hits.length; i++) {
$("#returnedProducts").append("<option value=" + searchResult[i]._source.category + ">" + searchResult[i]._source.category + "</option>");
}
}
});
}
});

Related

AJAX Call passing null values to controller

I'm trying to send data to the controller using this AJAX call of type POST but it's sending null values to the controller. Through this code I want to make new records in the Microsoft Dynamics 365 CRM database.
var formdata = new FormData();
var rowCount = $(".newRow").length;
var projectarray = [];
var datearray = [];
var amountarray = [];
for (var i = 0; i < rowCount; i++) {
projectarray[i] = $("#ProjectType_" + i).val();
datearray[i] = $("#ClaimExpenseDate_" + i).val();
amountarray[i] = $("#Amount_" + i).val();
}
formdata.append("projectarray", projectarray);
formdata.append("datearray", datearray);
formdata.append("amountarray", amountarray);
$.ajax({
url: "#Url.Action("SetClaimDetails", "Claim")",
type: "POST",
data: formdata,
processData: false,
contenttype: false,
success: function (data) {
debugger;
window.location.href = "ess/claim";
alert("Submit Successful!");
},
error: function (err) {
window.location.href = "";
alert("Submit Failed!");
}
});
Here is my controller method which is storing null values instead of the values passed by the AJAX call. And because of this I'm not able to create new records in the database.
public ActionResult SetClaimDetails(string projectarray, string datearray, string amountarray)
{
try
{
Entity item = new Entity("bam_expenseclaims");
item["bam_expdate"] = Convert.ToDateTime(datearray);
item["bam_amount"] = amountarray;
item["bam_project"] = new EntityReference("new_project", Guid.Parse(projectarray));
globalService.Connection.Create(item);
}
catch (Exception ex)
{
XmlConfigurator.Configure();
ILog log = LogManager.GetLogger("TechnicalErrorAppender");
log.Error(string.Empty);
throw ex;
}
return View(Constant.CLAIMPATH);
}

How to send data from javascript function to Django View

I am trying to send data from a javascript function that generates a random string upon the page loading to a Django view. I don't know how to structure the script tag to send the data after the page has loaded and the views.py to receive the data. I am new to javascript and don't quite know how to go about this. I appreciate any help provided.
index.html
<script>
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
console.log(makeid(9));
</script>
You can use ajax to send data to Django view like following code.
javascript:
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
$.ajax({
type: "GET",
url: '/my_def_in_view',
data: {
"result": result,
},
dataType: "json",
success: function (data) {
// any process in data
alert("successfull")
},
failure: function () {
alert("failure");
}
});
}
urls.py:
urlpatterns = [
url(r'^my_def_in_view$', views.my_def_in_view, name='my_def_in_view'),
...
]
views.py:
def my_def_in_view(request):
result = request.GET.get('result', None)
# Any process that you want
data = {
# Data that you want to send to javascript function
}
return JsonResponse(data)
If it was successfull it goes back to "success" part.
you can do that in two ways:
Tradicional with ajax
Websockets: With django channels
If you want to send a bit of information, an ajax request is enough, you have to set and address and a view to receive the POST or GET ajax request.
I recommend to you use pure JS, not jquery
For example, this is a call to refresh a captcha image....
/*Agregar boton refresh al lado del campo input*/
let captcha_field =
document.getElementById('captcha-field-registro_1').parentNode;
let refresh_button=document.createElement('BUTTON');
refresh_button.addEventListener('click',refresh_captcha)
refresh_button.innerHTML = "Refrescar Captcha"; // Insert text
captcha_field.appendChild(refresh_button);
let url_captcha= location.protocol + "//" +
window.location.hostname + ":" +
location.port + "/captcha/refresh/";
let id_captcha_0="captcha-field-registro_0"
function refresh_captcha(){
let xhr = new XMLHttpRequest();
xhr.open('GET', url_captcha, true);
xhr.onload = function recv_captcha_load(event){
console.log("event received", event,
"state",xhr.readyState);
let data_txt = xhr.responseText;
let data_json = JSON.parse(data_txt);
console.log("Data json", data_json);
if (xhr.readyState==4){
if (xhr.status==200){
console.log("LOAD Se ha recibido esta informaciĆ³n", event);
let captcha_img=document.getElementsByClassName('captcha')[0];
console.log("Catpcha img dom", captcha_img);
captcha_img.setAttribute('src', data_json['image_url'])
document.getElementById(id_captcha_0).value=data_json['key']
}
else{
console.log("Error al recibir")
}
}
};
var csrftoken = getCookie('csrftoken');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send();
}
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}

How to POST Data from HTML Page via WebApi in MVC Controller

Function which is use to take input data from HTML
function saveclickdata()
{
var allData = {
InvNo:document.getElementById('TbInvNo').value,
GrossSale:document.getElementById('TbOrderTotal').value,
discount:document.getElementById('TbDiscount').value,
CusCash:document.getElementById('TbCash').value,
CusBal:document.getElementById('TbBalance').value,
};
$.ajax({
url: "\Controllers\POSController.cs\SaveData",
type: 'POST',
data: allData,
success: function (res) {
alert("success");
},
error: function (err) {
alet("Error");
}
});
Api which is in controller used to post data
[HttpPost]
JsonResult SaveData(POSMater collection)
{
if (collection.InvNo.ToString() == null)
{
var LocalInvNo = (from b in db.TblPOSMasters select b).FirstOrDefault();
int MaxInvNo = Convert.ToInt32(LocalInvNo) + 1;
collection.InvNo = MaxInvNo;
TblPOSMaster master = new TblPOSMaster();
master.InvNo = collection.InvNo;
master.AddBy = 1;
master.AddDate = DateTime.Now;
master.CashStatus = "A";
master.CompId = 1;
//master.CreditAmt = collection.CreditAmt;
//master.CrCardNo = collection.CrCardNo;
master.CusCash = collection.CusCash;
master.CusId = 1;
master.GrossSale = collection.GrossSale;
db.TblPOSMasters.Add(master);
db.SaveChanges();
}
else
{
return Json(collection);
}
return Json(collection);
}
What should i do? My html button working properly but still not able to call api
I think you ought to use forward slashes (/) in your URL

How can I execute callback after multiple Ajax requests complete? [duplicate]

This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to execute a callback after multiple jQuery Ajax have completed.
In my code both Ajax requests call another function and when I try to use these functions I get undefined.
I think the problem has to do with using deferred/promise, but I don't know how to use them.
Here is my code:
<link rel="stylesheet" type="text/css" href="https://tag/sites/ocean1/maker/captions/shared%20documents/Web_ComplianceCSS.txt">
<div id = "cabbage" style="font-size:10px">
<p>Web Compliance Stats</p>
</div>
<script type = "text/javascript">
var WebComplianceReportApp = {} || WebComplianceReportApp;
WebComplianceReportApp.GetStatuses = (function() {
var pub = {},
_userId,
_ultimateObjectHolderArr = [],
_items = [],
_options = {
listName: "M_Web_Compliance",
container: "#cabbage",
};
pub.init = function() {
var clientContext = new SP.ClientContext.get_current();
_userId = clientContext.get_web().get_currentUser();
clientContext.load(_userId);
clientContext.executeQueryAsync(getUserInfo, _onQueryFailed);
};
function getUserInfo() {
_userId = _userId.get_id();
getSpecifiedList(_options.listName, _userId);
}
function buildObject(results, listName) {
_items = results.d.results;
$.each(_items, function(index, item) {
_ultimateObjectHolderArr.push({
"Division": item.ParentOrg,
"ORG": item.ORG,
"URL": item.URL,
"Status": item.Site_Status
});
});
//createStatusView2(_ultimateObjectHolderArr);
}
function getSpecifiedList(listName, userId) {
var counter = 0;
var baseUrl = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
var call1 = $.ajax({
url: url1,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
var url2 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
var call2 = $.ajax({
url: url2,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
}
function createStatusView2(Arr) {
var divisionArr = [];
var oRGArr = [];
var divisionCount = 0;
var oRGCount = 0;
for (var i = 0; i < Arr.length; i++) {
if ($.inArray(Arr[i].Division, divisionArr) === -1) {
divisionArr.push(Arr[i].Division);
var divisionHolderElement = $("<div id='p_" + Arr[i].Division + "' class='division_row_holder'></div>");
var divisionElement = $("<div id='" + Arr[i].Division + "' class='division_div ORG'></div>").text(Arr[i].Division);
$("#cabbage").append(divisionHolderElement);
$(divisionHolderElement).append(divisionElement);
}
if ($.inArray(Arr[i].ORG, oRGArr) === -1) {
oRGArr.push(Arr[i].ORG);
var orgElement = $("<div class='org_div ORG' id='" + Arr[i].ORG + "' style='font-size:10px;'></div>").text(Arr[i].ORG);
$("#p_" + Arr[i].Division).append(orgElement);
}
}
}
//automatically fired by init
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return pub
}());
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
//After the SP scripts are run, we access the WebComplianceReportApp.GetStatuses
WebComplianceReportApp.GetStatuses.init();
});
});
</script>
I dont know if this will make your code dirty, but I would use a flag in this case
ex:
var ajaxCalls = 0;
function checkAjaxCalls()
{
if (ajaxCalls == 2)
{
//do your thing...
//and maybe you want to reset ajaxCalls value to zero if needed...
}
}
And from each Ajax response completes, increment ajaxCalls variable by one, and call the checkAjaxCalls function from both your Ajax responses.
Method One:
This time we'll have waited for the request to complete instead of waiting for the request to succeed
$(".ajax-form-button-thingy").on("click", function() {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
error: function() {
throw new Error("Oh no, something went wrong :(");
},
complete: function(response) {
$(".ajax-form-response-place").html(response);
}
});
});
Method Two:
If you want to wait for ALL Ajax requests to complete without changing the async option to false then you might be looking for jQuery.ajaxComplete();
In jQuery every time an Ajax request completes the jQuery.ajaxComplete(); event is triggered.
Here is a simple example but there is more info on jQuery.ajaxComplete(); over here.
$(document).ajaxComplete(function(event, request, settings) {
$(".message").html("<div class='alert alert-info'>Request Complete.</div>");
});
Also you can take a look at the Ajax response by using request.responseText this might be useful in case you want to double check the response.
For more information about jQuery.ajax you can read the docs here
You could call createStatusView(); and then call createStatusView2(); after all of your Ajax requests are done
$(document).ready(function(){
createStatusView();
$(this).ajaxStop(function() {
// NOTE: I did not see you use createStatusView(); in your code
createStatusView2();
});
});

Angular ng-grid : how to load multiple api data?

I have a 'ng-grid' table that have 2 types of data source. One is from my database using a function called getContributors(), and another one is from a list of api(s).
The getContributors function is like the default function in the ng-grid tutorial.
function getContributors() {
var deferred = $q.defer();
$http.get(contributorsFile)
.then(function(result) {
contributors = result.data;
deferred.resolve(contributors);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
}
My method for loading the multiple api data is to load the database data first, and then after all the database data is all loaded it will make a request to the api using a parameter from the database data
var ajax_wait_count = 0;
gridService.getContributors().then(function(data) {
// Looping each data with angular.forEach()
angular.forEach(data, function(value, key){
var this_uid = value['uid'];
// if(ajax_wait_count==0)
// {
$timeout(function(){
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getrank.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['ranked_tier'] = json;
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlevel.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
data[key]['level'] = json['level'];
// console.log(json);
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getsummonercreate.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != 0) {
var date_c = json[0]['create_date'];
date_c = date_c.replace(' ', 'T');
new_date = new Date(date_c);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['summoner_create_date'] = datestring;
}
else if (json == 0) {
data[key]['summoner_create_date'] = "";
}
},
error: function () {
// alert("Error");
}
});
$.ajax({
url: "<?php echo $glob_base_url; ?>api/getlastplayed.php",
type: 'POST',
data: { id: this_uid },
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success: function (json) {
// do stuff with json (in this case an array)
// json = jQuery.parseJSON(json);
if (json != "null" && json != null) {
var datedatas = json;
var datearray = [];
var thedatestr = "";
var loopidx = 1;
now_date = new Date();
now_date.setHours(0);
now_date.setMinutes(0);
now_date.setSeconds(0);
now_date.setDate(now_date.getDate() - 2);
next_date = new Date();
next_date.setHours(23);
next_date.setMinutes(59);
next_date.setSeconds(59);
// next_date.setDate(next_date.getDate());
angular.forEach(datedatas, function (value3, key3) {
datearray[key3] = parseInt(value3['createDate']);
});
datearray.sort();
datearray.reverse();
var count_played_today = 0;
angular.forEach(datearray, function (value2, key2) {
if (loopidx == 1) {
thedatestr = value2;
}
date_compare = new Date(parseInt(value2));
if (date_compare.getTime() >= now_date.getTime() && date_compare.getTime() < next_date.getTime()) {
count_played_today++;
}
loopidx++;
});
// var date_c = json[0]['create_date'];
// date_c = date_c.replace(' ','T');
var dateinsert = parseInt(thedatestr);
new_date = new Date(dateinsert);
// console.log(json);
var datestring = new_date.format("yyyy-mm-dd HH:MM:ss");
data[key]['last_played_date'] = datestring;
this_date = new Date();
date_diff = dateDiff(new_date.toString(), this_date.toString());
data[key]['last_played_date_qty'] = date_diff.d + " days " + date_diff.h + " hours " + date_diff.m + " minutes";
data[key]['count_played'] = count_played_today;
}
else if (json == "null" || json == null) {
data[key]['last_played_date'] = "";
data[key]['last_played_date_qty'] = "";
data[key]['count_played'] = 0;
}
},
error: function () {
// alert("Error");
}
});
},1500);
ajax_wait_count=0;
// }
ajax_wait_count++;
});
$scope.myData = data;
});
Now, the problem that emerges is :
The loading time for the api data is very long, and because of ajax asynchronous request, I can't make a loading function to delay the data
It appends the api data after the database data, which sometimes confuses the user whether the data is loaded or not
Sometimes in Chrome, the request is too much and it returns "err_insufficient_resources"
My question is,
Can my method of loading the api data be changed so it will make the loading time much faster and more efficient?
To make users less confused about the high amount of data, how can I make the progressbar (angular progress bar) wait for the database data + the api (AJAX) data?
Thank you in advance

Categories