Search code examples
javascriptjqueryajaxangularjsspectrumjs

Submit color spectrum data to PHP back end using AJAX


Here is what I am trying to do:

  1. Pick color
  2. Display value
  3. Display color in div
  4. On submit, post AJAX to PHP

I feel like I am very close, just need that extra push as to where I am going wrong.

Here's a JSFiddle.

My current JavaScript:

app.controller('MyCtrl', function ($scope) {
    $scope.targetColor = '#ec9040';
});

angular.bootstrap(document, ['app']);

jQuery(function () {
    var field1 = $('#field1');

    $('#send').click(
        function () {
            console.log('fieldvalue: field1.val()')
            jQuery.ajax({
                type: "POST",
                url: "colormystatus.php",
                data: {
                    field1value: field1.val()
                },
                dataType: "html",
                success: function (data) {
                    alert(data);
                }
            });
        });
    });
}

Solution

  • You can move the jQuery(function () {}) into your controller, and send $scope.targetColor instead of field1.val(): (updated fiddle)

    app.controller('MyCtrl', function ($scope) {
        $scope.targetColor = '#ec9040';
    
        jQuery(function () {
            $('#send').click(function () {
                console.log('$scope.targetColor:', $scope.targetColor)
                jQuery.ajax({
                    type: "POST",
                    url: "https://httpbin.org/post",
                    data: {
                            field1value: $scope.targetColor
                           },
                    dataType: "html",
                    success: function (data) {
                                            alert(data);
                                             }
                });
            });
        });
    });