When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project:

wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' )));

As part of testing, I used an $http.get() in Angular:

$http.get('http://localhost/wp-admin/admin-ajax.php',{action:'get_saved_cover'}).then(function(data){
        console.log(data);
    });

The goal of my function was to retrieve and return a list of cars:

add_action( 'wp_ajax_nopriv_get_saved_cover', 'get_saved_cover' );
add_action( 'wp_ajax_get_saved_cover', 'get_saved_cover' );

function get_saved_cover(){
    $cars=array("Volvo","BMW","Toyota");
    return json_encode($cars);
    wp_die();
}

However, when I make the request, all I receive back is data: 0, status: 200, and some other standard responses in an array. It seems like there might be a missing piece that Angular requires or something else causing the issue.

Answer №1

Update the angular http parameter to use "params" instead of "data"

$http({
    url: 'http://localhost/wp-admin/admin-ajax.php',
    method: "GET",
    params: {action: "get_saved_cover"}
}).then(function (response) {
   console.log(response.data);
});

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

Sequelize does not automatically include a junction table in the associated model data

Imagine having two models, User and Event, established in a many-to-many relationship with User.belongsToMany(Event) and Event.belongsToMany(User). Everything seems to be functioning properly until executing User.findAndCountAll({include: [{model: Event}]} ...

Using CSS3 translate will result in children becoming relatively positioned

I am facing an issue with a sidebar that contains 2 divs. <div class="sectionsContainer clearfix"><-- Sidebar --> <div class="leftSection pull-left"> <p>Maor</p> </div> <div class="rightSection pu ...

Changing the old state in React js: A step-by-step guide

I have a collection of Faq elements. Clicking on a question should display the answer for that specific question while hiding all other answers. The issue I'm facing is that even though it displays the answer for the clicked question, it fails to hi ...

Is there a way to dynamically update the text of $ionicPopup's subTitle in Ionic?

I am currently attempting to modify both the value and style of the subText attribute linked to an $ionicPopup within my app. Despite searching extensively, I have been unable to uncover a viable method for accomplishing this task. Is there a way to achi ...

The most effective method for transferring asynchronous data to pages in Next.js

My current directory structure: - components - NavBar - Header - Layout - pages - pages - demo.js - _app.js - index.js // index.js import React from 'react'; import NewLayout from "../../components/NewLayout/NewLayou ...

Ways to retrieve form information from a POST request

I received a POST request from my payment gateway with the following form data: Upon trying to fetch the data using the code snippet below, I encountered errors and gibberish content: this.http .post<any>('https://xyz.app/test', { ti ...

What are the steps to execute a filter operation on a table by utilizing two select box values with jQuery?

I have a challenge with two dropdown menus. One contains names and the other subjects, along with a table displaying information in three columns: name, subject, and marks. I would like to implement a filter based on the selections in these two dropdowns. ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

Reorganizing JSON data with ES6 techniques

I have a scenario where I need to update tire quantities in an array like this: tires: [{ name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct1", quantity: 1 }, { name: "fancyProduct2", quanti ...

What is the method for extracting input from a paragraph in Laravel?

<div class="form-group"> <label for="amount_due" class="col-sm-4 control-label">{{trans('sale.amount_due')}}</label> <div class="col-sm-8"> <p class="form-control-static">Unique text to be added ...

Open the link and input the text into the text box?

Suppose I have the following JavaScript code: <script language="javascript" type="text/javascript"> function addText() { var newText = document.myForm.inputText.value; document.myForm.description.value += newText; } </script> I want t ...

Inheriting Components from Templates

Insight on Motivation There are countless situations where we may require multiple components to share the same functionalities. It is not ideal (and definitely shouldn't be done!) to simply copy child components. This is where the concept of inherit ...

"Troubleshooting the failure of the alert function to work properly when loading content

I am working on a webpage named index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Co ...

nextAuth.js is failing to access the accessToken, returning only the values {iat, exp, jti} instead

Here is the code I am working with: import NextAuth from "next-auth" import CredentialsProvider from "next-auth/providers/credentials" export default NextAuth({ sectret:process.env.NEXTAUTH_SECRET, session: { strategy: "jw ...

Creating an internal network using MVC, EntityFramework, AngularJS, and Breezejs?

Looking to embark on a learning project, I aim to develop a straightforward intranet application (featuring functionalities such as login/logout, user creation, project management, etc.) by incorporating some new libraries/frameworks. However, I am uncert ...

I have created a Joomla Template that incorporates my own CSS through JavaScript. Is there a method to include a distinct version tag to my custom CSS file, such as custom.css?20180101?

My usual method involves adding a unique tag to the css path in the html section, but my template is incorporating custom CSS through Javascript: if (is_file(T3_TEMPLATE_PATH . '/css/custom.css')) { $this->addStyleSheet(T3_TEMPLATE_URL . &apo ...

Attempting to save data to an external JSON file by utilizing fs and express libraries

I've encountered a challenge while attempting to serialize an object into JSON. Despite my best efforts, I keep encountering an error that has proven to be quite stubborn... Below is the code snippet that's causing the issue: APP.post('/api ...

A handy tip for sending a response once a for each loop has finished executing

It is important that Response.json executes only after the foreach loop has completed its execution. var todoarr = (req.body.data) ? req.body.data : undefined todoarr.forEach(function(element) { if(element.done == true) { TodoS ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Tips for dynamically passing parameters to functions in JavaScript?

Looking for a solution to dynamically receive input from the user in my function: divResize = { myDiv:function(width, height) {...} } divResize.myDiv(100,400); I want to make these numbers interactive and changeable based on user input. How can I achie ...