0

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;
}

?>
Naresh
  • 862
  • 3
  • 12
  • 35
  • You need to change the code where you access the php and get value – Sajeetharan Oct 23 '16 at 12:47
  • @Sajeetharan Could you please let me know what change should I make to my code? – Naresh Oct 23 '16 at 12:49
  • This submit is all wrong and there should be no jQuery involved at all. The `ng-init` idea is also all wrong. Suggest you study some angular form tutorials and learn about `ng-model` and `ng-submit` – charlietfl Oct 23 '16 at 12:50
  • @charlietfl I know it is wrong, could you please correct me the mistakes? – Naresh Oct 23 '16 at 12:52
  • Trying to explain that the approach is completely wrong. See [thinking-in-angularjs-if-i-have-a-jquery-background](http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background). Solution provided below is far more in line with angular methodology although I personally prefer `ng-submit`. Angular also has built in validation you can leverage – charlietfl Oct 23 '16 at 13:04

1 Answers1

1

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
}   
}]);
georgeawg
  • 48,608
  • 13
  • 72
  • 95
HalfWebDev
  • 7,022
  • 12
  • 65
  • 103
  • Code only answers without any explanation are not very valuable on SO regardless if they solve the problem or not – charlietfl Oct 23 '16 at 12:58
  • Just was editing the same. Pressed the submit button in a hurry. Apologies – HalfWebDev Oct 23 '16 at 13:00
  • still some problems here... not creating a key/value pair for post and need to serialize the data and `success` is not part of `$http` config – charlietfl Oct 23 '16 at 13:10
  • @charlietfl. Thanks for pointing it out. Nearly missed the important part of serializing.Corrected both – HalfWebDev Oct 23 '16 at 13:16
  • ok... but what is being serialized now? Needs to be object not a primitive or there will be no key/value pair sent... much closer now. Also should be `return response.data.phone;` since you converted to `then()` – charlietfl Oct 23 '16 at 13:17
  • Done. Please review now ! – HalfWebDev Oct 23 '16 at 13:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126452/discussion-between-megaracer-and-charlietfl). – HalfWebDev Oct 23 '16 at 13:26