I have a view file that is rendered from the default SiteController. This view file makes an ajax call to an action getdetails in a different controller called A1Controller. I want to know how to write the url in the ajax call and if there is anything that has to be changed in the UrlManager in web.php configuration file.
This is my ajax call :
ajaxCall = function () {
$.get('how/to/write/this/url?', function (data) {
var jsondata=JSON.parse(data);
GenerateTable(data);
setTimeout('ajaxCall()', 5000);
});
};
Can someone help me out please. Thanks in advance.
Inside the view file:
<?php
$ajaxUrl = \yii\helpers\Url::to(['controller/action-name']);
$this->registerJs("
ajaxCall = function () {
$.get('$ajaxUrl', function (data) {
var jsondata=JSON.parse(data);
GenerateTable(data);
setTimeout('ajaxCall()', 5000);
});
};
");
Related
I have created an ajax.php file on my server and send id to the file using ajax with jquery.
I want to run db queries in that ajax.php file to get the result.
I am unable to do this.
Can you please help me.
Jquery Code:
$('.invitebyemail').click(function(){
var email = $('#add-members-event-email').val();
var eventid = $('.eventid').val();
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
var APP_URL = {!! json_encode(url('/')) !!};
alert(APP_URL);
alert(url);
$.ajax({
url: APP_URL+'/ajax.php',
type: 'POST',
data: { id: eventid },
success: function (data) {
alert(data);
},
error: function () {
alert('error');
}
});
return false;
});
Ajax File Code:
use DB;
$eventid = $_POST['id'];
echo $eventid;
$users = DB::table('users')->get();
print_r($users);
Thanks
If you're using laravel I don't belive that using .php files like that would be the correct way of doing it... it's not really following the MVC patterns.
I recomend creating a controler php artisan make:controller MyController
creating a function as this on the controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Session;
use Auth;
use Response;
use DB;
use App\User;
class MyController extends Controller{
public function getUsers(Request $request){
$users = DB::table('users')->get();
// If you need access to request parameters use this ( $request->id ) being id the parameter name
return response()->json(["users" =>$users]);
}
}
creating a route in ProjectFolder/routes/web.php like this
Route::post('/getUsersAjax',[
'uses'=>'MyController#getUsers',
'as'=>'getUsers'
]);
And in your jquery dont forget to add the _token to your data data: { id: eventid , _token : token},
(if you need this token you can in a .blade.php file, your view, make this
<script>
var token = "{{Session::token()}}";
var urlRequest = "{{route('getUsers')}}";
</script>
)
https://laravel.com/docs/5.4/controllers
https://laravel.com/docs/5.4/routing
This is my controller which is calling the login service
mod.controller("loginCtrl",function($scope,loginService,$http)
{
$scope.Userlogin = function()
{
var User = {
userid :$scope.uname,
pass:$scope.pass
};
var res = UserloginService(User);
console.log(res);
alert("login_succ");
}
});
And this is the login service code which takes the User variable and checks for username & password
mod.service("loginService",function($http,$q) {
UserloginService = function(User) {
var deffered = $q.defer();
$http({
method:'POST',
url:'http://localhost:8080/WebApplication4_1/login.htm',
data:User
}).then(function(data) {
deffered.resolve(data);
}).error(function(status) {
deffered.reject({
status:status
});
});
return deffered.promise;
// var response = $http({
//
// method:"post",
// url:"http://localhost:8080/WebApplication4_1/login.htm",
// data:JSON.stringify(User),
// dataType:"json"
// });
// return "Name";
}
});
I have created a rest api using springs which upon passing json return back the username and password in json like this
Console shows me this error for angular
You need to enable CORS for your application for guidance see this link
https://htet101.wordpress.com/2014/01/22/cors-with-angularjs-and-spring-rest/
I prefer to use Factory to do what you're trying to do, which would be something like this:
MyApp.factory('MyService', ["$http", function($http) {
var urlBase = "http://localhost:3000";
return {
getRecent: function(numberOfItems) {
return $http.get(urlBase+"/things/recent?limit="+numberOfItems);
},
getSomethingElse: function(url) {
return $http.get(urlBase+"/other/things")
},
search: function (searchTerms) {
return $http.get(urlBase+"/search?q="+searchTerms);
}
}
}]);
And then in your controller you can import MyService and then use it in this way:
MyService.getRecent(10).then(function(res) {
$scope.things = res.data;
});
This is a great way to handle it, because you're putting the .then in your controller and you are able to control the state of the UI during a loading state if you'd like, like this:
// initialize the loading var, set to false
$scope.loading = false;
// create a reuseable update function, and inside use a promise for the ajax call,
// which is running inside the `Factory`
$scope.updateList = function() {
$scope.loading = true;
MyService.getRecent(10).then(function(res) {
$scope.loading = false;
$scope.things = res.data;
});
};
$scope.updateList();
The error in the console shows two issues with your code:
CORS is not enabled in your api. To fix this you need to enable CORS using Access-Control-Allow-Origin header to your rest api.
Unhandled rejection error, as the way you are handling errors with '.error()' method is deprecated.
'Promise.error()' method is deprecated according to this and this commit in Angular js github repo.
Hence you need to change the way you are handling errors as shown below :
$http().then(successCallback, errorCallback);
function successCallback (res) {
return res;
}
function errorCallback (err) {
return err;
}
One more thing in your code which can be avoided is you have defined a new promise and resolving it using $q methods, which is not required. $http itself returns a promise by default, which you need not define again inside it to use it as a Promise. You can directly use $http.then().
I am developing a web application using the Spring framework and Thymeleaf.
I have created a drop down menu, but I want something else on the page to appear when a certain option in the drop down menu is selected. By selected I mean when the option in the menu is clicked on and nothing more. I do not mean complete form submission.
I have read through the docs but found no solution.
Any ideas?
Thanks
You ca use JS using th:inline like this, explanation is on comment
JS code
<script th:inline="javascript">
//Declare the URL of RequestMapping to use
//Do no change format
/*[+
var urlToload = [[#{/path/spring}]];
var anotherUrlToUse = [[#{/another/url?param=}]];
+]*/
//Handle you jquery event
$('body').on('click', '.dropdown-menu', function (e) {
var t = $(this);
//Sending your ajax request
$.ajax({
url: urlToload,
method: 'POST',
data: {
optionSelected: t.val()
}
})
/**
* Execute when your request is done
* #param {type} data : the page result of your Request *
*/
.done(function (data) {
$("#receiver").html(data);
})
//Execute on fail
.fail(function (xhr, ajaxOptions, thrownError) {
console.log("ERROR");
//Use anotherUrlToUse with GET METHOD to redirect
window.location.replace(anotherUrlToUse+404);
});
});
</script>
Controller code
#RequestMapping(value = "/path/spring", method = RequestMethod.POST)
public String controllerMethod(Model model, #RequestParam("optionSelected") String optionSelected) {
/**
* Do your job
* Your code
*/
return "page/result";
}
Having trouble loading an external json file and having it's contents display on my view. I've included my view, controller and services code. What do I need to change?
view.html
<div ng-controller='BaseCtrl'>
<table class="table table-hover">
<tbody>
<tr class="tr-sep" ng-repeat="example in examples" ng-click="showUser(example)">
<td>{{example.name}}</td>
<td>{{example.type}}</td>
<td>{{example.size}}</td>
</tr>
</tbody>
</table>
</div>
controller.js
'use strict';
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, data) {
$scope.examples = data.getAllExamples();
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
service.js
'use strict';
angular.module('projyApp')
.service('data', function data() {
var examples;
var getAllExamples = function () {
$http.get("../../TestData/Examples.json").success($scope.examples = data.examples);
};
});
Your service code isn't correct. I see the following problems:
You're creating a local variable getAllExamples that's not accessible from outside the service;
You're using the $http service, but that dependency isn't expressed in the service constructor;
You're trying to update the scope from the service, but it's inaccessible from there. Plus, the $scope variable is not even defined inside the service code.
Here's how your service could look like:
.service('data', function($http) {
this.getAllExamples = function(callback) {
$http.get("../../TestData/Examples.json")
.success(function(data) {
if (callback) callback(data.examples);
});
};
});
And your controller code would be like this:
.controller('BaseCtrl', function ($scope, data) {
data.getAllExamples(function(examples) {
$scope.examples = examples;
});
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
});
You could ditch the callback in the getAllExamples function and work directly with the $http.getreturned promise, but that's a bit more complicated.
Update Added a Plunker script to illustrate the code above.
Main module definition should look like:
angular.module("projyApp",[/*dependencies go here*/]);
Service should look like
//this use of module function retrieves the module
//Note from comments in angular doc: This documentation should warn that "angular.module('myModule', [])" always creates a new module, but "angular.module('myModule')" always retrieves an existing reference.)
angular.module('projyApp')
.service('dataService', [/*dependencies,*/function() {
var service = {
examples:[],
getAllExamples = function () {
$http.get("../../TestData/Examples.json").success(function(returnedData){examples = returnedData});
}
}
return service;
});
Controller should look like:
angular.module('projyApp')
.controller('BaseCtrl', function ($scope, dataService) {
$scope.examples = [];
$scope.showUser = function(example) {
window.location = '#/user/' +example.size;
};
$scope.$watch(function(){return dataService.examples}, function(newVal,oldVal) {$scope.examples = newVal});
});
Also you can add
debugger;
on an line to trigger Chrome to break (like a breakpoint but without having to dig through the scripts at run-time) so long as the Debugging Panel is open (F12)
You should use a callback instead of assigning in to a scope in you data service. By doing that, you can use this function in multiple controllers an assign values to appropriate scopes.
Data Service
var getAllExamples = function (callback) {
$http.get("../../TestData/Examples.json").success(function(data) {
if (typeof callback === "function") callback(data);
});
};
Controller
data.getAllExemples(function(data) {
$scope.examples = data;
});
EDIT
Another what is to create a promise object.
Data Service
var getAllExamples = function () {
return $http.get("../../TestData/Examples.json");
};
Controller
var promise = data.getAllExemples();
promise.then(function(data) {
$scope.examples = data;
});
EDIT 2
In your service, you need to return your functions
angular.module('projyApp')
.service('data', function data() {
var examples;
return {
getAllExamples: function () {
$http.get("../../TestData/Examples.json").success(...);
}
};
});
I have below ajax query which returns me json from controller
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=1",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
the controller action is as below
[System.Web.Http.ActionName("GetHomeTab")]
public HomeTabModel GetHomeTab(int bizId)
{
var outlet = db.Info.Where(t => t.BizId == bizId).SingleOrDefault();
return new HomeTabModel
{
HomeDesc = outlet.BizHomeDesc,
HomeTabText = outlet.BizHomeTabText
};
}
Now my question is: curently i am sending hard coded value of bizId to web api. I want to send this value dynamically. How can i achieve this? I have that value in my route config file. The code is as below-
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{bizId}",
defaults: new { controller = "Home", action = "Index", bizId = 1 }
);
}
I am new to this. Please help! Thanks in advance!
no, actually after much research, i came up with this solution and this works fine for me....
In controller,
public ActionResult Index(int bizId)
{
ViewBag.BizId = bizId;
return View();
}
and in View,
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab?bizId=#ViewBag.BizId",
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
You can pass a data object as part of the GetJson call.
$(document).ready(function () {
$.getJSON(
"api/OutletPOC/GetHomeTab",{bizId : 1},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
});
Taking this one step further you could wrap this in a function.
function makeCall(id)
{
$.getJSON("api/OutletPOC/GetHomeTab",{bizId : id},
function (data) {
$("#homeTabDesc").append(data.HomeDesc);
$(".test").hide();
$("#hometabcontent").show();
});
}
Also look into using promises.
$.getJSON().then().done();