简体   繁体   中英

Assigning value to ng-init from Ajax result

I've a form with one input field to submit the student id via AJAX and I'm fetching some JSON result from the AJAX request. Now the returned data from AJAX request need to be assigned to ng-init in the input field ( phone ) below the form. Please help me how to assigning this value to ng-init . Thank you!

HTML

<div ng-app="">
    <form id="std_form">
        <input type="text" name="sid" id="sid">
        <input type="submit">
    </form>

    <input type="text" name="phone" ng-model="phone" ng-init="" id="phone">
    Ph: {{phone}}
</div>

jQuery

$('#std_form').submit(function(e){
    e.preventDefault();
    var val = $('#sid').val();
    var dataString = "sid=" + val;
    $.ajax({
        type: "POST",
        url: "post_process.php",
        data: dataString,
        dataType: 'json',
        success: function(data){
            $('#phone').val(data.phone);
        }
    });
});

post_process.php

<?php

if(ISSET($_POST['sid'])) {

    $sid = $con->real_escape_string($_POST['sid']);

    $sql = "SELECT phone FROM std_detials WHERE sid = $sid";
    $result = $con->query($sql);
    if ($result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $phone = $row['phone'];
    }
    $json = array('phone' => $phone);
    $json = json_encode($json);
    echo $json;
}

?>

You are not using ng-model for student id field. When in angular do as angular says. The code is a mix of traditional submission techniques of PHP and then ajax call through Jquery. Try to eliminate such practices as much as possible and adore the framework properly.

Try this code. Understand and apply. A brief:
I have used Angular's $http post call instead of jquery's $.ajax . You can keep the same call or use the native angular's call.

Removed some unnecessary markup.Added ng-model to input of student id, ng-click function to button used for submission and structured the code somewhat. If you have a separate services.js file for project add service code there or just add a new service as I have done in code here.

So basically you don't need ng-init for this problem. It should be used in rare situations. Please read docs here. https://docs.angularjs.org/api/ng/directive/ngInit

Hope it helps ! do let me know in case of any questions.

<div ng-app="myApp">
  <form id="std_form">
    <input type="text" ng-model="sid">
    <button ng-click="submitSid()"></button>
  </form>

  <input type="text" ng-model="phone">
  Ph: {{phone}}
</div>

JS

var app = angular.module('myApp', []);
app.controller('MyCtrl', ['StudentService', function(StudentService){
   $scope.submitSid = function(){
    var data = {sid: $scope.sid};
    StudentService.getStudentDetails(data).then(function(res){
        console.log(res);
        $scope.phone = res.phone; // Or change to res.paramName. Just check in console to confirm the res logged.
    })
}
}]);

 app.factory('StudentService', ['$http', '$httpParamSerializerJQLike',           function($http, $httpParamSerializerJQLike){

  var getStudentDetails = function(data){
  var params = $httpParamSerializerJQLike(data);
    return $http({
        method: "POST",
        url: "post_process.php",
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'},
        data: params
    }).then(function(response){
      return response.data;
    });
}

return {
    getStudentDetails : getStudentDetails
}   
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM