1

So I am trying to send an $http angularjs request to php but the it will trigger successCallback (so does that mean that my request is successful?) but when I checked my database nothing happened and my data is still there. I know I'm missing something in here. please help.

Controller (which calls the checkPollCodeIfAvail function)

pollFactory.checkPollCodeIfAvail('qwe123').then(function successCallback(response){
    console.log('success');
}, function errorCallback(response){
    console.log('fail');
});

Factory:

factory.checkPollCodeIfAvail = function(x){
    code = x;
    return $http({
        method: 'POST',
        data: {
            'action' : 'checkPollCode',
            'pollCode' : code
        },
        url: 'http://localhost/poll/api.php'
    });
};

return factory;

api.php

if(empty($_POST['action'])){
    return;
}

if(($_POST['action']) == "checkPollCode"){
    $checkPollCode = $_POST['pollCode'];
}

switch ($_POST['action']) {
    case 'checkPollCode':
        $sql = "DELETE FROM polls WHERE pollCode = :pollcode";
        $stmt = $db_con->prepare($sql);
        $stmt->bindParam(":pollcode", $checkPollCode);
        $stmt->execute();
        if($stmt->rowCount() > 0){
            echo "success";
        }else{
            echo "error";
        }
        break;
}

Thank you for anyone that can help me.

6
  • 1
    method of you is GET but in php is POST Commented May 6, 2017 at 13:02
  • Thanks for the response but I tried changing it to POST but it still won't work. Commented May 6, 2017 at 13:05
  • why you use switch case in php . try delete directly and remove successCallback in angular Commented May 6, 2017 at 13:08
  • I used switch since I will be having a few actions in my php file. Why do I have to remove successCallback? Commented May 6, 2017 at 13:11
  • you dont need it , and in angular you should transform data before send it . Let me try create answer Commented May 6, 2017 at 13:13

2 Answers 2

1

In angular try add this

 return $http({
        method: 'POST',
        data: {
            'action' : 'checkPollCode',
            'pollCode' : code
        },
        url: 'http://localhost/poll/api.php'
        transformRequest:function(obj) {
                var str=[];
            for(var p in obj){
    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))
                                }
                                return str.join("&");
                            },
                headers:{'Content-Type':'application/x-www-form-urlencoded'}
    }).then(function(response){
    console.log('success');
}

Defaut type header of angular is application/json , and if you dont change header , you should decode input in php . I'm not familar with php and I change to form-urlencoded .

For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

And this code

transformRequest:function(obj) {
                    var str=[];
                for(var p in obj){
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]))
                                    }
                                    return str.join("&");
                                }

before send data to server , you loop though data and transform it to x-www-form-urlencoded .

Sign up to request clarification or add additional context in comments.

7 Comments

This works thank you but I'm a newbie in angularjs and I don't really understand this code and why do I need to do this. Can you explain what's happening here?
@CityDove I edited answer and try explain . My english not good so it's hard for me to explain clearly
@ThanTung I see. Thank you! I have another question. Is the response in the .then(function(response) the echoed "success" in my php?
@CityDove what do you mean ? If you mean is display echo"success" in php you should create array in php and put message echo and encode it .
Like this : $ar = array() ar['message'] ='success' json_encode($ar); And in angular $scope.sucess = response.data.message;
|
0

You have some pbm in Http

Try this Code :

var fd = new FormData();
fd.append('action', "checkPollCode");
fd.append('pollCode', code);

$http.post("http://localhost/poll/api.php", fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(data, status, headers, conf) {
    //Evrytheng OK
}).
error(function(data, status, headers, config) {
    alert("You have some error");
});

Don't forget adding $Http in your controller:

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

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.