Why does my POST request result in [object Object] being returned?

I am just starting to learn AngularJS and I am unsure if my POST request is functioning correctly. After making the request, I am receiving an [object Object] response. What does this error indicate? Could it be related to an issue with the form?

//Activity controller
.controller('ActivityCtrl', function($scope, $rootScope, $state, $ionicLoading, $ionicScrollDelegate, PostService, $http, AuthService) {
    var user = AuthService.getUser();
    $http.get("http://hannation.me/api/buddypressread/activity_get_activities_grouped/?userid=" + user.data.id)
    .success(function(data) {
      $scope.activities = data.activities;
    });

  $scope.addActivity = function(){    
    //    
    var dataObj = {
        new_activity : $scope.new_activity
    };  
    $http.post('http://hannation.me/api/userplus/activities_post_update/?key=57f211a0354d7&cookie=' 
      + user.cookie + '&content=' + dataObj).success(function(data, status, headers, config) {
      $scope.message = data;
    });

    $scope.new_activity='';
  };
})
 <form  class="row">
      <div class="col col-80 content col-center">
        <input class="new-comment-message" type="text" placeholder="Leave a comment..." ng-model="new_activity"
         name="new_activity"></input>
      </div>
      <div class="col col-20 button-container col-center">
        <button class="button button-clear send" type="submit" ng-click="addActivity()">
          Send
        </button>
      </div>
    </form>

Answer №1

First and foremost, it is crucial to utilize the params property for query parameters instead of the deprecated success method in AngularJS. By using params, you can ensure that your query parameters are properly sanitized for use in a URL, as outlined in the encodeURIComponent() documentation.

$http.get('http://hannation.me/api/buddypressread/activity_get_activities_grouped/', {
    params: { userid: user.data.id }
}).then(function(response) {
    $scope.activities = response.data.activities;
});

Additionally, according to this documentation (assuming it is accurate), it is recommended to use a GET request instead of a POST request. Furthermore, the content field seems to require a string, so your second request should be structured like this:

$http.get('http://hannation.me/api/userplus/activities_post_update/', {
    params: {
        key: '57f211a0354d7',
        cookie: user.cookie,
        content: $scope.new_activity
    }
}).then(function(response) {
    // Please note that the documentation does not specify if there will be a response
    console.log('response data', response.data);
});

Answer №2

The answer is right there in your question. Make sure you include the object in your message like this:

 $http.post('http://hannation.me/api/userplus/activities_post_update/?key=57f211a0354d7&cookie=' 
  + user.cookie + '&content=' + dataObj).success(function(data, status, headers, config) {
  $scope.message = data.message;
});

Here, I have set one of the received values from the post request. To figure out the values in your response object, log your response object and assign the appropriate value to your $scope.message.

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

"Error: The angularjs code is unable to access the $http variable within

$http({ url: "php/load.php", method: "GET", params: {'userId':userId} }).success(function(data, status, headers, config) { $scope.mydata = data; mydata = data; }).error(function(data, status, headers, config) { }); It's puzzling why ...

NodeJS: Increasing memory consumption leads to system failure due to recursive scraping

Currently, I am utilizing a GET URL API in NodeJS to extract various data by looping through the months of the year across multiple cities. For each set of parameters such as startDate, endDate, and location, I invoke a scrapeChunk() function. This functio ...

Guide on converting arrays and sending this information in Node.js

I managed to retrieve quiz data and now I want to enhance it by mapping each answer to its respective quiz. I have a feeling that I should use something like forEach.push, but I haven't quite figured out the exact method... const API_KEY="https: ...

The Angular controller function is failing to execute properly, resulting in the following error message: [ng:are

After successfully creating a basic example without an external script file, I encountered an issue while working on my demo. The problem arises when I try to use a controller in the 'script.js' file and it does not seem to work as expected. Bel ...

Preventing Vue.js SPA from accessing cached version when JWT expires: the solution

I'm encountering an issue with my Vue.js / Express application that I can't seem to resolve. Here's how the process unfolds: An unauthenticated user logs into the app and is presented with the login page. Once successfully authenticated, t ...

Exploring Vue.JS with Staggered Transitions and Enhancing User Experience with Loading More

The VueJS Guide offers a clever method for using the item's index to create a delayed transition for the items in the data set. You can learn more about it here. While this approach works great when the data set remains static, I'm encountering a ...

Reactivity in Vue not responding when listening from a different object

Can someone help me understand why my Vue object is not reactive to changes in another object? See the code snippet below. exampleObject = { exampleProperty: null } exampleObject.update = function () { this.exampleProperty = 'updated data&apo ...

"After the document is fully loaded, the Ajax post function is failing to work

I am looking to trigger an Ajax call once my document has finished loading. Here is the code I currently have: <script> $(window).bind("load", function () { getCategories(); }); </script> <script> ...

Preventing pop-up windows from appearing when triggered by a mouse click event

I am looking for a solution to trigger a popup window when a user right-clicks on a specific area. Here is the current code I am using: $("#popup").bind('mousedown', function(e) { var w; if(e.which==3) { w=window.open('link& ...

Google Maps introduces a new feature that creates a blur effect on

Currently, I am utilizing the sample code provided below to superimpose an element on a Google map. <!DOCTYPE HTML> <html> <head> <title>Google Map Test</title> <style> html, body { margin: 0; ...

Getting Errors When Retrieving Data with Apostrophe Symbol ' in Node.js

I am currently developing a Next.js API page to extract data from a series of URLs. Interestingly, the URLs containing an apostrophe character ' fail to return any data, while those without it work perfectly fine. Surprisingly, when I execute the same ...

Optimal placement and size for the slick slider

I am new to CSS and currently experimenting with the Slick slider on a project: My setup involves a div container that spans 100% of the width of the page. Inside this container, there is another div (housing the slider) that takes up 80% of the width. D ...

React component unmounts but listener remains attached

After developing a SPA using react.js, I have incorporated react-router-dom, react-redux, and various other modules. The routes defined in my application: const allRoutes = [ { path: "/Intro", name: "Intro", component: Intro }, ...

Enhancing nouislider jQuery slider with tick marks

I have integrated the noUIslider plugin () into one of my projects. I am seeking guidance on how to display tick marks below each value on the slider. This is the current initialization code for the slider: $slider.noUiSlider({ 'start': sta ...

React fails to trigger a re-render despite updating the state following an API call

Recently, I started working with React and attempted to retrieve data from my API. However, changing the state does not trigger a re-render of the component. Inside the useEffect function in my component, I have code that fetches the API and then sets the ...

Change the attribute to read-only upon modification of the dropdown value

I have a dropdown menu with four options. My goal is to make the "number" input field readonly if the user selects either "option3" or "option4" from the dropdown. <select id="dropdown"> <option value="option1">option1</option> ...

Sort by characteristics of embedded array - Knockout

I'm struggling with filtering a nested array using Knockout. My goal is to filter the array by both 'tag-names' and 'name'. For example, searching for 'whal' should display all objects that contain a tag with that name ...

Encountering a client-side exception while deploying Next.js with react-google-maps/api on Vercel

Everything was running smoothly with my next js app during development and build phases. However, upon trying to deploy it on Vercel, I encountered an error when calling the page that uses my mapView component: An application error has occurred: a client- ...

During the rendering process, a referenced computed property is not defined on the instance

Description: In my child component, I am working with an array called expenseButton that is passed as props. The array contains objects with values which I need to calculate the sum of using the array.reduce() method. Issue: While I can successfully get ...

How to retrieve JSON data in Angular.js

I'm having trouble accessing a json file in angular.js with the code below. I keep getting an error message and could really use some help! Here is my module : angular.module("demoApp", ['demoApp.factory','demoApp.controllers']); ...