issue while printing the variable to html page - javascript

I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed
this is my html:
<div ng-app="app" ng-controller="VolController">
<div class="account-action">
<h3 style="display:inline;"><img class="img" align="left" src="images/u11.png">
<p style="color:white"> Welcome {{first_name}}<p></h3>
</div>
this is my controller:
app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){
var b=sessionStorage.getItem("userid");
var a="http://localhost:8080/volunteers/"+b;
$.ajax({
type:'GET',
url:a,
success:function(data){
console.log(JSON.stringify(data));
$scope.volunteer=data;
$scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
console.log(data);
},
error:function(data){
alert(data);
},
dataType:"json",
contentType:"application/json",
})
}]);
Question Updated!!!!

As you use $.ajax instead of native $http, you should wrap assigning into $apply:
success: function(data) {
$scope.$apply(function(){
$scope.volunteer = data;
$scope.first_name = JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
});
}

You should use $scope,
$scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

Don't make ajax call using jquery $.ajax. Please make ajax call using $http service of angularjs.
$http.get(url);
Do not forget adding $http service as dependedency in angular.

Related

passing data from laravel view to controller via ajax onchange event

I have a dropdown list in a blade view. I want to send the value of the selected item to the controller immediately onchange. I have 2 routes in web.php:
Route::get('/plots', 'PlotController#index');
Route::get('/plots/{testId}', 'PlotController#getData');
The first one populates the dropdown list. The second one is supposed send the value of the dropdown list to the controller, which pulls stuff from mysql and sends the data back to the view, which draws a chart. I can get the dropdown to populate ok, but I can't figure out how to send the selected value to the controller. I'm trying to use ajax to do it like this:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
console.log("testId=" + testId);
$.ajax({
url: 'plots/' + testId,
type: 'get',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
});
});
The testId output to the console is correct but it never makes it to the controller. The error I see in the console is:
GET http://homestead.test/plots/1 500 (Internal Server Error)
I'm pretty new to laravel and find it extremely confusing. Can anyone explain the correct way to do this?
EDIT:
After testing and confirming Rian's answer as correct, I then tried to implement the real code, which of course is much more complicated. Instead of the controller returning the input test_id:
return $request->test_id;
It actually returns a more complex structure:
return view('plot')
->with('measurements',json_encode($result))
->with('events',json_encode($timeline))
->with('limits',json_encode($limits));
When I uncomment the original controller code, including the return section above, it seems to affect the ability of the controller to return anything at all. Here is the first few lines of the PlotController getData method:
public function getData(Request $request) {
Log::debug("made it to PlotController.php#getData");
Log::debug("test_id="+$request->testId);
And here is the log output:
[2020-02-23 16:43:52] laravel.DEBUG: made it to
PlotController.php#getData
The second line does not output anything. Here is what I see in the javascript console after I select an item from the dropdown list:
testId=49 jquery.min.js:2 GET
http://homestead.test/get-data-by-id?test_id=49 500 (Internal Server
Error)
Any ideas?
The easiest way is to get the data in Laravel Request. At least that's how I do it.
So your route shouldn't contain any parameter for that.
Your route will look like this:
Route::get('get-data-by-id', 'PlotController#getData')->name('get.data.by.id');
Your ajax should be like this:
$(document).on('change', '#sel_test',function(){
var testId = $(this).val();
$.ajax({
type:'GET',
url:"{{ route('get.data.by.id') }}",
data:{'test_id':testId},
success:function(data){
console.log(data);
}
});
});
In your controller's getData() function just use Laravel Request to fetch the data.
public function getData(Request $request)
{
// You can return the ID to see if the ajax is working
return $request->test_id;
}
Make it post from Get for easier
At Web.php
Route::post('/list/plots', 'PlotController#getData')->name('getData');
At Blade file Ajax Request :
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
var url = '{{ route("getData")}}';
var token = "{{ csrf_token()}}";
$.ajax({
method:"post",
url: url,
data:{testId:testId,_token:token}
dataType: 'json',
success: function(response) {
console.log("success",response);
}
});
});
});
At Controller :
public function getData(Request $request){
$testId = $request->testId;
// Write your logic here
}
Try this. Hopefully work for you

Using php response to populate front end Ajax

This should be a very easy question, but I cannot find the answer. I have a js file that is making an ajax request to a php file. i am then trying to use the response provided by php to update the front end, but the response is not in the correct format. I am getting back the whole echo statement when I look in the console. Pardon my ignorance here but I am quite new to php. I think there is an issue sending back an a href link and br in my php
$.ajax({
url: 'php.php',
}, function (data) {
console.log(data);
$('.container').html(data);
});
PHP
<?php
$output = 'This is<br>a<br>test<br><span>Test Here</span>';
echo $output;
?>
When all this has successfully worked I want to change my html to:
<div class="container">
This is<br>a<br>test<br><span>Test Here</span>
</div>
When using jQuery's $.ajax function you can use either of { success: function() {...} } or .done() promise:
$.ajax({
url: 'php.php',
success: function (data) {
console.log(data);
$('.container').html(data);
}
});
Or
$.ajax({
url: 'php.php',
success: function (data) {
console.log(data);
$('.container').html(data);
}
}).done(function( data) {
console.log(data);
$('.container').html(data);
});

ng-repeat not reflecting when the source variable gets modified

I have the following angularJs code. When my source data changes, my ng-repeat does not update my view. I looked at other posts and added $scope.$apply(); , $scope.$digest(); at the end of my ajax success callback, but it did not help. The idea is that the page will have an empty table in the begining and after the ajax call onReady() it will populate the rows with data. Could someone point me at what I am missing here or a better way to achieve the same
JS:
(function() {
var app = angular.module("jmeter-module", []);
app.controller('JmeterTableController', ['$scope', function($scope){
$scope.data = [];
$(document).ready(function(){
var url = "jmeterTableData.html";
fetchTableData(url, 10, 25);
});
function fetchTableData(url, minAge, maxAge){
$.ajax({
type: "GET",
url: url,
data: { minAge : minAge,
maxAge : maxAge },
datatype: "json",
success: function(data){
/*If I try to print data here, I see the values rightly getting returned*/
$scope.data = data;
},
error: function(e){
console.log(e);
}
});
}
}]);
})();
JSP:
<div id="buildGroupsParentDivId" ng-controller="JmeterTableController as row">
.
.
.
<tbody id="jmeter-table-content" >
<tr ng-repeat="val in row.data">
<td><img title="History" src="/images/history.png" width="20" height="20"></td>
<td><input type="checkbox" value="save"></td>
<td>{{val.firstName}}</td>
<td>{{val.lastResult}}</td>
</tr>
</tbody>
the problem is with the execution of $.ajax outside of the scope of Angular's digest cycle. You could get this working with $scope.$apply, but since you're already using Angular it's better to use the AngularJS xhr helper methods:
https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

How to create a basic angularjs page for REST json data?

I'm trying to create a basic webpage that shows data retrieved by http://rest-service.guides.spring.io/greeting.
The json output is:
{"id":2273,"content":"Hello, World!"}
I'm using the following html page:
<body ng-app="hello">
<div class="container">
<h1>Greeting</h1>
<div ng-controller="home" ng-cloak class="ng-cloak">
<p>The Id is: {{greeting.id}}</p>
<p>The content is: {{greeting.content}}</p>
</div>
</div>
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="js/hello.js"></script>
</body>
And the hello.js:
var myApp = angular.module('hello', []);
myApp.controller('home', ['$scope', function($scope) {
$scope.greeting = {};
$http.get('http://rest-service.guides.spring.io/greeting')
.success(function(data, status, headers, config) {
$scope.greeting = data;
});
}]);
Result: the placeholders greeting.id/content are not resolved. What might be wrong here?
You didn't inject $http service.
myApp.controller('home', ['$scope, $http', function($scope, $http) {...}]);
EDIT
It is also worth to metnion what cverb said in his answer. In Angular 1.4 you should replace .success() with .then(), because .success is deprecated.
Now usage should be:
$http.get(url).then(
function(data){
//success callback
},
function(){
//error callback
});
);
change your $http call to following. You have also not injected $http in your controller.
$http.get('http://rest-service.guides.spring.io/greeting')
.success(function(data, status, headers, config) {
$scope.greeting = data.data;
});
Change your .success() with .then(), the .success() method is deprecated and does not work in the same way as a normal promise.
If you wish to keep using it, you can just use it like this.
$http.get('http://rest-service.guides.spring.io/greeting')
.success(function(data) {
$scope.greeting = data;
});
Also see the documentation of $http.

How to bind data in json to li using Angular js

am try to develop an application using angular js in which i take take data from database and populate li using that data
for that i write a WebMethod as fallow
[WebMethod]
public static string getname()
{
SqlHelper sql = new SqlHelper();
DataTable dt = sql.ExecuteSelectCommand("select cust_F_name,Cust_L_Name from customer");
Dictionary<string, object> dict = new Dictionary<string, object>();
object[] arr = new object[dt.Rows.Count];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
}
which return data in json form
am use the fallowing js to bind
var DemoApp = angular.module('DemoApp', []);
DemoApp.factory('SimpleFactory', function () {
var factory = {};
var customer;
$.ajax({
type: "POST",
url: "Home.aspx/getname",
data: JSON.stringify({ name: "" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
customer = $.parseJSON(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
factory.getCustomer = function () {
return customer;
};
return factory;
});
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
$scope.Customer = SimpleFactory.getCustomer();
});
and my view is as fallow
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DemoApp">
<head runat="server">
<title></title>
</head>
<body data-ng-controller="SimpleController">
<form id="form1" runat="server">
<div>
Name<input type="text" data-ng-model="Name" />{{ Name }}
<ul>
<li data-ng-repeat="customer in Customer | filter:Name">{{ customer.cust_F_name }} -
{{ customer.cust_L_name }}</li>
</ul>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="Script/Home.js" type="text/javascript"></script>
</body>
</html>
but it not working it will work fine if i hard code the data in factory but when i bring data using ajax call it will not work am unable to understand why it so.
Why it's not working?
you cannot just attach a variable to the scope when it's value is waiting for on asynchronous call.
when you use 3rd-party libraries that changes the scope you must call $scope.$apply() explicitly
prefer $http over $.ajax and use promises!
DemoApp.factory('SimpleFactory', function ($http) {
return {
getCustomer: function(){
return $http.post('Home.aspx/getname',{ name: "" });
})
}
}
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function(customer){
$scope.Customer = customer;
},function(error){
// error handling
});
});
If you still want to use $.ajax
you must explicitly call $scope.$apply() after the response
you must use promises or callbacks to bind to scope variables.
If you want to first fetch data from the server and than load the view
#Misko Hevery has a great answer: Delaying AngularJS route change until model loaded to prevent flicker
It's not related to your problem but load jquery before you load angular.js
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
Your problem is the js (the function "SimpleFactory.getCustomer()") is returning before AJAX call returning..
Also, you should use $http in Angular instead of jquery's ajax, because:
$http returns a "promise" similar to other areas in angular, which means .success, .done are consistent with angular.
$http set the content type to 'application/json' for you on POST requests.
$http success and error callbacks will execute inside of angular context so you don't need to manually trigger a digest cycle - if you use jQuery, then it might be necessary to call $apply..
Like this:
var DemoApp = angular.module('DemoApp', []);
DemoApp.factory('SimpleFactory', ['$http', function ($http) {
var factory = {};
factory.getCustomer = function () {
var promise = $http.post('Home.aspx/getname', {name: ''});
promise.catch(function(error) {
alert(error);
});
return promise;
};
return factory;
}]);
DemoApp.controller('SimpleController', ['$scope', 'SimpleFactory', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function(customer) {
$scope.Customer = customer;
});
}]);
Factories in AngularJS are singletons. So the way you've written the code will execute the ajax call when the factory is injected into the controller. You don't see the customer data because the server response will be handled after you assign the json data to the scope variable.
A quick (and dirty) fix which will probably work is wrapping the customer object:
DemoApp.factory('SimpleFactory', function ($rootScope) {
// ...
var customer = {};
// ...
$.ajax({
// ...
success: function(data) {
$rootScope.$apply(function() {
customer.data = data;
});
}
// ...
});
});
// In view
<li data-ng-repeat="customer in Customer.data"> <!-- ... --> </li>
A better approach would be to use either to use the builtin $http or the $resource angular service. The last one requires you to make use of RESTful services (recommended). If for any reason you still want to make use of jQuery ajax calls you need some form of telling Angular that the ajax call has been completed: have a look at the $q promise service.

Categories