I am doing:
var url = '#Url.Action("Attachments", "Transactions")';
url += '/?id=' + 3201;
$("#attachments").load(url);
However, on load it doesn't do anything. Am i missing something?
I essentially want to call something similar to:
#{Html.RenderAction("Attachments", "Transactions", new { id = 3301 });}
I get the following error on console:
http://server:54137/Transactions/#Url.Action(%22Attachments%22,
You must be using an external JavaScript file which will not parse your razor syntax hence the error in your console of #Url.Action(%22Attachments%22..
You have a couple of options:
Create a JavaScript function and pass in the url:
function loadUrl(url) {
$("#attachments").load(url);
}
Then in your razor call it within a script tag:
loadUrl(#Url.Action("Attachments", "Transactions", new { id = #Model.Id })
Add the url to the html element as data and read it from your JavaScript with the data method.
In your razor markup add this:
<button data-url="#Url.Action("Attachments", "Transactions", new { id = #Model.Id })" />
From your JavaScript event handler read it with:
var url = $(this).data('url');
$("#attachments").load(url);
I prefer the second option.
You Need to use Html.Raw check below
var url = "#Html.Raw(Url.Action("Attachments", "Transactions"))";
url += '/?id=' + 3201;
$("#attachments").load(url);
Related
I am making a website that grabs data from an API. The API essentially consists of a script normally ran as such
<script type="text/javascript" src="https://www.fxblue.com/users/dynascalp_demo/overviewscript"></script>
it will simply create an array and push the data I need from it, like this:
if (!document.MTIntelligenceAccounts) document.MTIntelligenceAccounts = new Array(); document.MTIntelligenceAccounts.push({ "userid": "dynascalp_demo","balance": 9275.95,"equity": 9275.95,"closedProfit": -724.05,"floatingProfit": 0,"freeMargin": 9275.95,"totalDeposits": 10000,"totalWithdrawals": 0,"totalBankedGrowth": -7.24,"monthlyBankedGrowth": -0.67,"weeklyBankedGrowth": -0.16,"dailyBankedGrowth": -0.03,"bankedProfitFactor": 0.66,"deepestValleyCash": -819.04,"deepestValleyPercent": -8.19,"troughInBalance": 9175.79,"peakInBalance": 10020.11,"historyLengthDays": 331,"averageTradeDurationHours": 2.17,"worstDayPercentage": -1.44,"worstWeekPercentage": -2.32,"worstMonthPercentage": -4.31,"tradesPerDay": 2.5,"totalClosedPositions": 589,"totalOpenPositions": 0,"bankedWinningTrades": 382,"bankedLosingTrades": 207,"bankedBreakEvenTrades": 0,"bankedWinPips": 1486.3,"bankedLossPips": -1604.6,"initialDeposit": 10000,"totalBankedPips":-118.3,"totalOpenPips":0,"peakPercentageLossFromOutset": -8.24,"riskReturnRatio": -1.21,"openAndPendingOrders": []});
My idea is to run this code conditionally, in another, bigger script. I will query my database and check whether the data is already in the database. If it is, then skip the request altogether and send the data from the database through an ajax request handled by the server, which will return a JSON. If it isn't or the data has expired, meaning it has not been updated for at least a day, it should grab the data from the API and update the database. This is done by the front-end as there is no Node.js support in the back-end.
The only thing I'm missing is how I should execute this script from mine, instead of calling it directly in the HTML.
For example, Fetch() does not work. I believe the request is malformed, or it is not the type of request it expects. Unexpected end of input is thrown and the request does not succeed.
This code should result in a number being shown
function fxBlue_retrieveAPI() {
document.MTIntelligenceAccounts = new Array();
const url = "https://www.fxblue.com/users/dynascalp_demo/overviewscript";
//var fxblue_API_Names = ["dynascalp_demo", "fxprogoldrobot", "fxprosilverrobot", "forex_gump_ea"];
var varNames = ["totalDeposits", "balance", "totalBankedGrowth", "monthlyBankedGrowth", "deepestValleyPercent", "historyLengthDays"];
var experts = [];
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", url);
document.body.appendChild(s);
for (var i = 0; i < document.MTIntelligenceAccounts.length; i++) {
experts.push({ name: document.MTIntelligenceAccounts[i].userid, id: i });
if (document.getElementById(experts[i].name + varNames[0])) { document.getElementById(experts[i].name + varNames[0]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].totalDeposits; }
if (document.getElementById(experts[i].name + varNames[1])) { document.getElementById(experts[i].name + varNames[1]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].balance; }
if (document.getElementById(experts[i].name + varNames[2])) { document.getElementById(experts[i].name + varNames[2]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].totalBankedGrowth + "%" };
if (document.getElementById(experts[i].name + varNames[3])) { document.getElementById(experts[i].name + varNames[3]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].monthlyBankedGrowth };
if (document.getElementById(experts[i].name + varNames[4])) { document.getElementById(experts[i].name + varNames[4]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].deepestValleyPercent + "%" };
if (document.getElementById(experts[i].name + varNames[5])) { document.getElementById(experts[i].name + varNames[5]).innerHTML = document.MTIntelligenceAccounts[experts[i].id].historyLengthDays };
}
}
<script type="text/javascript" src="/cdn-cgi/scripts/API/jquery-3.1.1.min.js" async></script>
<script type="text/javascript" src="/cdn-cgi/scripts/API/test.js"></script>
<body onload="fxBlue_retrieveAPI()">
<h3>Total banked growth data example</h3>
<p id="dynascalp_demototalBankedGrowth"></p>
</body>
Assuming (or hoping) that you won't experience CORS problems with your data source (here at SO it is not possible to reach the source), you could do something like this to get to the actual contents of the script file:
const actualText=`if (!document.MTIntelligenceAccounts) document.MTIntelligenceAccounts = new Array();\ndocument.MTIntelligenceAccounts.push({\n"userid": "dynascalp_demo","balance": 9275.95,"equity": 9275.95,"closedProfit": -724.05,"floatingProfit": 0,"freeMargin": 9275.95,"totalDeposits": 10000,"totalWithdrawals": 0,"totalBankedGrowth": -7.24,"monthlyBankedGrowth": -0.67,"weeklyBankedGrowth": -0.16,"dailyBankedGrowth": -0.03,"bankedProfitFactor": 0.66,"deepestValleyCash": -819.04,"deepestValleyPercent": -8.19,"troughInBalance": 9175.79,"peakInBalance": 10020.11,"historyLengthDays": 331,"averageTradeDurationHours": 2.17,"worstDayPercentage": -1.44,"worstWeekPercentage": -2.32,"worstMonthPercentage": -4.31,"tradesPerDay": 2.5,"totalClosedPositions": 589,"totalOpenPositions": 0,"bankedWinningTrades": 382,"bankedLosingTrades": 207,"bankedBreakEvenTrades": 0,"bankedWinPips": 1486.3,"bankedLossPips": -1604.6,"initialDeposit": 10000,"totalBankedPips":-118.3,"totalOpenPips":0,"peakPercentageLossFromOutset": -8.24,"riskReturnRatio": -1.21,"openAndPendingOrders": []});`;
// fetch("https://www.fxblue.com/users/dynascalp_demo/overviewscript")
fetch("https://jsonplaceholder.typicode.com/users/3") // (some dummy data source for demo purposes only)
.then(r=>r.text())
.then(text=>{ text=actualText; // mimmic the text received from www.fxblue.com ...
obj=JSON.parse(text.replace(/(?:.|\n)*push\(/,"").replace(/\);$/,""))
console.log(obj)
})
It is then up to you to decide whether you want to use the data or not.
Whatever you do, it is important that the action happens in the callback function of the last . then() call. Alternatively you can of course also work with an async function and use await inside.
My idea is to run this javascript code conditionally, by querying my database
For this you could do an jquery ajax call, and act based on the response you get. I recommend using jquery for the ajax call. Here is the jquery ajax call where you pass whatever data is necessary to the controller.
$.ajax({
type: "GET",
url: "/ControllerName/ActionName",
data: { data: UserIdOrSomething },
success: function(response) {
// you can check the response with an if, and implement your logic here.
}
});
You can place this ajax call in the document.ready function to automatically call it whenever the page loads.
$( document ).ready(function() {
// place the above code here.
});
As an example, here is how an asp.net core controller action would look like that would handle this ajax call;
[HttpGet("ActionName/{data:string}")]
public IActionResult ActionName(string data) // parameter name should match the one in jquery ajax call
{
// do stuff. query your database etc.
var response = "the response";
return Json(response);
}
finally, keep in mind handling sensitive data in javascript is generally not a good idea, as the javascript code is open to everyone. For example, in this case, you will be giving out a way for people to check if a user exists in your database, which could be problematic. I would suggest using guid as id for the users table if possible, which may or may not be useful to mitigate the dangers depending on how you query the database.
I have a webpage that was developed by someone else. I want to take the variable that they are displaying on when the page loads from the following tag <h3 id="TAGS"></h3> and append that to a this example URL http://someurl.com/<variable>.
I'm not a JavaScript person so any help would be appreciated.
I tried the following which did not work
var myURL = $('#TAGS').innerHTML
<input type="button" value="Download" onclick="window.location.href=\'http://someurl.com/' + myURL + '\'"/>
JAVASCRIPT + jQuery:
Create a global variable like var downloadURL = "" and make a function in jQuery:
$( document ).ready(function() {
var myURL = $("#TAGS").html();
downloadURL = "http://someurl.com/" + myURL;
});
and then you make your button like this:
<input type="button" value="Download" onclick="download()"/>
having the method download do whatever you want:
function download() {
if(downloadURL!="") {
window.location.href=downloadURL;
}
else {
//you don't have a value set
}
downloadURL="";
}
JAVASCRIPT: Create a global variable like var downloadURL = "" and make a function to load on page load:
window.onload = function() {
var myURL = document.getElementById("TAGS").innerHTML;
downloadURL = "http://someurl.com/" + myURL;
});
and then you make your button like this:
<input type="button" value="Download" onclick="download()"/>
having the method download do whatever you want:
function download() {
if(downloadURL!="") {
window.location=downloadURL;
}
else {
//you don't have a value set
}
downloadURL="";
}
You're trying to use Jquery library with '$' sign. if you didn't install that library simply don't use it. instead, you can use pure browser JavaScript function.
var myURL = document.getElementById("TAGS").innerHTML;
myURL will be whatever inside the HTML element.
for example: <h3 id="TAGS">test</h3>
myURL = test
Try this code:
var myURL = $('#TAGS').val()
But don't forget include jQuery to you code.
I have the following route definition:
routes.MapRoute(
"FormPreview",
"Forhandsgranska/{FormId}/{action}/{id}",
new { controller = "FormPreview", action = "Introduction", id = UrlParameter.Optional }
);
I have the following code that triggers the route and It works perfect:
$('#previewButton').on('click', function(){
document.location = '#Url.Action("","formPreview", new { formId = Model.Id })';
});
But now I have the following code that don't work. My route definition is not triggered and I'm redirected to a wrong page, and I don't know why:
var formId = $(this).closest('tr').data('formId');
document.location = "#Url.Action("", "formPreview")/" + formId;
What Is the difference between these two? Why Is the first one working and not the second one?
You have to use .replace method.
document.location = '#Url.Action("", "formPreview",new {formId ="formId"})'.replace("formId",formId);
In Razor every content using a # block is automatically HTML encoded by Razor.
What you have specified: #Url.Action("", "formPreview"), is not the same as #Url.Action("","formPreview", new { formId = Model.Id }). It doesn't match because in the route table you have a required formId, but you haven't specified it in #Url.Action.
Since your URL generated by routing happens before the JavaScript has a chance to interact with it, I suppose one (hacky) way to do it would be to create a dummy formId value and replace it on the client side with a real value.
document.location = '#Url.Action("", "formPreview",new {formId ="DUMMY"})'.replace("DUMMY",formId);
Alternative
Or you could add the dummy as a default value when the formId is not supplied.
routes.MapRoute(
"FormPreview",
"Forhandsgranska/{FormId}/{action}/{id}",
new { controller = "FormPreview", FormId = "DUMMY", action = "Introduction", id = UrlParameter.Optional }
);
Then you could replace the value on the client when needed.
document.location = '#Url.Action("", "formPreview")'.replace("DUMMY",formId);
However, as a side effect that means whenever you create a URL without specifying the FormId it will come out as /Forhandsgranska/DUMMY.
I want to pass a field of a domain object to a javascript function in my view.gsp (grails) , but I am getting a syntax error.
Here is my gsp and javascript - please let me know if you see the syntax error. Thanks!
/*HTML*/
<td>${fieldValue(bean: studentInstance, field: "active")}</td>
/*JS*/
<script type="text/javascript">
var id = 0;
function setID(userId){
console.log("userId: " + userId);
id = userId;
}
</script>
The issue is you have function in your onclick. You don't need it there. Remove it so your onclick looks like this:
onclick="setID( ${studentInstance.id})"
I have a page called search.jsp. When the user selects a record and the presses an edit button, I would like to open a new page (in the same window) with the record data (that is stored in a json object and passed to the new page). How do I use Javascript (or jQuery) to open a new page and pass the JSON data?
If the two pages are on the same domain, a third way is to use HTML5 localStorage: http://diveintohtml5.info/storage.html
In fact localStorage is precisely intended for what you want. Dealing with GET params or window/document JS references is not very portable (even if, I know, all browsers do not support localStorage).
Here's some very simple pure JavaScript (no HTML, no jQuery) that converts an object to JSON and submits it to another page:
/*
submit JSON as 'post' to a new page
Parameters:
path (URL) path to the new page
data (obj) object to be converted to JSON and passed
postName (str) name of the POST parameter to send the JSON
*/
function submitJSON( path, data, postName ) {
// convert data to JSON
var dataJSON = JSON.stringify(data);
// create the form
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', path);
// create hidden input containing JSON and add to form
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", postName);
hiddenField.setAttribute("value", dataJSON);
form.appendChild(hiddenField);
// add form to body and submit
document.body.appendChild(form);
form.submit();
}
Use some PHP like this on the target page to get the JSON:
$postVarsJSON = $_POST['myPostName'];
$postVars = json_decode( $postVarsJSON );
Or, more simply for JavaScript:
var postVars = JSON.parse( <?php $_POST['myPostName']; ?> );
Assuming the two pages are on the same domain, you can use the returned object created by window.open() to access (and edit) the window object of a newly opened window.
Hmm, for example, you have object
var dataObject = {
param : 'param',
param2 : 'param2'
};
You can translate it into string, using JSON.stringify method
var dataObjectString = JSON.stringify(dataObject);
Then you should use Base64 encoding to encode you data (base64 encode/decode methods can be easely found in search engines)
var dataObjectBase64 = base64encode(dataObjectString);
You will get something like this
e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307
Then you can pass this string as a parameter:
iframe src="http://page.com/?data=e3BhcmFtIDogJ3BhcmFtJyxwYXJhbTIgOiAncGFyYW0yJ307"
Finally, reverse actions on the loaded page.
You can create "on the fly" a form with a hidden/text input value this will hold the json value, then you can submit this form via javascript.
Something like this...
Im using JQUERY AND UNDERSCORE(for template purpose)
this is the template
<form method='<%= method %>' action="<%= action %>" name="<%= name %>" id="<%= id %>" target="_blank">
<input type='hidden' name='json' id='<%= valueId %>' />
</form>
you can then post use it on javascript
function makePost(){
var _t = _.template("use the template here");
var o = {
method : "POST",
action :"someurl.php",
name : "_virtual_form",
id : "_virtual_form_id",
valueId : "_virtual_value"
}
var form = _t(o); //cast the object on the template
//you can append the form into a element or do it in memory
$(".warp").append(form);
//stringify you json
$("#_virtual_value").val(JSON.stringify(json));
$("#_virtual_form_id").submit();
$("#_virtual_form_id").remove();
}
now you dont have to be worry about the lenght of you json or how many variables to send.
best!
If the the JSON is small enough you can just include it as a GET parameter to the URL when you open the new window.
Something like:
window.open(yourUrl + '?json=' + serializedJson)
Assume if your json data
var data={"name":"abc"};
The page which sends JSON data should have the following code in the script tag.
$.getJSON( "myData.json", function( obj ) {
console.log(obj);
for(var j=0;j
<obj.length;j++){
tData[j]=obj;
//Passing JSON data in URL
tData[j]=JSON.stringify(tData[j]);
strTData[j]=encodeURIComponent(tData[j]);
//End of Passing JSON data in URL
tr = $('\
<tr/>
');
//Send the json data as url parameter
tr.append("
<td>" + "
" +Click here+ "" + "
</td>
");
}
});
The page which receives the JSON data should have the code.
<html>
<head></head>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<body>
<p id="id"></p>
</body>
<script type="text/javascript">
function getQuery() {
var s=window.location.search;
var reg = /([^?&=]*)=([^&]*)/g;
var q = {};
var i = null;
while(i=reg.exec(s)) {
q[i[1]] = decodeURIComponent(i[2]);
}
return q;
}
var q = getQuery();
try {
var data = JSON.parse(q.jsonDATA);
var name=data.name;
console.log(name);
document.getElementById("id").innerHTML=name;
} catch (err) {
alert(err + "\nJSON=" + q.team);
}
</script>
</html>