I have a ASP.Net web app with jquery implemented on the client side. The client side jquery script makes an asynchronous call to a web method in the server side code. The call returns the status open record(active/inactive) which jquery uses to update the user. The goal is to have jquery repeatedly call the server, once open record is inactive, then we need to display message to user so that you're no longer associated to this record..I set up the TimeInterval in one off the HiddenFieldValues and passing to the Jquery/ajax Function.
This function is written In a separate JavaScript file and it has been referred in my ASPX page Script Manager. I have to pass 'interval' from the server side, which is configured in the .config file.
function myWebServiceFunction(val1, val2, val3, interval) {
$.ajax({
type: "POST",
url: "/Application/WebServices/MyService.asmx/CheckFunction",
data: "{'val1':'" + val1 + "','val2':'" + val2 + "','val3':'" + val3 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
debugger;
var obj = function callbackfunction() {
myWebServiceFunction(HealthCarrierShortName, authID, networkID, interval)
}
if (!msg.d) {
window.setTimeout(obj, interval);
}
else {
// Still need to implement how to display to user if the record is not long associated to that user. help me in this too
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('AJAX failure');
}
});
}
In my Server Side, I Used RegisterStartUpScript at the end of Page_load method and calling that JQuery Function
ScriptManager.RegisterStartupScript(Me.Page, Page.GetType(), "AuthLockPolling", " myWebServiceFunction('" + val1HiddenField.Value + "','" + val2HiddenField.Value + "','" + val3HiddenField.value+ "','" + val4HiddenField.value+ ");", True)
But it is not working properly(Don't know exactly the reasons). My Jquery function is not being called at all. I testing by placing debugger into my script and it is not been hit.
Still need to implement how to display message to user if the that record is not long associated to that user like in a alert window/pop-up window. Please help me in this part too.
Please Advise me what went Wrong and How to solve this. Thanks In advance!
How to solve this:
RegisterStartupScript can be confusing (ask me how I know!). Are you using this on a page that uses partial-page updates (i.e., has UpdatePanel controls)? If not, you should use the method in the ClientScriptManager (instead of ScriptManager) class.
If it is used on a page with partial-page updates for a control that's inside an UpdatePanel, the first parameter should be a control within the UpdatePanel, rather than the Page.
And a debugging tip: Test by passing in JavaScript code that's drop-dead simple, like alert('Hello, World!');. This can help you tell if the problem is in the RegisterStartupScript call or in your myWebServiceFunction function.
Finally, here's the Microsoft documentation: https://msdn.microsoft.com/en-us/library/bb310408(v=vs.110).aspx. Because there are methods of the same name in different classes, read the documentation verwy, verwy, carefulwee.
Related
I am working inside of an Oracle package. I am trying to use an AJAX call to call a procedure from a button click. The ajax call is inside of a function. I am not getting any syntax errors from Oracle or when I'm using the browsers debug mode so I'm not sure what the problem is. Function is below.
htp.p('
function ApplyTest(_ht) {
var _inst = "";
var _pidm = '||v_web_pidm||';
var _inst = document.getElementById("Test").value;
alert("Heat Ticket value is: " + _ht);
alert("the instance is: " + _inst);
var resp = confirm("Are you sure you want patch applied to TEST8?");
if (resp == true) {
alert ("user pidm is: " + _pidm);
return $.ajax ({
type: "POST",
cache: false,
dataType: "json",
url: "gyapatch.p_update",
data: {"v_instance" : _inst, "v_ht" : _ht},
success : function(data) { alert("success"); }
});
alert("Got here");
alert("value: " + _inst);
window.location.reload;
alert("got to the end");
} else {
return;
}
}
');
code for the button is:
<button name="TestApply" id = "Test" onclick="ApplyTest('||val_patch.heat_ticket||')" type="button" value="T">Apply to TEST8</button>'
When I try to return the ajax call nothing is happening and I can't even reach the "Got Here" alert. When I remove the "return" keyword, I can reach the alerts but either way, nothing is happening. GYAPATCH.p_update is the package/procedure I wish to have executed when this is ran
I'm not sure what the problem is. Any help on this would be greatly appreciated. Thanks in advance.
So after a couple of hours, I had figured out the problem. This was more of a learning lesson as the issue was pretty simple. I needed to remember that I was working inside of an Oracle database AND also using WebTailor. The code posted above is correct. It turns out that the procedure I was trying to call (p_update) was not registered.
WebTailor allows you to build web applications utilizing Banner. In WebTailor, any pages that are used (usually stemming from a package.procedure), need to be registered or else they are not recognized.
I found this while debugging. Under the Network tab in my debugger, I noticed that when I click my button, I am getting a 404 error when my package.procedure is called. So I then realized it couldn't find my package and then proceeded to check if it was registered. This was a simple, silly error on my part. I am grateful for the feedback, but this will probably serve as a learning lesson or reminder to anyone trying to use ajax while working with Banner data.
I'm trying to work on a clickable DIV from some vertical tab panel. What I want is when clicking on a specific DIV call a static method to do some tasks, so I did this:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li onclick="myEvent()">Tuttle</li>
then, my JavaScript code:
<script>
function clickEvet() {
alert("alert test message");
#MyProject.myMethod()
}
</script>
Calling the function "clickEvent()" works. The problem is that #MyProject.myMethod() is called no matter what, in other words, #MyProject.myMethod() is being executed as soon the page loads. I want it only when I click on my div.
This is from a cshtml file and I'm using .net 4.5
SOLUTION:
I'm editing my question to post the answer for future references...:
Thanks to other comments I finally understood how to work with Ajax and make it work. Here is the solution:
<script>
function vaxGUID() {
$.ajax({
type: 'POST',
url: "/VAXBean/bmx",
data: '{"Name":"AA"}',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
success: function (data) {
bmx = "http://www.vitalbmx.com";
$('a.varURL').attr('href', bmx);
GUID = data;
alert("Good response - " + data + " - " + bmx);
},
error: function (data, success, error) {
alert("Error : " + error);
}
});
return false;
}
</script>
With this Ajax method I'm making the call to some static method in the background
I want it only when I click on my div. <= When you click on the DIV that is being done in the browser after the request has been sent. There is no way for the browser to call directly back inside a method in your application. The HTML has already been generated and sent by the server in the request to the client and that is where that communication cycle stops.
If you want a click (or any other event) to do something specifically on the server you need to do one of these standard actions that are used to communicate back to the server.
Create an AJAX request back to your MVC Controller to get data (or whatever).
Create a link (standard url)
Create a form post back
And of course the #MyProject.myMethod() executes every time your page is rendered because your razor view is a code file that is being interpreted line by line so it can be rendered and sent to the client that requested it. What would be valid here is if myMethod output some javascript or something that the browser could understand and do something with, that is what would be expected.
You can't do it. All # (Razor) expressions is resolved during page rendering on server. That's why you method is called.
Probably, you need to make an Ajax call.
Look for a more detailed explanation here:
How do I call a static method on my ASP.Net page, from Javascript?
I'm pretty much a complete beginner at javascript and jQuery, so please bear with me.
I have a Spark-API running, and a web front-end that uses it through ajax calls.
I'm trying to call this function
function getSpotifyURL(ms, name) {
$.ajax({
url: "http://localhost:8081/playlist?ms=" + ms + "&name=" + name,
dataType: "json",
})
.done(function( data ) {
console.log(data);
})
}
The method is placed outside of:
$(document).ready(function() {
The reason it's outside is that I get an error upon calling it saying it's "undefined" if it's within $(document).ready.
The Spark-method is supposed to return a String (and it does when you try it directly through the browser).
The way I'm calling the getSpotifyURL-method is through a html button's "onclick". Like this:
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
The problem:
The .done-block does nothing in my code. Nothing is printed to console.
What I've tried:
Using "success" within the ajax part instead of .done
Placing the function with $(document).ready(function() { ... }
I understand that you might need more information to be able to help me, but I'm not sure what else information to provide right now. So if there's something you need to know, just ask.
Ideas?
SOLVED!
I'm a dumb person and forgot to remove dataType: "json", as the Spark-server in this instance returned a String, not a json object. Anyway, thanks for your input everybody. Much appreciated.
I think the problem is when you bind your function onclick. There is a syntax error, as you can see on the browser console
function getSpotifyURL(ms, name) {
console.log("http://localhost:8081/playlist?ms=" + ms + "&name=" + name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
I guess data is a variable, so you should call it without brackets
<a href='#' onclick='getSpotifyURL(data[i].duration, data[i].destination)'>Create Spotify playlist for this trip</a>
The reason you are getting undefined method when you are placing the function inside the $(document).ready(function() { ... }); call is because you are using the onclick attribute to call the function. $(document).ready(...) is not in global context as to where you onclick attribute is, and would therefore not recognize it from within the document.ready resulting in your undefined method error.
When sending your Ajax request, you also need to specify a type of request (GET or POST) that you are making. I would also suggest restructuring your ajax call to look more like #Moe's answer.
If you want to get it inside the DOM, consider doing the following:
HTML
<!-- I gave the link a class name and removed the onclick= attribute -->
Create Spotify playlist for this trip
JavaScript
$(document).ready(function() {
// I gave the <a> link a click handler
$(".create-spotify-playist").on("click", function(e) {
e.preventDefault(); // prevents link from requesting
var ms = ?? //I'm not sure where you're getting your parameters from,
var name = ?? //so you will probably have to figure out how to get those in here yourself
$.ajax({
type: "GET",
url: "http://localhost:8081/playlist",
data: { ms: ms, name: name },
success: function(data) {
console.log("Success: " + data);
},
error: function(data) {
console.log("Error: " + data);
}
});
});
});
I gave the link a click handler and placed it inside the $(document).ready, and by removing the onclick attribute from earlier, it can now be triggered from inside $(document).ready.
At the moment I have multiple forms, and am writing the JavaScript out very simply. I want to create a simple comment system using the following AJAX, but am running into troubles that I cannot sort out..
The AJAX call looks like this:
var dataString = 'commentauthor=' + commentauthor + '&parentid=' + parentid +'&linkid='+
linkid + '&comment=' + comment + '&location=' + location;
alert("check : " + dataString)
$.ajax({
type: "POST",
url: "comments/addcomment.php",
datatype: "html",
data: dataString,
success: function(){
alert('comment added!');
},
error: function(){
alert('failed adding comment!' +dataString);
}
The dataString at all times pulls out the correct information from the forms. Also, the PHP the AJAX is sending it to already works when it's set as the forms action, and all the $_POST[''] names match up.
I've been looking around but can't figure it out. Am I encoding the data wrong or something? The PHP side of things doesn't even get to the AJAX response, so it's got to be just failing to send right?
Also, is there a better way to check JavaScript errors? I've been using the google chrome console but half the time when something goes wrong it doesn't through up an error anyway (like this time)
Is addcomment.php printing anything out? I vaguely remember having a similar problem which was because the PHP file wasn't returning anything. If it isn't, try this before the end of the file:
echo 1;
I am attempting to interface with the Google Maps API marking locations based on latitude and longitude data. I would also like to get time zone information based off of this latitude and longitude. To do this, I am using another external API that takes in the latitude and longitude and returns the time off-set. My issue, however, is that this time data returns after the page is loaded.
What is the best way to then add this information to the page after the page has loaded for the user? I started out thinking about using postback, but after doing some research, I don't think that's the right method for my problem.
In browsers, JavaScript allows you to contact a server after a page is loaded. This is known as an asynchronous request, the first 'A' in 'AJAX' (Asynchronous Java and XML).
The X can be a bit of a misnomer, as people will happily pass whole chunks of HTML, or JSON (AJAJ?) or other forms of data instead of XML through this mechanism.
I would always use a framework (my personal choice being JQuery) to perform the operation, as the framework writers will have done the job of making it all work cross-browser for you.
You could use this:
http://api.jquery.com/jQuery.get/
or if the return data is JSON,
http://api.jquery.com/jQuery.getJSON/
This function, part of JQuery, will execute a callback function once the data is loaded. Your callback function can then use the JQuery selectors to find and update the elements in question.
If you update your question with specific code examples I can be more specific with my response.
Edit after seeing code example:
It looks like your problem is actually one of working out the order of code execution. Your code follows this pattern (somewhat simplified and a touch rearranged):
var startTimeZone;
jQuery(document).ready(function($) {
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=SecretKey&q=" + start_locale + "&format=json",
dataType: "jsonp",
success: function(parsed_json) {
startTimeZone = parsed_json.data.time_zone[0].utcOffset;
console.log("Callback: " + startTimeZone);
},
error: function(parsed_json) {
}
});
});
console.log("Main:" + startTimeZone);
Firstly, there isn't a need to wrap the ajax command in the document ready callback - that only needs to be done once for the whole of your code, around wherever the entry point is. (I assume that it was an attempt to delay the execution until after the following code.) (There is more to learn here as well - JQuery gives you more than one event to help initialise your code and work with the DOM, see window.onload vs $(document).ready() for a brief description)
If you ran the snippet above, you'd find that the console log would probably show:
Main: Undefined
Callback: [StartTimeZone]
where [StartTimezone] is the response from the server. The ajax command is asynchronous, meaning it goes off and does its thing, taking as long as it needs, leaving the code after it to run as if nothing had happened. When it's finished it calls the 'success' or 'error' callback appropriately. So the 'main' console log is called before the variable has been defined. After that, the callback is hit by the response to the ajax call - so the StartTimeZone is output.
If you're new to callbacks or used to a language that doesn't support them or use them very often (like PHP), you may expect or want the code to pause at the ajax call, then run the callback, then carry on with the rest of the code. Obviously this isn't the case.
In this simple situation I would simply move the code to process the timezone into the callback, but your code has a further wrinkle - you need two values, which you seem to need to retrieve with separate calls.
In this case, we need to make sure we have both values before we run the code that uses them. How can we do this?
A simple solution would be:
var startTimeZone;
var endTimeZone;
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=SecretKey&q=" + start_locale + "&format=json",
dataType: "jsonp",
success: function(parsed_json) {
startTimeZone = parsed_json.data.time_zone[0].utcOffset;
getEndTimeZone();
},
error: function(parsed_json) {
//console.log("Error: " + parsed_json);
}
});
function getEndTimeZone() {
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=SecretKey&q=" + end_locale + "&format=json",
dataType: "jsonp",
success: function(parsed_json) {
endTimeZone = parsed_json.data.time_zone[0].utcOffset;
console.log(endTimeZone);
processTimeZones();
},
error: function(parsed_json) {
//console.log("Error: " + parsed_json);
}
});
}
function processTimeZones() {
var timeZoneDifference = (endTimeZone * 3600000) - (startTimeZone * 3600000);
// Do the rest of your processing here
}
Functions aren't run until they are called. Also, functions in JavaScript have access to the variables in their containing scope (this means that the functions have access to startTimeZone and endTimeZone, which are defined outside the functions themselves.)
The code above will call getEndTimeZone on success of the first ajax call. getEndTimeZone then uses an ajax call to get the end time zone, then calls the process function on success. This function definitely has access to the variables you need.
Of course, we're waiting in a queue now for two requests to be processed. We could speed things up a little by calling both at the same time, calling the process function with both, then figuring out if we have the data we need before doing the processing:
var startTimeZone;
var endTimeZone;
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=SecretKey&q=" + start_locale + "&format=json",
dataType: "jsonp",
success: function(parsed_json) {
startTimeZone = parsed_json.data.time_zone[0].utcOffset;
processTimeZones();
},
error: function(parsed_json) {
//console.log("Error: " + parsed_json);
}
});
$.ajax({
url: "http://www.worldweatheronline.com/feed/tz.ashx?key=SecretKey&q=" + end_locale + "&format=json",
dataType: "jsonp",
success: function(parsed_json) {
endTimeZone = parsed_json.data.time_zone[0].utcOffset;
console.log(endTimeZone);
processTimeZones();
},
error: function(parsed_json) {
//console.log("Error: " + parsed_json);
}
});
function processTimeZones() {
if (startTimeZone != undefined && endTimeZone != undefined)
{
var timeZoneDifference = (endTimeZone * 3600000) - (startTimeZone * 3600000);
// Do the rest of your processing here
}
}
Whichever ajax call returns first will call the process function. However, one of the variables will be undefined so the if condition will fail and the function will silently return. When the second result comes in, both variables will be set. Now the if condition will be met and the processing code will run.
There are 1001 ways to skin the proverbial cat, but these should hopefully get you started using the callbacks effectively.
Of course, all this is ignoring the fact that you've put the ajax calls in a for loop. Things could get funky if each iteration of the processing you need to do is dependent on the order it happens - the ajax calls could return in potentially any order. As you're plotting a route, this may well be the case.
If so, you could split your code into two phases - a loading phase and a processing phase. Run all the callbacks in the loading phase, then when you have all the data move to the processing phase and place the markers on the map. You could store the data in an array of objects.
There are a few ways to detect the end of the loading phase. One would be a counter that you increment every time you make an ajax call and decrement every time you get a success. You'd be able to create a loading progress bar using the same counter.
Also you could display a message to the user if any of the calls failed, with a link to restart the process. (Trivially this would reload the whole page, but you could restart the loading stage.)
HTH. By all means shout if you need further help.