最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Values of input field showing in console but not in input field + not able to save to the db - Stack Overflow

programmeradmin7浏览0评论

I am working with angular and the angular material (material design) dependency.

I have this main grid that when i click on it a tile will be created and when i click on that tile a pop up appears. In that pop up is a form with 2 input fields that should display the x and y coordinates of the tile. The values don't show in the input field but they do in my console.

What i am trying to achieve is to be able to save these coordinates to my db. For some reason when i hit save it does not get saved to my db.

Here is my code for the pop up box:

<form ng-controller="AppCtrl">

          <div layout="row">
              <input type="text" id="coord_x" name="coordinate_x" value="" ng-model="task_coordinate_x" >
              <input type="text" id="coord_y" name="coordinate_y" value="" ng-model="task_coordinate_y">
          </div>
</form>

The code for my app.js:

app.controller('AppCtrl', function($scope, $mdDialog, $http) {  
$scope.save_task = function() {
            $http.post('db.php?action=add_task', 
                {
                    'task_coordinate_x'          : $scope.task_coordinate_x,
                    'task_coordinate_y'          : $scope.task_coordinate_y
                }
            )

            .success(function (data, status, headers, config) {
                //$scope.get_task(); //this will fetch latest record from DB
console.log("The task has been added successfully to the DB");
                console.log(data);
            })
            .error(function(data, status, headers, config) {
                console.log("Failed to add the task to DB");
            });

function snapToGrid(x, y, $element, animate) {

        //Set gridsize and offsets
        var gridSizeX = 60;
        var offsetX = 0;
        var gridSizeY = 69;
        var offsetY = 10;

        //calculate the x and y positions on the grid
        var newX = x - ( x % gridSizeX );
        var newY = y - ( y % gridSizeY );

        // pass the x and x to the popup hidden input field to be able to save to db
        localStorage.setItem('coordinateX', newX);
        localStorage.setItem('coordinateY', newY);
        console.log("NewX: " + newX);
        console.log("NewY: " + newY);

        //apply the new positions
        if(animate){
            $element.animate({
                top: offsetY + newY,
                left: offsetX + newX,
            }, 200)
        }else{
            $element.css({
                top: offsetY + newY,
                left: offsetX + newX,
            })
        }
    }

};

This is my php code:

<?php 
    include('config.php');

    switch($_GET['action'])  {

        case 'add_task' :
            add_task(); 
            break;
    }


    /**  Function to add a task to db **/
    function add_task() {
        $data = json_decode(file_get_contents("php://input")); 
        $task_coordinate_x            = $data->task_coordinate_x;
        $task_coordinate_y            = $data->task_coordinate_y;

        print_r($data);

    $qry = 'INSERT INTO tblTask(task_coordinate_x, task_coordinate_y) 
                VALUES ("' 
                . $task_coordinate_x . '","' 
                . $task_coordinate_y . '")';

        echo ($qry);

        $qry_res = mysql_query($qry);
        if ($qry_res) {
            $arr = array('msg' => "Task added successfully!!!", 'error' => '');
            $jsn = json_encode($arr);
            // print_r($jsn);
        } 
        else {
            $arr = array('msg' => "", 'error' => 'Error in inserting record');
            $jsn = json_encode($arr);
            // print_r($jsn);
        }
    }
?>

I am working with angular and the angular material (material design) dependency.

I have this main grid that when i click on it a tile will be created and when i click on that tile a pop up appears. In that pop up is a form with 2 input fields that should display the x and y coordinates of the tile. The values don't show in the input field but they do in my console.

What i am trying to achieve is to be able to save these coordinates to my db. For some reason when i hit save it does not get saved to my db.

Here is my code for the pop up box:

<form ng-controller="AppCtrl">

          <div layout="row">
              <input type="text" id="coord_x" name="coordinate_x" value="" ng-model="task_coordinate_x" >
              <input type="text" id="coord_y" name="coordinate_y" value="" ng-model="task_coordinate_y">
          </div>
</form>

The code for my app.js:

app.controller('AppCtrl', function($scope, $mdDialog, $http) {  
$scope.save_task = function() {
            $http.post('db.php?action=add_task', 
                {
                    'task_coordinate_x'          : $scope.task_coordinate_x,
                    'task_coordinate_y'          : $scope.task_coordinate_y
                }
            )

            .success(function (data, status, headers, config) {
                //$scope.get_task(); //this will fetch latest record from DB
console.log("The task has been added successfully to the DB");
                console.log(data);
            })
            .error(function(data, status, headers, config) {
                console.log("Failed to add the task to DB");
            });

function snapToGrid(x, y, $element, animate) {

        //Set gridsize and offsets
        var gridSizeX = 60;
        var offsetX = 0;
        var gridSizeY = 69;
        var offsetY = 10;

        //calculate the x and y positions on the grid
        var newX = x - ( x % gridSizeX );
        var newY = y - ( y % gridSizeY );

        // pass the x and x to the popup hidden input field to be able to save to db
        localStorage.setItem('coordinateX', newX);
        localStorage.setItem('coordinateY', newY);
        console.log("NewX: " + newX);
        console.log("NewY: " + newY);

        //apply the new positions
        if(animate){
            $element.animate({
                top: offsetY + newY,
                left: offsetX + newX,
            }, 200)
        }else{
            $element.css({
                top: offsetY + newY,
                left: offsetX + newX,
            })
        }
    }

};

This is my php code:

<?php 
    include('config.php');

    switch($_GET['action'])  {

        case 'add_task' :
            add_task(); 
            break;
    }


    /**  Function to add a task to db **/
    function add_task() {
        $data = json_decode(file_get_contents("php://input")); 
        $task_coordinate_x            = $data->task_coordinate_x;
        $task_coordinate_y            = $data->task_coordinate_y;

        print_r($data);

    $qry = 'INSERT INTO tblTask(task_coordinate_x, task_coordinate_y) 
                VALUES ("' 
                . $task_coordinate_x . '","' 
                . $task_coordinate_y . '")';

        echo ($qry);

        $qry_res = mysql_query($qry);
        if ($qry_res) {
            $arr = array('msg' => "Task added successfully!!!", 'error' => '');
            $jsn = json_encode($arr);
            // print_r($jsn);
        } 
        else {
            $arr = array('msg' => "", 'error' => 'Error in inserting record');
            $jsn = json_encode($arr);
            // print_r($jsn);
        }
    }
?>
Share Improve this question edited Jul 9, 2015 at 7:30 Bruce 1,6814 gold badges20 silver badges22 bronze badges asked Jul 3, 2015 at 14:07 GY22GY22 7853 gold badges19 silver badges50 bronze badges 3
  • I would remend storing the coordinate variables in an object coordinates.x and coordinates.y due to the inheritance and proper style. I would also initialize them there. Did you investigate where it fails? Does your server get the variables or are they not available in the save_task method? – enpenax Commented Jul 3, 2015 at 14:25
  • @enpenax, this is what happens -> recordit.co/HcnJOljPxC – GY22 Commented Jul 3, 2015 at 14:30
  • Can you remove the print_r() mand and try? I am not pletely sure of this but PHP doesn't execute beyond the print_r() if it is called – srthu Commented Jul 7, 2015 at 13:39
Add a ment  | 

3 Answers 3

Reset to default 3

i think the problem might happen in php

type in your address bar: http://yourservername./db.php/action=debug

make a php function

 switch($_GET['action'])  {

        case 'debug' :
            debug(); 
            break;
    }

function debug() {

$qry = 'INSERT INTO tblTask(task_coordinate_x, task_coordinate_y) 
            VALUES ("' 
             some value '","' 
            some value '")'
    or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR

);}

and make sure its work

I hope it helps.

This is the problem in your PHP code, you aren't using associative arrays correctly. You also have a major misunderstanding of angular's .post().error() method.

$task_coordinate_x            = $data->task_coordinate_x;
$task_coordinate_y            = $data->task_coordinate_y;

should be

$task_coordinate_x            = $data['task_coordinate_x'];
$task_coordinate_y            = $data['task_coordinate_y'];

This is why your back end is blank/not returning anything. I've verified this with this test:

<?php
$array = ['test' => 'testval'];
echo $array->test;
?>

This returns a blank page, nothing is echoed. The -> is used for object properties, if you had a PHP Class. Associative arrays and classes are very different in PHP. Try echo $array['test'] and it works.

Another thing is you are defining the add_task function, but never invoking it! at the end of the file include add_task();

Additionally, your php functions end by echoing the arrays, it would be a much better practice for them to return a value and then later be outputted as JSON, you'll see why

say you modify the add_task function to return an that $qry_res variable. Then, after calling that function you can create much better outputs

$qry_res = addtask();
$response = [];
if($qry_res){
    $response['success'] = true;
    $response['message'] = "Task added successfully";
}
else {
    $response['success'] = false;
    $response['message'] = "Task not added";
}
echo json_encode($response);

Another very useful suggestion would be for you to perform some kind of error checking on the $qry_res = mysql_query($qry) line. If the query fails, concatenate that error message to $response['message'] (within the function make sure to declare global $response), (another very useful PHP debugging technique is the output buffer).

Now with this response, we can use angular to see whether the task was pleted successfully, by checking the data.success like so: (the data is the response from PHP that now is much better formed JSON)

You also have a major misunderstanding of the .post().error() method. This will be executed when the HTTP/POST request fails, not if the PHP was successful or not, See how to have angular actually detect if the php succeeded:

.success(function(data, status, headers, config) {
    console.log(data.message);
    if(data.success){
        // query was successful
    }
    else {
        // query was unsuccessful
    }
})
.error(function(data, status, headers, config) {
    console.log("Failed to reach PHP file or recieve response");
});

Hope this was helpful

You cannot access global variable (In this case your DB Connection) inside your function, That's why you are not able to insert data into the database. Please find PHP code below and update, I hope it will work for you!!

For me this is working perfectly!!

<?php

class createCon  {
    var $host = 'localhost';
    var $user = 'root';
    var $pass = 'root';
    var $db = 'tblTask';
    var $myconn;

    public function connect() {
        $con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        if (!$con) {
            die('Could not connect to database!');
        } else {
            $this->myconn = $con;
            //echo 'Connection established!';
        }   
        return $this->myconn;
    }

    public function close() {
        mysqli_close($myconn);
        echo 'Connection closed!';
    }

}


$connection = new createCon();
$connection->connect();


if($_GET['action'] == 'add_task'){

    $data = json_decode(file_get_contents("php://input"));         
    $task_coordinate_x  = $data->task_coordinate_x;
    $task_coordinate_y  = $data->task_coordinate_y;    

    $qry = 'INSERT INTO tblTask(task_coordinate_x, task_coordinate_y) 
            VALUES ("' 
            . $task_coordinate_x . '","' 
            . $task_coordinate_y . '")';

    if ( mysqli_query($connection->myconn, $qry)) {       
        echo "Success";
    } else {
        echo "Fail";      
    }    
}

?>

If you have any query please let me know!!

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论