1

How can I pass the information from an input field in the front end(using angularjs) as a JSON object to a server(javascript)?

Basically what I intend to do is take input from a user, and pass it as a query to search a database and return the values.

My controller code:

`app.controller('SearchController',['$scope','$http',function($scope,$http){
    $scope.click=function(){

    var data=$scope.query1;

    $http.post('/credjson',data);

    /*$scope.addRowAsyncAsJSON = function(){        
        $scope.cred.push({ 'query':$scope.query1 });

        var dataObj = {
            query : $scope.query1,
        };  

        var res = $http.post('/credjson', dataObj);
        res.success(function(data, status, headers, config) {
            $scope.message = data;
        });
        res.error(function(data, status, headers, config) {
            alert( "failure message: " + JSON.stringify({data: data}));
        });     

        $scope.query1='';*/`

Note: The code in between /* */ was a different attempt at trying this out.

My view code:

    `<div style="padding-top:20px" ng-controller="SearchController">
        <form name="form1" ng-submit="click()">
    <input id="creditq" ng-model='query1' type="text" /> 
    <button id="Search" ng-value='Search'>Search</button><br/><br/>
    </form>
    </div>`

1 Answer 1

1

Just construct your JSON payload and pass it to $http as the second param

data: { query1: $scope.query1 }

and then

$http.post('/credjson',data);
Sign up to request clarification or add additional context in comments.

3 Comments

I still keep getting "Cannot GET /credjson" in the browser window
Are you sure the api endpoint /credjson is correct and working? Use some chrome extension like postman to verify the endpoint is working correctly first.
I checked using fiddler, figured what i did wrong. I had to use app.post in my server code, though now i am stuck on extracting the data from /credjson into the server to use. Any help with this would be awesome.

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.