ajax push data to backend method

Brandon R asked on January 10, 2019 22:31

I am building a custom webpush notificaiton. I am getting the token that the service worker creates then using ajax to push it to my back end.

My issue is the the response is always 500 and it never reaches a break point. Ideally I want to reach the method that is in my dedicated project not my cms project however below is the code just to get the reponse to the back end in the Old_App_Data.

Thank you!

Relavent code in my javascript webpart.

   .then(function(token){
        $.ajax({
       type: "POST",
       url: "Notfications.aspx/getToken",
       data: token,
       dataType: 'json',
       contentType: "application/json; charset=utf-8",
       success: function (result) {
          alert("Result: "+ result );
       },
       error: function (result) {
            alert("Error try again");
       }
   });

code in my soultion

[assembly: RegisterCustomClass("MyClassName", typeof(getTokenAjax))]
namespace CMSApp.Old_App_Code
{
    public class getTokenAjax
    {
        [WebMethod]
        [ScriptMethod]
        public static string getToken(string webtoken)
        {
            var x = webtoken;
            return webtoken;
        }
    }
}

Correct Answer

Suneel Jhangiani answered on January 11, 2019 14:05

The code isn't getting hit because you are using the URL "Notfications.aspx/getToken" and hence it is trying to load from there.

In your custom project create a new Page and inherit from the CMSPage base class. You can then access the WebMethod by using the URL of the Custom Page ie. "/CMSModules/CustomProject/Pages/WebMethods.aspx/getToken" - For the example the page is created under a Pages sub-folder of the CustomProject module.

I believe the Strands Recommender module follows this pattern, so would suggest you take a look at that.

0 votesVote for this answer Unmark Correct answer

Recent Answers


Brandon R answered on January 11, 2019 21:34

This worked, thanks much! I will have to recreate my module now because it was seprate project. Thanks much!

0 votesVote for this answer Mark as a Correct answer

Brandon R answered on January 14, 2019 21:05

Suneel Jhangiani the web method is only accessible when I am logged in and throwing a 401 error for public users. Is there a way to get around this?

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.