I have a node.js project with frontend written in Pug. On the pug side I have written a Javascript function that is making an Ajax call and returning a string, I am trying to call this function inside that same pug file but it gives me a function not defined error. Can anyone please help with this?
header(class="global-header")
p Current Status: #{getCurrentAvail()}
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data){
console.log("===1")
currentAvail = data.message
console.log(currentAvail)
return data.message
},
error: function(data){
console.log("Error function avail");
}
});
}```
It appears you have some piece of external data and you want that data to show in a rendered web page. You have two basic choices here:
1. Server-side fetching and rendering of the data. You can have your server get the data before rendering the page and pass that data to your template engine so your template engine can insert the data into the page at the appropriate place.
2. Client-side fetching and insertion of the data. You can call the getCurrentAvail() function from within a <script> tag in the web page. This will send the rendered web page to the browser. As it loads, the browser will then execute your script, fetch the data from your server and then you would use DOM APIs in the browser to insert the result of that ajax call into the web page to make it visible to the user in the page.
Also, please note that your function getCurrentAvail() has no return value at all. You aren't returning anything from the outer function. Your return data.message is inside the asynchronous success callback so that just go back to nowhere. If you're going to go with the client-side option #2, then you can just put the DOM manipulation code right into the success callback function.
Your current code is attempting to do 1/2 server and 1/2 client and that is not something that will work.
At all times, have total clarity on what is in the server and what is in the client. Ajax methods run in the browser. A #{variable} construct exists only in Pug, and the substitution occurs on the server.
I think this is what you need:
header(class="global-header")
p Current Status:
span#status
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data) {
document.getElementById("status").innerText = data.message
},
error: function(data){
console.log("Error function avail");
}
});
}
getCurrentAvail();
Related
I've got a parent page that houses a series of iframes. These all reside on the same domain.
I've got an AJAX call that runs within each iframe when it loads and it retrieves some JSON for me that I'm using to populate inputs that reside within it. It's the same information being retrieved by each iframe.
Currently, I'm running that AJAX call inside of each iframe. This doesn't strike me as particularly performant and I'm encountering issues with this. In some cases depending on the order the DOM loads, one iframe will have the correct data available while another won't have any at all.
My thought now (and open to suggestion) is to load the AJAX once within the parent page, store the data I need as local storage variables and then call those from within each iframe. Idea being it loads once (before the iframes are called) so that the data is there and defined, every time.
As a rough proof of concept I've got this;
Parent page
$.ajax({
url: 'https://www.urlofsite.com/mylookupfile.php',
type: 'POST',
dataType : 'text',
data: {Finder: finderID},
success: finderAccess,
error: finderDecline
});
function finderAccess(data) {
console.log("sucessful send:");
// Parsing the returned data from the DB into a JSON object
var useableData = $.parseJSON(data);
console.log(useableData);
// Set the session variables that will be used by each form
localStorage.setItem('fName', useableData.fname);
const sessfName = localStorage.getItem('fName');
localStorage.setItem('lName', useableData.lname);
const sesslName = localStorage.getItem('lName');
}
//error function and some other non-related scripts follow
So now I've got my session vars set and it works within the parent page. If I call something like
$(".class-name-of-a-p").html(sessfName);
The paragraph with that class properly displays the value stored in the variable.
Moving onto the iframe now...
Iframe
$("#person_first_name").val(sessfName);
$("#person_last_name").val(sesslName);
My understanding of the HTML Local Storage method of creating local storage variables is that they are available as long as the domain is the same. That's the case here, but, in the iframe the console tells me the variables don't exist and throws an error.
Store the Ajax request in the window object (in your top-level frame):
window.lookup = $.ajax({
url: 'https://www.urlofsite.com/mylookupfile.php',
type: 'POST',
dataType : 'text',
data: {Finder: finderID},
});
Now, in each of your child frames, you can do
window.parent.lookup.done(function (data) {
// work with data
});
and all iFrames will receive the request as soon as it's there.
This works because $.ajax returns a promise. This promise is stored in window.lookup. You register as many .done() callbacks with a promise as you like - all of them will be notified when the promised result (the Ajax request in this case) is available. It also caches the data - frames that load later (or are created later) will receive the result immediately.
If you want to do some pre-processing before you hand down the data to your child frames, use .then() in the main top frame:
window.lookup = $.ajax({
url: 'https://www.urlofsite.com/mylookupfile.php',
type: 'POST',
dataType : 'text',
data: {Finder: finderID},
}).then(function (data) {
var modifiedData = doSomethingWith(data);
return modifiedData;
});
Now all child frames will receive modifiedData.
Error handling can be done in the top frame (this error handler will be called once):
window.parent.lookup.done(function (data) {
// work with data
}).fail();
url: 'https://www.urlofsite.com/mylookupfile.php',
type: 'POST',
dataType : 'text',
data: {Finder: finderID},
}).fail(function (jqXHR, textStatus, errorThrown) {
finderDecline();
});
or in the child frame (this will be called once per frame):
window.parent.lookup.done(function (data) {
// work with data
}).fail(function (jqXHR, textStatus, errorThrown) {
// do something appropriate
});
or in both.
I tried to call c# function in javascript so i used this: var a = <%=MYC#FUNCTION()%>, but the function in the weird brackets execute even before my page load. like executing the function is the top priority of my code.
i want the function to execute when i am calling it in my javascript code.
Please help me, i need this for my project in school.
i tried to use this but i didnt really understood this ->
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
You are misunderstanding the life cycle of the request/response. In your code, the order of execution will be
Web browser sends a request to your web server.
Web server (C# code) now handles the request and start creating HTML response.
Web server uses your controller/view (MVC) or .aspx/.aspx.cs (web form) to create the response.
Your code "MYC#FUNCTION()" is now executed. Let assume it returns a number 123.
After this, your html response is sent back to web browser.
Web browser receives the response and display to UI. Now, if you inspect HTML you will see "var a = 123;" (123 coming from your "MYC#FUNCTION()")
If you want to execute "MYC#FUNCTION()" after page load. Then you need to look at AJAX.
I have to process an operation in Javascript using data stored in session (System.Web.HttpContext.Current.Session["Filtre"])
Is it even possible to catch and do operation in Javascript using the asp.net session ?
I already tried some sample like this one without success :
var f = '<%=Session["Filtre"]%>';
In the case where this is impossible (for security issues I guess), is it possible to call a aspx.cs function in javascript who will perform the operation ?
Have a good day.
You cannot mix client side javascript and server side code (such as sessions). The processes do not run at the same time.
Your code
var f = '<%=Session["Filtre"]%>';
could work, BUT:
First the server needs to execute the <% %> block to generate a string, which is placed in some text
That text is sent to the browser, possibly as part of a page
Only in the browser it is interpreted and executed as javascript
There is no easy way for the browser to execute random server side code.
Complicated ways use AJAX calls to call specifically designed methods on the server (instead of arbitrary code).
using <scriptmanager> you can do
Please go through the below article
http://www.codeproject.com/Articles/525364/AJAX-for-Beginners-Part-3-Calling-Server-Side-Meth
Yes, your JavaScript can call a C# method if you annotate the method with WebMethod. This makes the method callable from remote Web clients (i.e. it becomes a 'page method'). MSDN.
You would need the EnableSession property set to true in order to use the Session. Example:
[WebMethod(EnableSession=true)]
public static int Example() {
...
Then call the page method from JavaScript, probably using jQuery.
$.ajax({
type: "POST",
url: "MyPage.aspx/Example",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ }",
error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); },
success: function (msg) {
alert(msg.d);
}
});
I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.
I'm making a dynamic webpage which retrieves lots of data from a database very frequently, like at least every 3 seconds.
I tested my webpage and database locally by using XAMPP. It works perfectly. However, it turns to be very slow after I upload everything to 000webhost (my free account). My webpage even freezes (I cannot scroll the page, not even doing anything but wait for the data to be transferred.) when retrieving the data.
I used a setTimeout function which called several ajax commands to read data from my database. I have optimised the data capacity already, but the page still freezes. I also tried to disable most of the ajax commands and only left one. When loading, the page freezes just as a blink, but anyhow it still freezes...
Most of my ajax commands are like below which simply retrieves data from my database and updates the related fields on my webpage. Some ajax commands uses $.parseJSON() because I need the whole row from a table.
$.ajax({
type: "GET",
url: "get_balance.php",
data: {wherematch: localStorage.login_user},
dataType: "html", //expect html to be returned
async:false,
success: function(response){
document.getElementById('balance').innerHTML = response;
}
});
Can anyone provide some suggestions how to solve this issue? Should I pay and get a better account?
Thanks.
to have an ajax refreshing every 3 s, your javascript & ajax must be like this:
function get_data(){
$.ajax({
type: "GET",
url: "get_balance.php",
data: {wherematch: localStorage.login_user},
dataType: "html", //expect html to be returned
success: function(response){
document.getElementById('balance').innerHTML = response;
setTimeout(get_data(),3000);
}
});
}
get_data();
Put setTimeout() function inside the ajax. You will not get freeze because we don't set async as false