When invoking a webservice, the following function returns an error stating "An error occurred when trying to execute the function! [object Object]" which originates from the Ajax

I am new to using web services and I am trying to call a web service from an HTML page. However, I am encountering the following error message: "Hit error fn! [object Object]" and I am unable to send mail to the desired email address. Can you please help me troubleshoot this issue?

function test() {

    var firstName = $('#txtName').val();
    var lastName = $('#txtMessage').val();
    var email = $('#txtEmail').val();

    $.ajax({ 
        url: "http://localhost/ZeroDebt/WsZeroDebtApp.asmx/SendEmailToClient",    
        data: { 
            _fromAddress: JSON.stringify(email),
            _Subject: JSON.stringify("Zero Debt App Invitation Request"),
            _body: JSON.stringify(firstName + ' ' + lastName),
            clientName: JSON.stringify('Dr. Hanoi'),
            clientEmail: JSON.stringify('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3e3d3c1f27262571313a2b">[email protected]</a>') 
        },
        dataType: "jsonp",
        success: function(data) {
            alert(data);
        },
        error: function(error) {
            alert("Hit error fn!" + error);
        }
    });
}

Answer №1

Here is a suggestion for rewriting the code. Please give it a try yourself:

const SENDMAIL_URL = "http://localhost/ZeroDebt/WsZeroDebtApp.asmx/SendEmailToClient";

function test() {
  const firstname = $('#txtName').val();
  const lastname = $('#txtMessage').val();
  const email = $('#txtEmail').val();

  const data = JSON.stringify({
    _fromAddress: email,
    _Subject: "Zero Debt App Invitation Request",
    _body: `${firstname} ${lastname}`,
    _clientName: 'Dr. Hanoi',
    clientEmail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9afbf8f9dae2e3e0b4f4ffee">[email protected]</a>'
  });

  function notify(args) {
    console.log(args);
  }

  function onSuccess(data) {
    notify(data);
  }

  function onError(error) {
    notify("Hit error fn!"); // Important to separate string from Object
    notify(error);
  }

  $.ajax({
    url: SENDMAIL_URL,    
    data: data,
    dataType: "jsonp",
    success: onSuccess,
    error: onError
  });
}

Additionally, it is recommended to store your URL as a constant string to make it easier to maintain and configure all URLs in one place.

Answer №2

Finally, after much searching, I have discovered a solution. The key is to provide the client's email in a format that is not a string. Instead of using "[email protected]", use [email protected]."

The correct approach is as follows: data: { _fromAddress: JSON.stringify(Email),_Subject:JSON.stringify("Zero Debt App Invitation Request"),_body:JSON.stringify(firstname +' '+lastname), clientName: JSON.stringify('Dr. Hanoi'), clientEmail: [email protected] }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process to change the jQuery quiz outcome into a PDF when a user clicks a

I'm currently working on a jQuery quiz project where I want users to be able to download their results in PDF format with just one click. After doing some research, I came across the dompdf library, which allows me to convert HTML to PDF. If you&apos ...

Is there a way for me to retrieve the return value from each of my promises?

Here's a helpful guide on how to efficiently handle multiple ajax requests with a dynamic number of objects. The process involves: var deferredArr = $.map($(".dynaload"), function(el, i) { return $.ajax({ url: $(el).data("loadUrl"), ...

Leveraging Django's JSONResponseMixin for handling AJAX responses

I'm currently using Django in conjunction with AJAX. My goal is to have a javascript file (vote.js) POST data to a Django View, which will then respond with JSON data to be utilized by my javascript's callback function in the HTML. Below is the ...

Vue.js - Error: Module not found: Cannot locate module 'lottie-vuejs'

I've been attempting to integrate lottie-vuejs into my project. After running the npm install command and following the steps outlined here, I encountered an issue. Unfortunately, I received the following error message: Module not found: Error: Can ...

I do not intend for my JavaScript code to be echoed in PHP

I have encountered an issue with an ads script that I saved in my database using a textarea field. However, when I try to echo this script in PHP, it does not work as expected. Below is the script that I stored in the database: <script type="text/javas ...

Using jQuery to exclude the title element within a contenteditable div from selection does not work effectively

Struggling to figure out how to save the content of a contenteditable div to a database using jQuery AJAX. The issue arises with the line page_body: selecting $(".class2").not('h2').html() grabs the title as well, when I only want the rest of the ...

What is the best method for distributing this array object?

I am faced with the task of spreading the following object: const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }]; I want to spread this array object and achieve the following format: form:{ ...

Utilizing ngFor in Angular to iterate through an array and retrieve the count of elements while displaying their

I utilized the following angular functions to display the data: availableLockers = [ { "lockerCode": "L01", "allocStatus": "alloc" }, { "lockerCode": "L02", &qu ...

How do I set up a recurring task every two minutes using selenium webdriver in JavaScript?

I need to test my website by logging in and clicking the refresh button every 2 minutes without closing the browser window. Here is a simplified version of my code: var webdriver = require('selenium-webdriver'); var driver = new webdriver.Builde ...

Incorporate an image upload feature into the current ajax script

Everything in my code seems to work fine, except for image uploading. It successfully inserts all the data into the database. <input type="file" name="image2" class="file" id="imgInp"/> However, after adding the file input type in PHP, an error mes ...

Improving data in a table using ajax and JQuery

I am currently working on updating a table utilizing data from AJAX/JSON. Below is my JQuery code: Adjusted to simplify execution with functions. $(document).ready(function() { //var userid = $( ".migrating" ).data( "userid" ); function ajaxUpda ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

What is the method for accessing an app from a file other than server.js?

I am dealing with two different files: file1.js const app = express(); require('./file1/config/customConfigurations').customSettings() .then((settings) => { app.locals.customSettings = settings; console.log(app.locals.customSettings) ...

Integrating redux-form with the react-widgets DateTimePicker component

I am currently working on a project using ReactJS with Redux and I am trying to incorporate a form similar to the one shown in this example: Most of the components are working well, but I am encountering an issue with the DateTimePicker due to the momentL ...

Using asynchronous method calls to create arrays in ES6

In my current task, I am working on completing the following method: collectAllResults: function (callback) { this.getTotalCount((count) => { // the count typically is 5 let results = [] for (var i = 0; i < count; i++) { th ...

Exceeded server capacity while attempting to extract pricing information from a search bar

Thanks to some guidance from the Stackoverflow community, I successfully developed a scraper that retrieves a list of part numbers along with their respective prices. Here is an example format of the data retrieved: part1 price1 part2 price2 ... .. ...

Having trouble importing Tone.js in your Next.js project?

Having trouble importing Tone in my Next.js project. Despite having Tone as a dependency, I face an issue when trying to run import * as Tone from 'tone'. Next.js shows an error stating it can't locate the module node_modules/tone/build/esm/ ...

Having difficulty manually concealing the launch image on the physical device

When testing my trigger.io app on the Android simulator or my Nexus phone, I can manually hide the launch image through code successfully. However, when running the app on the iOS simulator, the launch image remains visible. Additionally, when debugging di ...

Exploring the possibilities with JavaScript options

I am currently working on a project that involves a dropdown list... to complete unfinished sentences. Unfortunately, I am facing an issue with a message stating Uncaught TypeError: Cannot read property 'options' of null Below is a portion of m ...

"Disabling the promise manager in selenium-webdriver: A step-by-step guide

According to the information provided on https://code.google.com/p/selenium/wiki/WebDriverJs#Promises, the selenium-webdriver library utilizes an automatic promise manager to streamline promise chaining and avoid repetitive tasks. However, there are situa ...