0

This is my server side code in PHP to update the supplier.

$app->put('/supplier/:id', function($id) use($app) {
    // check for required params
    verifyRequiredParams(array('name', 'mobile'));
    $name = $app->request->put('name');
    $mobile = $app->request->put('mobile');

    $db = new DbHandler();
    $response = array();

    $result = $db->updateSupplier($id, $name, $mobile);
    if ($result) {
        $response["error"] = false;
        $response["message"] = "Supplier updated successfully";
    } else {
        // supplier failed to update
        $response["error"] = true;
        $response["message"] = "Supplier failed to update. Please try again!";
    }
    echoRespnse(200, $response);
});

When I test this code with my rest client postman it works fine.

Now I want to use same API in my angular js application. This is my function for the same functionality.

var REST_SERVICE_URI2 = 'http://abcd.com/SupplierApi/v1/supplier/5';

function updateSupplier(supplier, id) {
    ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
    var data = {
        name: supplier.name,
        mobile: supplier.mobile
    };

     ͟r͟e͟t͟u͟r͟n͟ $http.put(REST_SERVICE_URI2, data)
        .then(
            function (response) {
                ̶d̶e̶f̶e̶r̶r̶e̶d̶.̶r̶e̶s̶o̶l̶v̶e̶(̶r̶e̶s̶p̶o̶n̶s̶e̶.̶d̶a̶t̶a̶)̶;̶ 
                return response.data;
            },
            function(errResponse){
                console.error('Error while updating Supplier');
                ̶d̶e̶f̶e̶r̶r̶e̶d̶.̶r̶e̶j̶e̶c̶t̶(̶e̶r̶r̶R̶e̶s̶p̶o̶n̶s̶e̶)̶;̶ 
                throw errResponse;
            }
        );
    ̶r̶e̶t̶u̶r̶n̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶.̶p̶r̶o̶m̶i̶s̶e̶;̶

}

The angular js code though is not able to update supplier. Is there anything wrong in my update function?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • While not the cause of your problem, **avoid the [$q defer anti-pattern](https://stackoverflow.com/questions/30750207/is-this-a-deferred-antipattern)** because it is unnecessary and prone to erroneous use. – georgeawg Jul 30 '17 at 18:02
  • Have you tried adding echo statements to see if the request received on the server is as expected? – Andrew Stalker Jul 30 '17 at 18:06
  • When an API works with postman and doesn't work with AngularJS it is usually a [CORS problem](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). The API needs to respond to OPTIONS requests and other requests with appropriate CORS headers. Check to see if `errResponse.status` is -1. – georgeawg Jul 30 '17 at 18:54
  • Also if the `updateSupplier` function fails, the API should avoid responding with 200 (OK) status. Instead, use an appropriate `4XX` or `5XX` status code. – georgeawg Jul 30 '17 at 19:05
  • @georgeawg i checked. errResponse.status is -1. What does that mean? How to fix it? – Devesh Agrawal Jul 31 '17 at 01:16

0 Answers0