Get Ajax / jQuery variables from external text file - javascript

I hope someone can help me with this:
I'm building a website with a product comparisontable (with checkbox filters) and I'm using a Javascript I found on the internet. I have some knowledge of JavaScript, but Ajax en jQuery are new for me :-).
The code that's working:
$(document).ready(function () {
filter_data();
function filter_data() {
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var walk = get_filter('walk');
var bike = get_filter('bike');
var swim = get_filter('swim');
var multi = get_filter('multi');
$.ajax({
url: "functions/fetch_data.php",
method: "POST",
data: {
action: action,
walk: walk,
bike: bike,
swim: swim,
multi: multi
},
success: function (data) {
$('.filter_data').html(data);
}
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function () {
filter_data();
});
});
This code is working, but ... the variables inside this function, need to be generated from an external text file. Because the variables need to be edited easily and very frequent. And there are a lot more variables than you see in this code.
And this is what my (shortened) textfile looks like:
1,brand,Brand
2,walk,Walk
2,bike,Bike
2,swim,Swim
2,multi,Multi
The numbers indicate whether the field should be used in the filter or not. Lines with number 2 are the variables, and need to be 'pasted' in the code as variables and datafields.
Is it possible to get the fields/variables from the textfile within Javascript Ajax / jQuery? So with an extra function?
I hope someone can help me with this, I've been working on it for many hours but I can't get it to work properly.
Thanks!!

Related

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

Parsing duplicate xml child elements with javascript

So I've been able to apply some code online from previous discussions to a project that I'm working on however, now that there are multiple xml elements to grab I cannot seem to figure out how.
The xml structure is set up like this:
``
<DEPTId id = "1234">
<GROUP_DESCRIPTION>Something</GROUP_DESCRIPTION>
<DESCIPTION>Some department</DESCRIPTION>
<SOFTWARE>piece 1<SOFTWARE>
<SOFTWARE>DSFAON</SOFTWARE>
<SOFTWARE>asdvn</SOFTWARE>
<DEPTId>
I have tried to either reformat the structure to be SOFTWARE1, SOFTWARE2, .. but I felt as though one element should suffice as there can be many pieces of software, and couldn't find a way to iterate across each element. However the code I have only prints out the SOFTWARE elements text as one string, and not separate checkboxes which I want.
My JavaScript is below. It checks their group and department from the html page, and if it is equal to the xml it will append the listed software to the table on the page.
function defaultSoftware() {
$("#defaultSoftwareList").empty();
$.ajax({
type: "GET",
url: "blahblah.xml",
contentType: "charset=utf-8",
dataType: "xml",
async: true,
success: parsePersonaXML
});
function parsePersonaXML(xml) {
$(xml).find("DEPTId").each(function() {
var htmlDepartment = $("#b1Department").val();
var htmlGroup = $("#techpersonaGroup").val();
var xmlGroup = $(this).find("GROUP_DESCRIPTION").text();
var xmlDepartment = $(this).find("DESCRIPTION").text();
if (htmlDepartment == xmlDepartment && htmlGroup == xmlGroup)
$(this).find("SOFTWARE").each(function() {
var sd = ("SOFTWARE").text();
$("#techpersonaList").append('<input type="checkbox" checked /> ' + sd + '<br />');
});
});
}
}
If anyone knows what I am doing wrong or how I can change it your help would be much appreciated!

Issue with HTML being returned in a $.ajax

Hey guys I have the following code:
$(document).ready(function () {
$(".atf-submit").click(function () {
atf_name = $(this).parent().parent().find(".user_table");
atf_amount = $(this).parent().parent().find(".user_atf");
runATFinsider();
});
});
function runATFinsider(){
var urlatfinsider = '/pcg/ATF/updateATF_window.php';
var tagatfinsider = $("#insider_dialog");
var promise1a = showUrlInDialogATFinsider(urlatfinsider);
var promise2a = sendUpdateATFwindow();
$.when(promise1a, promise2a).done(function(data1, data2) {
tagatfinsider.html(data1[0]).dialog({
width: '100%',
modal: true
}).dialog('open');
//$('.updaterATF_outerbody').text(data2[0].atfName),
//$('.updaterATF_outerbody').text(data2[0].atfAmount)
//alert(data2[0].atfname);
console.log(data2);
});
}
function showUrlInDialogATFinsider(urlatfinsider)
{
return $.ajax({
url: urlatfinsider
});
}
function sendUpdateATFwindow()
{
return $.ajax({
data: {
'atfName': atf_name.val(),
'atfAmount': atf_amount.val()
}
});
}
Look at the top and lets say the values of atf_name and atf_amount are 'joe and 0' When I do a console.log or alert(data2[0].atfName) it does not exist? It is not defined and when I did the console.log(data2), in place of where the values should be is abunch of HTML of the table and all that the values came from. I don't know why this is happening and it makes no sense because when I do alert(aft_name.val()) I would get the correct value that was taken?
If you could give me a hand I would appreciate it. Also this code runs when a dialog window is already opened and than this opens another one. I don't think that should be a problem.
David
Here is the HTML:
<input type='hidden' class='user_table' value='$memusername'/>
<input type='hidden' class='user_atf' value='$memATF'/>
These are inside a table.
Putting this as an answer because I pointed out you don't need to ajax call to get the values of atf_name and atf_amount in the comments to your solution. My suggestion, in order to keep the changes to your code to a minimum, would be to change the sendUpdateATFwindow() to:
function sendUpdateATFwindow() {
return {'atfName': atf_name.val(), 'atfAmount': atf_amount.val()};
}
Not sure but I've done jQuery AJAX return values like this:
$.ajax({
type: "POST",
url: url,
data: 'string'
}).done(function(returnVar) {
/* Do something with returnVar*/
});
I honestly don't know if this will help, but it's what I've used personally.
EDIT:
Also the return in AJAX file has to be sent out. I mainly deal with PHP files so I just do
ECHO $myVariable;
Hey guys I figured it out. I actually needed to create a separate file to return the values that were sent in so I just created this:
$name_ATF = trim( $_POST['atfName'] );
$amount_ATF = trim( $_POST['atfAmount'] );
$returnArray = array( 'atfName' => $name_ATF, 'atfAmount' => $amount_ATF);
echo json_encode($returnArray);
Worked great. Thanks guys for your hard work!
David

can javascript get value from MVC?

i am using asp.net mvc 3. in one my of page. i need to get a list of string from a list object.
so i do this:
#{
var orderIds = from s in Model.Orders
select s.id;
}
and from one of my ajax call, i will need "orderIds "
$("#renderBtn").click(function () {
var inputData = {
'orderIds': need to get the order ids here
};
$.ajax({
url: '/Order/ExtraData',
data: inputData,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
....
},
error: function () {
...
}
});
});
any idea how can i get orderIds and use in javascripts?
Thanks
Your code aboce defining orderIds is a server-side variable; what you need us a client-side variable. You'll need to define that variable at the creation of the view, in a script block near the bottom of the page.
#{
var orderIds = string.Join(",", Model.Orders.Select(s => s.id).ToArray());
}
<script>
    var orderIds  = [#orderIds]
</script>
Caveat: The code may not be perfect, and may not compile, but that should give you an idea how to proceed.
If you aren't (or don't want to) using inline javascript and keep it all separated you could do something like this:
#{
var orderIds = string.Join(",", Model.Orders.Select(s => s.id).ToArray());
}
<input type="hidden" id="orderIds" value="#orderIds" />
And then in your javascript/jQuery:
orderIds = $('#orderIds').val();

What is the best way to store a list client side to toggle dropdown select choices in asp.net-mvc site

I have a page that I load a select dropdown box but I want to have javascript code toggle this list to a different set of choices.
I have the code that clears and repopulates a select list box in javascript
function UpdateDropdown(list, dropdownSelector) {
var options = '';
$.each(list, function (index, value) {
if (value.Text == null) {
value.Text = '';
}
if (value.Value == null) {
value.Value = '0';
}
options += '<option value="' + value.Value + '">' + value.Text + '</option>';
});
$(dropdownSelector).html(options);
}
so that is not the issue but my question is How can i store an array locally from my view Model to lookup later from javascript? Should i store it in a hidden select box? is there a recommended practice here?
The easiest and cleanest solution is to just write some json to your view, stored in a variable that you then access inside your UpdateDropdown function. In your view:
<script type="text/javascript">
var globalData = #Html.Raw(Json.Encode(Model.MyArray));
</script>
The exact method you use to output json will differ depending on the version of ASP.NET MVC you're using, but that should put you on the right track.
And general javascript best practice is to create a single namespace for your code that you then put all your other variables into, so that you don't pollute the global namespace. So really it should be something like:
<script type="text/javascript">
var MyApp = {};
MyApp.dropdownData = #Html.Raw(Json.Encode(Model.MyArray));
</script>
But the first block of code I provided would be fine to get started with.
leora,
I was inspired by the following solution for sending 'lists' from javascript to and mvc action:
var leadIds = $('input.chkTileSelector:checked').map(function () {
return { name: 'leadIds', value: $(this).parents('div.Lead').data('id') };
}).get();
$.ajax({
url: '#Url.Action("UnParkLeads", "Lead")',
type: 'POST',
dataType: 'json',
data: leadIds,
success: function (result) {
ReloadResultGrid();
}
});
you can see the article here:
http://zootfroot.blogspot.com/2011/09/jquery-post-javascript-array-to-aspnet.html

Categories

Resources