Issue with sending data to the server via API using AngularJS controller

I am a beginner in angular js and I am attempting to POST data to the server using an API that I have created:

 function addmovie_post() {

 {
    $genre = $this->post('genre');
    $cast = $this->post('cast');    
    $director = $this->post('director');
    $title = $this->post('title');
    $price = $this->post('price');
    $image = $this->post('image');

    }
{
    //checking for empty parameters

    if(empty($title) || empty($cast) || empty($genre) || empty($image) || empty($price) || empty($director))
     { 
            $info->status = 'failure';
            $info->error->code = 13;
            $info->error->text = 'one or more parameters missing';
            
            $this->response($info, 400);
    }
}
{   // checking for duplicate record
        $this->load->database();
        $sql = 'select count(id) as records from movies where title = "'.$title.'" and cast = "'.$cast.'";';
        $query = $this->db->query($sql);
        $data = $query->row();
        if ($data->records == "1") {
            $info->status = 'failure';
            $info->error->code = 18;
            $info->error->text = 'duplicate record';
            $this->response($info, 400);
        }
    }
$this->load->database();
$info = array('id'=> null, 'title'=>$title, 'cast'=>$cast,'genre'=>$genre, 'image'=>$image, 'price'=>$price,'director'=>$director );
$this ->db->insert('movies', $info);
$data->title = $title;
$data->cast = $cast;
$data->genre = $genre;
$data->price = $price;
$data->image = $image;
$data->director = $director;
$data->message = 'The movie has been added';
$this->response($data,201);
}

The API is functioning correctly. The code implementation with HTML in Angular seems to be error-free as no errors are displayed in the console. However, the data is not being sent through successfully and console.log does not show any data.

  var app = angular.module('postapp', []);

   app.controller('MyCtrl', function ($scope, $http) {

 var formData = {
 title: "default",
 director: "default",
 cast: "default",
 genre: "default",
 image: "default",
 price: "default"
  };


 $scope.submitForm = function() {

 $http({

    url: "http://creative.coventry.ac.uk/~4078078/moviereviews/v1.0/index.php/movie/addmovie",
    data: $scope.form,
    method: 'POST',
    headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}

}).success(function(data){

    console.log("OK", data)

}).error(function(error){"ERR", console.log($scope.error.error)})
 };

  });

HTML:

<div ng-app="postapp">

    <form name="formData" ng-submit="submitForm()" ng-controller="MyCtrl">

        title:    <br/><input type="text" ng-model="form.title">    <br/><br/>
        price: <br/><input type="text" ng-model="form.price"> <br/><br/>
                    genre:    <br/><input type="text" ng-model="form.genre">    <br/><br/>
                    image:    <br/><input type="text" ng-model="form.image">    <br/><br/>
        cast:    <br/><input type="text" ng-model="form.cast">    <br/><br/>
        director: <br/><input type="text" ng-model="form.director"> <br/><br/>

    </form>
 </div>

Answer №1

Try taking a risk. Delete the action from your controller and test if it still functions.

Furthermore, this will prevent the default behavior (such as form submission to the server and page reload), but only when the form does not have action, data-action, or x-action attributes.

Another potential issue could be related to cross-domain problems. Check if it works with a local URL instead.

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

Learn how to extract an ID created with AngularJS using JavaScript

I have a piece of code that generates multiple divs using ng-repeat and assigns each one an id based on a specific value. <div ng-repeat="item in $scope.items"> <div id="ajs-{{item.title}}">{{text}}</div> <script> v ...

Grunt: Can you explain the concept of recursive templates?

Hey there, I'm new to using Grunt and I've run into a puzzling issue with recursive templates. Let me provide you with a concrete and straightforward example: var path = require('path'); module.exports = function(grunt) { grunt.init ...

How can I identify where a Mesh and Particle System intersect in Three.js?

I have a unique setup where I have a particle system utilizing sprites, housed in an Object3D akin to the "interactive / points" example from three.js. Additionally, I have a simple sphere mesh that tracks my cursor's movements. Check out the example ...

Inject JavaScript Object Information into Bootstrap Modal

After iterating through each object and assigning its data to an individual div along with a button, I encountered an issue. When testing the buttons, I noticed that only the last object's data was displayed in all of the modal windows. Any suggestion ...

Having trouble with the functionality of a Chrome extension content-script JavaScript that is set to run at document_end

Currently, I am in the process of developing a Google Chrome extension that is designed to hide the "news" section located on the right-hand side of Facebook, along with the ads displayed on the right side. Additionally, the background color is meant to be ...

How can you access the URL of a resource action in Angular?

In my Angular application, I have created a resource named 'Files' with the following definition: app.factory('Files', function($resource) { return $resource('/api/accounts/:account_id/sites/:site_id/files/:file_id'); }); ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

(Original) redirect from specific url / url detection New text: "Redirection

Sorry for the long and confusing question, my apologies for wasting your time. I am still learning programming and what I really wanted to ask is "how can I retrieve a GET parameter using JavaScript?" Apologies for any inconvenience. ...

Tips for executing multiple asynchronous calls simultaneously within a nested map function

I am facing a scenario where I have an object with nested arrays of objects which in turn contain another set of nested arrays. To validate these structures, I have an asynchronous function that needs to be executed concurrently while awaiting the results ...

When using JSON.Stringify in a React App, it only displays the first item and the length of the object instead of all the other items

Working on a React App, I encountered an issue while trying to convert an array to JSON and send it to the server. My approach was like this: console.log(JSON.stringify(mainArray)) I anticipated seeing output like this during testing: "breakfast": { ...

What are the best practices for securely using JSON.stringify in JavaScript?

When I use JSON.stringify on a string that includes <script> tags, the script tags somehow escape and show up in the body of my document, causing unexpected results with the "injected" data. I'm puzzled by how they manage to escape, considering ...

Is there a way to retrieve postmessage data from React?

I am attempting to embed a React URL within an iframe in my JSP project. Here is the code snippet from the sender side: <iframe id="eda" style="display: none;" src="http://myhost:3000/" width="100%" heig ...

What steps can be taken to resolve the vulnerability in webpack-pwa-manifest?

Looking for solutions to address the [email protected] and minimist vulnerability. I attempted removing node/modules and package-lock.json, followed by a fresh npm installation, but the issue persists. Any suggestions would be greatly appreciated. Scr ...

Exploring the functionality of promises in JavaScript

Currently, I am using the most recent version of Angular. The code snippet I've written looks like this: $q.all({ a: $q.then(func1, failHandler), b: $q.then(func2, failHandler), c: $q.then(func3, failHandler), }).then(func4); Is it guaranteed ...

Using AngularJS to add external scripts to partials with ng-include

Why won't my main javascript files (located in index.html) work in the partials (such as page1.html)? For example, jQuery and syntax highlighting scripts are not functioning properly when I click on my menu items. HTML CODE: <div data-ng-controll ...

Ways to activate an event with select2

Hey there! I have a unique setup on my selling item page with select tags. The first select tag is created using HTML, while the others are dynamically added using jQuery when the user clicks on an "Add More" button. <select id='code0' onclic ...

Need to `come back` multiple times

I am facing an issue where I want to return multiple lines, but only the first line is being returned. I attempted to create a function specifically for returning the line, but encountered errors because I couldn't figure out where to place it. Does ...

Grouping an array of arrays of objects

I am trying to group an array of objects based on the value of the first item below: const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"va ...

Establishing a standard flatiron-director route (within the element) using the polymer core-pages component

This particular query is closely linked with issues surrounding the usage of flatiron-director/core-pages SPA in conjunction with route-specific JavaScript functions and default routes. While the solution proposed may be effective, my limited expertise in ...

Having trouble with loading JSON due to a Cross-Domain AJAX problem

I am facing a challenge with a URL that I do not have control over, which returns a JSON string. Within this JSON string, there is a URL that I am attempting to load using JavaScript/jQuery AJAX. However, I am encountering a Cross-Domain issue while trying ...