I am trying to populate a ListBox dynamically. But it's not working with ajax request.
Here's what I am doing.
My Ajax request :
angular.module("confessions_module").factory("Universities",function(){
var service = {};
service.getUniversitiesAjax=function(callback)
{
$.ajax({
type:'GET',
url:'myurl',
success:function(e)
{
universitiesList = $.parseJSON(e);
callback(universitiesList);
}
});
// var a = [{ 'name':'asdasdsad','id':123},{ 'name':'mozi','id':123}];
// callback(a)
}
return service;
});
My Controller calling the function and populating the array:
Universities.getUniversitiesAjax(
function(university)
{
for(var i=0;i<university.length;i++)
{
var unii = { 'name' : university[i].name , 'id' : university[i].id };
$scope.unis.push(unii);
}
}
);
My View:
<select id="dd_universities">
<option ng-repeat="uni in unis">{{uni.name}}</option>
</select>
Now there are two lines commented in My Ajax Request code. When I uncomment those two lines , my data gets populated with no problem. But whenever I try to populate it using the ajax request code as it is happening now. It does not work. What could be the problem ?
Your AJAX callback is executed "outside" of Angular, so even though you are changing your scope properties:
$scope.unis.push(unii);
Angular will not notice these changes. Call $scope.$apply() after your for loop. This will cause Angular to run a digest cycle, which will notice your changes and update your view(s).
Related
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
I have a angular controller that has a function which adds the html retrieved in post to a container. I can then click on a div within that sets a var result to some data onclick.
<div onclick="var result = {"some":"data", "right":"here"}...
The issue Im having is retaining the callback functions functionality. This is what I am trying to convert.
jQuery.post(url, {
'callback': "callbackFunctions.setData(result);callbackFunctions.closeDialog();",
'return_type' : 'json'
},
function (json) {
if (json.success) {
jQuery('#template').html(json.message);
}
}, 'json');
That snippet is currently using a external set of functions from the angular controller.
var callbackFunctions = {
closeDialog: function () {
angular.element('#template').dialog('close');
},
SetData: function (result) {
var scope = angular.element('.variables img:visible').scope().$parent;
scope.$apply(function(){
jQuery.extend(true, scope.variables, {
url: result.url,
name: result.name,
thumbnail: result.thumbnail,
value: result.url
});
});
}
};
I just don't think this is the cleanest solution. It currently works I just cant seem to convert this to angular's $http request and get the callback functions to work. Ideally this would be $http.post and when calling the functions they would be within the controller so I already have access to the scope.
One gotcha I can not modify the http I am requesting its used in a ton of other areas of the site not yet updated.
Controller
$http.post(url, data).then(function(response){
$scope.message = response.message;
}, function(error){
console.log("Error detected : " + error);
})
HTML
<div id="template">
{{message}}
</div>
I don't really know what you want to do with the API's data but you can use ng-bind or {{variable}} inside your html to display them
I am using jQuery to delete some data from database. I want some functionality that when jQuery returns success I want to execute a query. I want to update a another table on success of jQuery without page refresh. Can I do this and if yes how can I do this?
I am newbie to jQuery so please don't mind if it's not a good question for stackoverflow.
This is my script:
<script type="text/javascript">
$(document).ready(function () {
function delete_comment(autoid, btn_primary_ref) {
$.ajax({
url: 'rootbase.php?do=task_manager&element=delete_comment',
type: "POST",
dataType: 'html',
data: {
autoid: autoid
},
success: function (data) {
// I want to execute the Update Query Here
alert("Comment Deleted Successfully");
$(btn_primary_ref).parent().parent().hide();
var first_visible_comment = $(btn_primary_ref).parent().parent().parent().children().find('div:visible:first').eq(0).children('label').text();
if (first_visible_comment == "") {} else {
$(btn_primary_ref).parent().parent().parent().parent().parent().parent().prev().children().text(first_visible_comment);
}
load_comment_function_submit_button(autoid, btn_primary_ref);
},
});
}
$(document).on('click', '.delete_user_comment', function (event) {
var autoid = $(this).attr('id');
var btn_primary_ref = $(this);
var r = confirm("Are you sure to delete a comment");
if (r == true) {
delete_comment(autoid, btn_primary_ref);
} else {
return false;
}
});
});
</script>
You can't do database operations directly in Javascript. What you need to do is to simply make a new AJAX request on success to a php file on the backend to update given table. However this would mean two AJAX requests to the backend, both of which manages database data. Seems a bit unnecessary. Why not just do the update operation after the delete operation in the php file itself?
add a server sided coded page that will execute your query.
example :
lets say you add a page named executequery.php.
with this code:
when you want to execute your query do the following :
$.post("executequery.php",//the URL of the page
{
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){
//this is the callback that get executed after the page finished executing the code in it
//the "data" variable contain what the page returened
}
);
PS : tha paramters sent to the page are conidired like $_POST variables in the php page
there is an other solution but its UNSAFE i recomand to NOT use it.
its to send the query with the paramters and that way you can execute the any query with the same page example :
$.post("executequery.php",//the URL of the page
{
query:"insert into table values("
param1:value1,
param2:value2....//if you want to pass some parameters to the page if not set it to null or {}
},
function(data){});
an answer from a previously question I asked here has posed another problem for me, as I am learning more and more about async calls I still can not figure out how to accomplish (as the previous answer showed me) a list which allows me to store and use data from a selected list item.
$('#home').live('pageshow', function(){
// creating object
var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
});
with js fiddle http://jsfiddle.net/amEge/3/
This code works excellent and will allow me to accomplish what I want but fist I need to populate the customerList from a ajax call. But from the "success" function I cannot seem to get the code to work.
$.post(postTo,{id:idVar} , function(data) {
customerList = data;
//alert(customerList);
})
When I move the code inside the ajax function it dose not work. I was just wondering if anyone could help me and maybe show me how to deal with this from asynchronous calls ?
Many Thanks
You need to change your page as below.
// I assume this is your dot net web service url
var webServiceURL = 'customer.asmx/GetCustomer';
// here home is your page's ID
$('#home').live('pageshow', function(){
getCustomerList();
});
function getCustomerList(){
param=JSON.strigify({id:'2'});
callWebService(param, webServiceURL, onGetCustListSuccess, onGetCustListFailed)
}
function onGetCustListFailed(){
alert("service request failed");
}
function onGetCustListSuccess(data, status){
// creating object
// replace previous line with below
// var customerList = JSON.parse('{"customerInAccount":[{"customer_name":"Jane Doe","auto_id":"21"},{"customer_name":"Jack Black","auto_id":"22"}]}');
var customerList = JSON.parse(data.d);
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// running a loop
$.each(customerList.customerInAccount, function(index,value){
listString += '<li><a href="#" data-cusid='+this.auto_id+'>'+this.customer_name+'</a></li>';
});
listString +='</ul>';
console.log(customerList);
//appending to the div
$('#CustomerListDiv').html(listString);
// refreshing the list to apply styles
$('#CustomerListDiv ul').listview();
// getting the customer id on the click
$('#customerList a').bind('click',function(){
var customerID = $(this).data('cusid');
alert(customerID);
});
}
function callWebService(param,url,successFunc,errorFunc){
if(errorFunc=='undefined'){
errorFunc=OnDataError;
}
$.ajax({
type: "POST",
url: url,
data: param,
contentType:"application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc,
beforeSend:function(){$.mobile.loading( 'show' );},
complete:function(){$.mobile.loading( 'hide');}
});
}
Hope this would help you out. If you have problems asks me here.
Correct me if I'm wrong, but I'll hazard a guess that your "live" code looks something like this:
$('#home').live('pageshow', function(){
// creating object
var customerList;
$.post(postTo, {id:idVar}, function(data) {
customerList = data;
//alert(customerList);
});
// creating html string
var listString = '<ul data-role="listview" id="customerList">';
// and all the rest...
If so, then your problem is that the code that's depending on your customerList variable being filled in ("all the rest...") runs immediately, rather than waiting for the response from your HTTP request to come back from the Web server. That $.post() doesn't wait around (or "block," as we say in the computer software programming game) while the HTTP transaction makes its way to the Web server and back. Instead, the rest of your code runs immediately, and then later, when that response comes back to the browser, the JavaScript engine dutifully executes your success function (or "closure," as we hm hmm hmmmm).
So what you'll want to do is put all this other code (the stuff that's dependent on customerList) into a separate function, then call that function from within your success closure. You won't even need your customerList variable then; you can just pass the new response data as an argument to your new function.
Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.