Jquery AJAX button call in Umbraco BackOffice - javascript

Hi I just created a simple new option for umbraco backoffice, it is a simple html page which displays a button to click.
Simple form
This button should send an ajax call to an UmbracoApi, but the request never reaches the webapi. Below the Api Code:
API Code
The Ajax call is a simple Jquery Ajax call in the event click of the html button.
I'll appreciate any help you can provide me, in order to complete this ajax call.

I think yor problem is the way you are calling it:
not sure if url casing not same as Controller and action will cause routing failure or not, but might as well make then the same
you action is binding a primitive type, from my understanding of webapi - primitive type will check at querystring otherwise specifically tell it to look at body
more info about this, checkout https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
so base on above two statement, try change your call to:
$("#btnGetData").click(function() {
$.ajax("http://localhost:44302/Umbraco/Api/StripeBackOfficApi/GenerateLockBoxile?date=" + $('#txtDate').val(), {
type: "GET"
}, cache: false, success: function(data, status, headers, config) {
if (data) {
alert("Done!");
}
}, error: function(jqXHR, timeout, message) {
console.log("Error: " + message);
}
});
});

Related

asp.net webservice jquery populate textbox

I want to get 3 values from a web service by providing current URL and current user. My webservice accepts 2 parameter URL and user. Web service works fine.
Now I want to put this 3 values in 3 different textboxes using jquery.in txtOrgCity = city, in txtPin = pin, in txtCountry = country
bellow is code for txtOrgCity
$(document).ready(function () {
$('#txtOrgCity').val({
source: function (request, response) {
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
response(data.d);
},
error: function (err) {
alert(err);
}
});
when I run it gives me [object object] in text box.
How do I define to grab City for txtOrgCity, pin for txtOrgPin, country for txtOrgCountry in response(data.d).?
and do I need to duplicate the same code for other 2 text boxes or any better way.?
Given code is just for some txtbox autocomplete and it works perfectly so I just wanted it to modify a bit for my need. $('#txtOrgCity').val was $('#txtOrgCity').autocomplete
Any help would be appreciated.
--
Thanks
I recommend that you open this up in google chrome. Open up your developer tools (press f12) and, open up resources and select the page you are currently working on. Then use the find box to search for your javascript method which fires the ajax and put a break point inside the success part of your ajax call. Now run your code and wait to hit the break point. Now you can see what is inside your data.d object. Do not resume and keep debugging. Open up your console tab and type data.d. you should see an intelicence option box with all the variables inside your data.d object. You should see the variable for city, pin and country in whatever way you named them when you deserialized your data and returned it as json to your ajax call.
If, for example, you write data.d.city in your console it should write out the corresponding value. The same goes for any other json variable your service passed back to the browser.
With that information it is easy enough to use jquery and do what you want with the data. So in the succes part of your ajax call you can write:
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
p.s. im writting on a phone.
For your example you should not write out the same code two more times. Do not call ajax inside a jquery .val(), that is wrong. Make a new function which handles your ajax, call it from the page load or anywhere you need :
function loadData(//put your user parameter in here if you need){
$.ajax({
url: '../lead_hunter.asmx/GetOrgCity',
method: 'post',
contentType: 'application/json;charset=utf-8',
data: JSON.stringify({ url: "http://srv3.testsrv.com/homepage", user: "testuser#testsrv.com" }),
dataType: 'json',
success: function (data) {
$("#txtOrgCity").val(data.d.city);
$("#txtPin").val(data.d.pin);
$("#txtCountry").val(data.d.country);
},
error: function (err) {
//welldone for handling your error message. Many people neglect this. As a developer that is like coding blindly. At the very least you can console.log(err); if you don't want the user to see
alert(err);
}
});
}
Instead of $('#txtOrgCity').val({})
In your .ready function make the AJAX call first.
Store d.OrgCity, d.OrgPin & d.OrgCountry into some local JavaScript variables. In the Ajax call success use these values to deposit into textboxes like
$('#txtOrgCity').val(d.OrgCity)
You are after JSON.stringify(). So where you specify your .val() You want .val(JSON.stringify());

Call WebMethod in C# codebehind without using a server form in ASPX page

Due to issues with styling, and needing multiple forms on one single web page, I currently have a form that is outside of the normal form with runat=server.
Is it possible for me to still call a WebMethod in the C# codebehind of this web page using ajax? I want to submit the information from this form to the same connection string that I am using earlier in the page, in a different form.
Here is my current code:
$().ready(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
function createJob() {
var txtTestValue = document.getElementById('jobTitle').value;
$.ajax({
// POST signals a data request
type: "POST",
// This directs which function in the c# code behind to use
url: "Account/help.aspx/CreateJob",
// The paramater pageIndex, page number we need to load, to pass to GetCustomers(int pageIndex)
data: txtTestValue,
// Type of data we are sending to the server (i.e. the pageIndex paramater)
contentType: "application/json; charset=utf-8",
// Type of data we expect back from the server (to fill into the html ultimately)
dataType: "text",
// If all goes smoothly to here, run the function that fills our html table
success: OnSuccess,
// On failure, error alert user (aka me so that I know something isn't working)
failure: function (response) {
alert("failure");
},
error: function (response) {
alert("error");
}
});
});
And my WebMethod in the codebehind:
[WebMethod]
public string CreateJob()
{
//rest of my database code here
}
Sorry for the confusion but it's doing everything right up until the ajax code, and then seems to ignore it (and returns that the ajax failed with an error). My code is not reaching the WebMethod and any breakpoints I set in Visual Studio are not triggered in the page header. Thanks in advance for your help!
You need to declare the method as static.
[WebMethod]
public static string CreateJob()
^^^^^
{
//rest of my database code here
}
Another issue is if input[type=submit] is ASP.Net Button control, it will post back to server. You cannot use ASP.Net Server control to make jQuery Ajax call - $.ajax.
// This code won't work if `input[type=submit]` is a server button control
$(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
you need to use regular html input or button control with type=button instead of type=submit.
The webmethod should be static.
[WebMethod]
public static string CreateJob()
{
//rest of my database code here
}

Calling a static method from cshtml file

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?

Ajax/Jquery calling a webmethod/service every 'interval' seconds

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.

ASP.NET AJAX - ScriptManagerProxy and handling html button clicks

I am trying to figure out how to accomplish the following:
Handle client-side click event of button - prevent postback if result of javascript call is false (e.g. onclick="js:return IsThisAllowed()")
Javascript method will return true or false, depending on result of call to generated web service method using ScriptManagerProxy
The code below is simplified down to the main components that I am referring to in this question. I can alert() the return value no problem, but the part I'm having trouble with is how I can return the result of the web service method call back to the button onclick handler? Since the function Finish() is called in a separate thread upon success of what I assume is the XmlHttp.send() call, how can I send the value of the response as the return value of the javascript method? Am I going about this all wrong?
I've used similar code many times before to update the DOM with the return values, such as within a <div>, but never had to worry about capturing the return value and using it within my script.
What I have so far:
.NET web service method (VB.NET):
<WebMethod()> _
<ScriptMethod()> _
Public Function IsAllowed() As Boolean
Return True
End Function
.NET code for the page to generate AJAX web service methods, and html button
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MyWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
<asp:Button ID="_btn" runat="server" OnClientClick="js:return IsAllowed();" />
Javascript
<script type="text/javascript">
function IsAllowed(orderid) {
if (!processing) {
processing = true;
var ws = new MyWebService();
ws.IsAllowed(Finish, Error)
// return TRUE if call to IsAllowed returns true!!!
return false;
}
}
function Finish(result) {
alert(result)
}
function Error() {
}
</script>
You can't do this: the call to the web service is an asynchronous request to the server that immediately returns control to the client - and your javascript is (almost) always going to finish executing before the request completes (most likely before the request is even delivered).
Since you don't know when you'll receive the response from the call to ws.IsAllowed, you need to handle it in your callbacks (Finish and Error).
(This is true whatever AJAX mechanism you're using.)
I'm not familiar enough with ScriptManager-based AJAX to tell you exactly how to do this, but the general idea is that I'd turn it around: instead of canceling an ASP.NET button's click event, I'd only trigger the ASP.NET button if the AJAX call returned true.
Using jQuery, I'd do it by making the AJAX call from a vanilla HTML button (not an ASP.NET web control). In the success handler (the equivalent of Finish), I'd trigger my ASP.NET button (which I'd probably hide) when the return value is true.
Have you considered using jQuery?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "~/WebServices/IsAllowed.asmx/{Method Name}",
data: ('{ whatever data is needed for decision making json serialized }'),
success: function (msg) {
alert(msg);
},
error: function (request, status, error) {
alert(err.Message);
alert(err.StackTrace);
}
});

Categories

Resources