1

I posted the code for my index.html, app.js and insert.php.

The dependencies installed are express, mysql and morgan.

In my folder I have

  • /node_modules
  • app.js
  • index.html
  • insert.php
  • package.json

I have a WAMP local server running in the background. phpMyadmin's username is root and password is blank, by default. I've set up a database called storestuff with a table in it named thestuff which has two columns title and content.

So I run node app.js in the terminal and then get
Server running on port 3000.
Connected successfully to the database.

Now, I go to visit localhost:3000

When the page loads, terminal shows GET / 304 20.635 ms - - which means the page loaded correctly.

I've also inserted some dummy data into the MySQL storestuff database using phpMyAdmin for testing purposes. Visiting localhost:3000/load which is a route set up in app.js, terminal shows GET /load 200 16.382 ms - - which shows in the browser, a page with JSON data which is indeed the dummy data I had inserted and http code 200 means the GET request worked properly.

When I fill out the title field and the content field and press submit, terminal shows POST /insert.php 404 2.949 ms - 150 which I don't understand because insert.php is in the same folder as index.html.


index.html

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro">
  </head>

  <body>
    <font face="Source Sans Pro">
      <div ng-app="myApp" ng-controller="myController">
        <h1> Hello world! </h1>
        <form>
          Title <input type="text" ng-model="title"><br>
          Content <input type="text" ng-model="content"><br>
          <input type="button" value="Submit" ng-click="insertdata()">
        </form>
        <script>
          var app = angular.module('myApp', []);
          app.controller('myController', function($scope, $http) {
            $scope.insertdata = function() {
              $http.post('insert.php', {
                'title':$scope.title,
                'content':$scope.content
              })
              .then(function(data) {
                console.log("Data inserted into the MySQL database successfully.");
              });
            }
          });
        </script>
      </div>
    </font>
  </body>
</html>


app.js

var express = require('express');
var mysql = require('mysql');
var morgan = require('morgan');
var app = express();
app.use(morgan('dev'));

var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '',
    database : 'storestuff'
});

connection.connect(function(error) {
    if(error) console.log("Problem connecting to MySQL: " + error);
    else console.log("Connected successfully to the database");
});

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

app.get('/load', function(req, res) {
    connection.query("SELECT * from thestuff", function(err, rows) {
        if(err) console.log("SELECT from thestuff... did not work: " + err);
        else res.end(JSON.stringify(rows));
    });
});

app.listen(3000, function() {
    console.log("Server running on port 3000.");
});


insert.php

<?php
  $data = json.decode(file_get_content('php://input'));
  $title = mysql_real_escape_string($data->title);
  $content = mysql_real_escape_string($data->content);
  mysql_connect('localhost', 'root', '');
  mysql_select_db('storestuff');
  mysql_query("INSERT INTO thestuff('title', 'content') VALUES('".$title"', '".$content"')");
?>
4
  • have you tried with $http.post('http://localhost/insert.php') Commented May 11, 2017 at 4:13
  • Not Found The requested URL /insert.php was not found on this server. A typical 404 note :( Commented May 11, 2017 at 4:14
  • 1
    are you getting data on insert.php? try var_dump($data); on that file Commented May 11, 2017 at 4:15
  • Could you show me how to use that function? Like where does it go? In the controller? In the insertdata function? In my post request? Sorry.. i'm kinda new to this JavaScript business :P Commented May 11, 2017 at 4:24

3 Answers 3

1

add this in the top of your php file

<?php
  header("Access-Control-Allow-Origin: *");
Sign up to request clarification or add additional context in comments.

9 Comments

The terminal showed a POST /insert.php 404 with my original $http.post('insert.php') but when I change to either of your $http.post('http://localhost/insert.php') or $http.post('http://127.0.0.1/insert.php') pressing submit doesn't even give me an error nor a success, just nothing happens
and did you tried printing the post data in your php file
Yes, I did try localhost, sorry I had a typo in my comment reply
Well, it never gets to the PHP file so printing the data there doesn't output anything in my terminal nor the chrome console
go to the network part from inspect on your browser. then see what it is showing when you click on submit button
|
1

try with headers property

$http({
      method: 'POST',
      url: 'insert.php',
      data: {'whetever':'data', 'in':'json format'},
      headers: {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
    })
    .then(function(res){
         console.log('successful response', res);
    .catch(function(err) { 
         console.error('Error while post', err);
    });

and you can access in on insert.php

header("Access-Control-Allow-Origin: *");

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST)) {
    $_POST = json_decode(file_get_contents('php://input'), true);    
    echo $data->whatever;
  }

Note: you can also you set it globally for all post request within .config block as below

myApp.config(function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});

Comments

0

You are using node to power your web server. Couple of things: in your app routes you don't have a route for app.post ('/insert.php'), which is the cause of your 404. But node.js itself won't interpret php files for you, so at best it will show the code for the php file. There are plugins you can use or use another web server like nginx in front of the express/nodejs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.