Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Begin Mailchimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
/* Add your own Mailchimp form style overrides in your site stylesheet or in this style block.
   We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll">
<h2>Subscribe</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
<label for="mce-EMAIL">Email Address  <span class="asterisk">*</span>
</label>
<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
</div>
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_aaa7182511d7bd278fb9d510d_01681f1b55" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='ADDRESS';ftypes[3]='address';fnames[4]='PHONE';ftypes[4]='phone';fnames[5]='BIRTHDAY';ftypes[5]='birthday';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->

The above code functions correctly without any issues. However, when attempting to include the same functionality in an Angular application, there are some challenges:

Reference Source: https://gist.github.com/inorganik/846c52550db97454646054270e4f1270

Here is a snippet of the implementation:

app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';

interface MailChimpResponse {
  result: string;
  msg: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
submitted = false;
  mailChimpEndpoint =
    'https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55';
  error = '';

  constructor(private http: HttpClient) {}

  userForm: FormGroup;

  ngOnInit(): void {
    this.userForm = new FormGroup({
      email: new FormControl('', [
           Validators.required,
            Validators.email,
        ]),
    });
  }

  subscribeEmail() {
    this.error = '';


        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'callback').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }
}

View Working StackBlitz here..

The issue arises when implementing the above code in an Angular application, resulting in a 404 error.

Please refer to the network/console tab in the developer tool for more information on the 404 error.

I also noticed that the parameter passed in the URL does not reflect in the query parameters of the network call.

Kindly assist me in making the API URL work seamlessly in the Angular application by clicking the subscribe button.

Take a look at the StackBlitz provided: https://stackblitz.com/edit/angular-jsonp-gfzdr1

Answer №1

Your parameter sending method needs adjustment. Take a look at this functional example for properly submitting the request. Although you may still encounter an error, it will be due to MailChimp notifying you of exceeding the number of processed records.

Functional Example: https://stackblitz.com/edit/angular-jsonp-1qquhy

Answer №2

When adding a URL, make sure to include the "&" symbol at the end. For example, if your URL is: &id=01681f1b55

Don't forget to add the "&" symbol after the URL as shown below: &id=01681f1b55&

If you want to see a working StackBlitz example, check out the link below:

Working version:https://stackblitz.com/edit/angular-jsonp-96dmvh

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

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

Is client-side JavaScript executed prior to server-side JavaScript in AJAX?

I'm curious about how client-side code interacts with server-side responses. I have a lengthy and complex piece of code that triggers a function which in turn executes some server-side code using a HTTPRequest Object, returning a string to the calling ...

A guide on transferring data from JavaScript to HTML and efficiently directing it to a Laravel 5 controller

Recently, I have been exploring different ways to connect Javascript with HTML and interact with PHP. Although I am comfortable using plain PHP to send or retrieve data from a PHP backend, I decided to dive into Laravel5 as my PHP framework. So far, it has ...

Having trouble with Rails 6 Bootstrap 4 Modal staying open after submitting?

Everything is working smoothly with Open Modal, but I am facing an issue with closing the modal. Here are the relevant files: Inside client.haml (the client layout) = link_to t('.mail to admin'), blame_path(@admin), remote: true routes.rb get ...

One of my AngularJS directives seems to be malfunctioning while the rest are working fine. Can you help me troubleshoot

Recently, I've been immersing myself in the job search process and decided to create a website as a sort of online resume while also learning AngularJS. I enrolled in the Angular course on CodeSchool and am slowly building my website to my liking. (Pl ...

Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them. If you want to check out my curren ...

Tips for asynchronously subscribing to an observable from an array in Angular

I am facing a scenario where I have an array containing IDs and I need to subscribe to observables for each ID in a sequential order. I attempted to use a foreach loop but the responses were not in the desired order. Then, I tried to implement a for loop a ...

Amend and refresh information using AJAX technology

My code isn't working as expected when I try to use AJAX to retrieve data from an editable form and update it in the database. Can someone help me find the issue? Below is the code I'm using: <?php $query = db_get_list("SELECT * FROM ...

Monitor the status updates by utilizing APEX.SERVER.PROCESS functionality

Environment: Oracle APEX v5.1.2 with Oracle 12c R2 Database I have created a report based on the columns of a table named MY_TASK. The columns include: TASK_ID (Primary Key), TASK, TASK_STATUS (from TASK_CHECKER.task_status) In addition, I use another t ...

What is the best way to retrieve the parent div's ID with JavaScript and Selenium?

My current project involves utilizing webdriverjs, and I am faced with the challenge of retrieving the parent id of a specific webelement among multiple elements with similar classes. Each element has a different id that gets dynamically generated when a m ...

Issue: $controller:ctrlreg The controller named 'HeaderCntrl' has not been properly registered

I am encountering an error while working on my AngularJS program. I have defined the controller in a separate file but it keeps saying that the controller is not registered. Can someone please help me understand why this issue is happening? <html n ...

Utilize Angular Ag-grid's feature called "Columns Tool Panel" to trigger checkbox events

How can I capture the check/uncheck/change event of side panel columns? I have reviewed the documentation at https://www.ag-grid.com/angular-data-grid/tool-panel-columns/, but couldn't find any information on this. This relates to the Enterprise ver ...

Tips for confirming that one of three checkboxes has been selected in AngularJS

Here is the code snippet for checkboxes: <input name="chkbx1" type="checkbox" ng-model="LoanReferData.Prop1" ng-class="Submitted?'ng-dirty':''" required>Prop 1</input> <input name="chkbx2" type="checkbox" ng ...

extract data from a dropdown menu with playwright

I'm having a tough time figuring out how to select the "All" option in a dropdown menu and extract all the data from that page. I've found some related posts, but they don't quite match my scenario. The "select" element I'm working with ...

retrieve information from the local JSON file

Hi there, I am looking to retrieve data from my JSON file and then display it in HTML. Before that, I want to simply log it in the console. How can I accomplish this task? The JSON file will be updated based on user input. varer.json [{"id":&qu ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...

Enhancing Bootstrap Slider Range with jQuery/Javascript

Currently, I have incorporated the Bootstrap slider into a webpage that features two sliders on a single page. The range of the second slider depends on the value of the first one. It is crucial for me to be able to update the range of the second slider af ...

Navigating to a pre-defined default route in Angular 2 with content

Is there a way to set a default route using the updated RC router? @Routes([{ path: '/', component: Home }]) What if I want to display a page with a non-empty path initially? For example: @Routes([{ path: '/home', component: Home } ...

The Ajax call failed to connect with the matching JSON file

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script <script> function launch_program(){ var xml=new XMLHttpRequest(); var url="student.json"; xml.open("GET", url, true); xml.send(); xml.onreadystatechange=fun ...

Tips for retrieving multiple values or an array from an AJAX request?

Is there a correct way to pass multiple sets (strings) of data back after executing an ajax call in php? I understand that echo is typically used to send a single string of data back, but what if I need to send multiple strings? And how should I handle th ...