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

Optimizing Angular6 Pipe Filter Performance for Large Arrays

I have written a filter that retrieves a subset of items from a large array consisting of around 500 items. import { Injectable, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'searchFilter' }) @Inject ...

issue with node callback function - code malfunctioning

I have written a script in Node.js and Express to send an email after a SQL transaction is successfully completed! router.post('/',function(req,res,next){ sql.connect(config).then(function() { var request = new sql.Request(); ...

Applying a translucent layer of color to a jpeg image to create a subtle background effect

I am attempting to create a semi-transparent, solid background color on top of an <img> tag, while still showing the original image underneath at the same ratio and size. Below is a snippet of the code I am working with (let me know if you need more ...

Update an existing item or add a new one if it is not already present

I am attempting to create a functionality similar to canva.com, where users can select images from the sidebar and drop them anywhere in the "div", allowing multiple images with individual positions. However, when I use setState(prevState=>{return [...p ...

The issue with using Angular's form.fieldName.$invalid within the ng-class attribute

After spending some time, I finally figured out the mistake I made in solving this problem. It was a simple error that caused my Angular validation to not work as expected. In order to help others avoid making the same mistake, I decided to share it here. ...

jQuery $.ajax problem encountered

When working with AngularJS, we have the ability to catch errors using the $http() service as shown below: return $http(defaultConfig).then(sendResponseData)**.catch(errorCallBack)**; On the other hand, when attempting to do something similar in jQuery: ...

Executing a for loop just once in JavaScript

var door1 = {open: false,car: false,choose: false}; var door2 = {open: false,car: false,choose: false}; var door3 = {open: false,car: false,choose: false}; var carName = 0; var objectName = 0; var goatName = 0; var min = 1; var max = 4; var random = Math. ...

Unable to trigger AJAX POST with jQuery click handler

Important Note: Personally, I have a preference for utilizing jQuery over the shorthand $; although it involves more typing, I find it to be more readable. I am working on a simple form that allows users to input their first and last names as well as an e ...

Parsing JSON as a sequence of individual characters

Currently encountering an issue and seeking guidance from anyone who may have experienced this before and knows what's going on. Utilizing $resource to fetch data from our WebAPI. (angularJS controller code) Controller.service.common.GetData.get({ ...

Hover and hover-off functions in navigation menu

html <div class="hidden-nav"> <h4>lorem</h4> <ul class="decor-menu-list"> <li><a href="#">123</a></li> <li><a href="#">123</a></li> <li><a hre ...

What is the best way to add new input fields dynamically using the push() function in AngularJS?

I'm currently working on implementing an add more field feature in angularjs. Here is the code that I am using: Javascript <script> function FruitsController($scope){ var div = 'Apple'; $scope.fruits= ...

Is RaphaelJS truly a vector-based tool?

Is it possible to position a circle at 50% of the width of the canvas using RaphaelJS without having to calculate the exact pixel value? I am looking for a simple way to place an element at half its container's width, but I'm not sure if this can ...

When iterating over objects in JavaScript, the loop may return undefined, while using Lodash's map

After encountering an issue with a JavaScript loop where the value was returning as null upon completion, I decided to try using lodash for the same purpose and it successfully returned the result. This is what I attempted: JavaScript: const jsRows = Ob ...

Transferring an Array from PHP to Javascript

I'm attempting to pass a PHP array so that I can use it in JavaScript. The PHP code I have written is shown below: <?php $link = mysqli_connect("localhost", "root", "password", "database"); /* check connection */ if (mysqli_connect_errn ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

Struggling to set up a development environment for AngularJS? I am facing difficulties in launching a simple AngularJS application

Just starting out with AngularJS and trying to navigate the app building process. Initially created two files, index.html and app.js, followed by utilizing the npm init command to generate my package.json file which ended up looking like this (added the st ...

The process of accessing a global JavaScript variable within an AngularJS directive is a common task

I spent some time searching for an article that addresses my specific question but came up empty-handed. My dilemma revolves around accessing a pre-defined JavaScript global variable within an AngularJS built-in directive. Let's say I declare the fo ...

What is the best way to record and share a video with jquery and laravel?

Is there a way to grant users access to record videos within an application and then upload them after previewing? I've been able to successfully record and download a video, but now I'm unsure of how to proceed with uploading it to the server. ...

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...

Exploring the concepts of express post and delete responses that are unclear

It appears that I am facing an issue where trying to access an attribute of an element from a JSON file returns null. Additionally, I am still encountering npm audit problems. What are your thoughts on this situation? Below is the code snippet that has be ...