Joomla 3.2, get works, post doesn't - joomla

So I have this JS code:
myClass = new Class({
initialize: function() {
this.btnSubmit = document.id('btnSubmit');
this.sendData = new Request({
"url":"/",
"method":"post",
"data": {"option":"com_my4quiz", "controller":"conduit", "task":"save", "hrdata":"foo"},
"onSuccess": this.handleResult.bind(this)
});
this.btnSubmitObserver = function() { this.sendData.send(); }.bind(this);
this.btnSubmit.addEvent("click", this.btnSubmitObserver);
},
handleResult: function(stuff) {
//do stuff
}
});
If I'm posting this to my Joomla 3.2.0 component it returns the home page. As soon as I switch to get, it sends the data to the correct place and I get what I expect.

I think its due to your controller page loads the entire view.
This may happen due to inside your controller save(). function not rendering any specific view .
So the solution is after the Ajax result just render the proper layout or just put an exit();
At the end of your save()
exit();
or
$view->setLayout($layoutName);
$view->display();
Hope its helps..

Related

How to pass variables from Controller to View without refreshing the Web Page in Laravel?

Whenever there is a call to Controller inside View, I want the Controller to return some variables to the View and do not refresh the View.
Already know:
return view("webpage" , compact('variable1', 'variable2') );
What I expect to achieve:
return compact('variable1', 'variable2');
This will not return the Webpage but only some of the variables.
Edit:
Thinking it from a complete different perspective, The question maybe rephrased as such
Is there a way to manipulate REQUEST variables of a web page from the controller? This way, i would be able to get new variables from the Controller without the web page being Refreshed.
With out much to work with, here is an example:
Ajax call:
$.ajax({
url: '/your/route/',
type: 'GET',
data: {getVariable: formInputValue},
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log('Failed');
});
Controller Function:
public function getVariable(Request $request){
$resault = $request->getVariable;
return response()->json($results);
}
Update: as per comments on this answer try this and see if it works for you.
In your controller where you fetch records instead of using a ->get();
change it to paginate(5); this will return 5 records per page. and on your view at the bottom of your </table> add {{ $variable->links() }}

View returning in popup laravel 5.4

I am returning a view from controller, but instead of opening new page, the view is opening in popup which i assume is error message popup,. i am new in laravel.
Controller Code
public function postRegister () {
return view('front.member.registerpayment')->with('amountUSD', $data['btc_withcom']);
}
You can do this using AJAX request.
In your controller…
public function postRegister () {
// do something to get your data
return response()->json(
[
'data'=>$your_data
]
);
}
Then make a ajax request
First import jquery.
Then
$.ajax({
url: ‘your url’,
method: ‘POST’
data: ‘pass any data to controller’
success: function(data){
// invoke popup with data
// you can easily do this with jquery UI library
}
})
Here is the complete example to open dialog box.
Hint: append your data to html before invoking

Keeping data in-sync with server

This is my stack : Ember.js + Express/Node.js
Say i have an Endpoint as \posts, it will return an array of objects.
and i have following template named allPosts :
{{#each post in content}}
<p>{{post.body}} </p>
{{/each}}
Route:
App.AllPosts =Ember.Object.extend({
body : null
})
App.AllPostsRoute = Ember.Route.extend({
setupController : function(controller,model){
controller.set('content',model);
}
});
And controller as
App.AllPostsController = Ember.Controller.extend({
actions: {
save : fucntion(){
// Get And update data from server via ajax
}
}
});
I want to keep data in sync with data on server, for this i planned to use setInterval and call the save action above every 1000ms to update the data. But it doesn't work. i used setInterval like this
setInterval(App.AllPostsController.actions.save,3000);
I DONT want to use Ember Data. As the data is dependent on another Node app which runs server side.
You're trying to run an action on a type, not an instance of the controller. Instead you should start saving when you actually hit the route and controller, setupController is a good place to accomplish this.
App.AllPostsRoute = Ember.Route.extend({
setupController : function(controller,model){
controller.set('content',model); // in this code model would be blank, I'm assuming you're leaving out code
this.startSaving(controller);
},
willTransition: function(transition){
//if I'm leaving, this.stopSaving();
},
isSaving: false,
startSaving: function(controller){
this.set('isSaving', true);
this.realSave(controller);
},
realSave: function(controller){
if(!this.get('isSaving')) return;
Em.run.later(function(){
controller.send('save');
}
},
stopSaving: function(){
this.set('isSaving', false);
}
});

Page navigation using ajax in codeigniter

IN codeigniter I am repeatedly using the controllers to load all the templates of my page....
I have divided the page into header, top navigation, left navigation and content and footer.
This is what I do at present
public function get_started() {
if (test_login()) {
$this->load->view('includes/header');
$this->load->view('includes/topnav');
$this->load->view('includes/leftbar');
$this->load->view('login_nav/get_started');
$this->load->view('includes/footer');
} else {
$this->load->view('errors/needlogin');
}
}
Is there any jquery-ajax helpers or plugins in codeigniter which would allow me to keep header footer and topnavigation static and allow me to load specific views using ajax.
thanks in advance..
You can use the constructor to set your static header:
//in your controller
public $data;
function __construct()
{
$this->data['header'] = 'static_header';
$this->data['static_footer'] = 'static_footer';
}
function get_started(){
if (test_login()) {
$this->data['subview'] = 'login_nav/get_started';
} else {
$this->data['subview'] = 'errors/needlogin';
}
$this->load->view('template',$this->data);
}
function get_page(){
$view = $this->load->view('your_dynamic_view','',TRUE);
print json_encode(array('success' => TRUE, 'view' => $view);
}
// in your template.php
<div id="header"><?php echo $this->load->view('header');?></div>
<div id="subview"><?php echo $this->load->view('subview');?></div>
<div id="footer"><?php echo $this->load->view('footer');?></div>
// in your script - used to load dynamic view on you subview div
<script type="text/javascript">
$.get('controller/get_page',{},function(data){
if(data.success){
$('#subview').html(data.view);
}
},'json')
</script>
Message me if there's a problem with my code
Happy coding ---> :D
The answer from PinoyPal is theoreticaly correct, but it didn't work for me in practice because it lacks one major detail: a route.
Take a look at this part of their script:
// in your script - used to load dynamic view on you subview div
<script type="text/javascript">
$.get('controller/get_page',{},function(data){
if(data.success){
$('#subview').html(data.view);
}
},'json')
</script>
Here in place of 'controller/get_page' there should be a url for an actual GET request. This is how it is generally supposed to look:
$("a.your_navigation_element_class").on('click',function(e){
e.preventDefault(); //this is to prevent browser from actually following the link
var url = $(this).attr("href");
$.get(url, {}, function(data){
if (data.success){
$('#subview').html(data.view);
}
},'json')
});
Now here's a question: where will this GET request end up? In the default controller route, that's right. This is why you need to 1) modify your request url and 2) set up a route, so that this request will be passed to an ajax-serving controller. Or just add an ajax-serving function to your default controller and re-route ajax requests to it.
Here follows how it should all look wrapped up
In ...\application\controller\Pages.php:
class Pages extends CI_Controller {
...
public function serve_ajax ($page) {
$view = $this->load->view($page, '', TRUE);
print json_encode( array('success' => TRUE, 'view' => $view);
}
...
}
In ...\application\config\routes.php:
...
$route['ajax/(:any)'] = 'pages/serve_ajax/$1';
On your page:
...
<body>
...
<div id="page"></div>
...
<script>
$("a.navigation").on('click',function(e){
e.preventDefault();
var url = $(this).attr("href");
$.get("/ajax" + url, {}, function(data){
//The trailing slash before "ajax" places it directly above
//the site root, like this: http://yourdomain.com/ajax/url
if (data.success){
$('#page').html(data.view);
}
},'json')
});
</script>
</body>
And you're all set.

MVC3 redirect to action after ajax call

In an ASP.NET MVC3 Application I have a button in the view.
When the button is clicked a function is called and it jquery ajax call is made to save items to the database
function SaveMenuItems() {
var encodeditems = $.toJSON(ids);;
$.ajax({
type: 'POST',
url: '#Url.Action("SaveItems", "Store")',
data: 'items=' + encodeditems + '&storeKey=#Model.StoreID',
complete: function () {
}
}
});
}
What i want is after the items are saved to the database I want to redirect to another view. (Redirect to action)
How can I do that?
I tried to use return RedirectToAction("Stores","Store") in the controller at the end of the SaveItems function. But it is not working
I also tried to add window.location.replace("/Store/Stores"); in the complete function of the ajax call but didn't work either
Any help is greatly appreciated
Thanks a lot
You can use javascript to redirect to the new page. Set the value of window.location.href to the new url in your ajax call's success/complete event.
var saveUrl = '#Url.Action("SaveItems","Store")';
var newUrl= '#Url.Action("Stores","Store")';
$.ajax({
type: 'POST',
url: saveUrl,
// Some params omitted
success: function(res) {
window.location.href = newUrl;
},
error: function() {
alert('The worst error happened!');
}
});
Or in the done event
$.ajax({
url: someVariableWhichStoresTheValidUrl
}).done(function (r) {
window.location.href = '#Url.Action("Stores","Store")';
});
The above code is using the Url.Action helper method to build the correct relative url to the action method. If your javascript code is inside an external javascript file, you should build the url to the app root and pass that to your script/code inside external js files and use that to build the url to the action methods as explained in this post.
Passing parameters ?
If you want to pass some querystring parameters to the new url, you can use this overload of the Url.Action method which accepts routevalues as well to build the url with the querystring.
var newUrl = '#Url.Action("Stores","Store", new { productId=2, categoryId=5 })';
where 2 and 5 can be replaced with some other real values.
Since this is an html helper method, It will work in your razor view only,not in external js files. If your code is inside external js file, you need to manually build the url querystring parameters.
Generating the new url at server side
It is always a good idea to make use of the mvc helper methods to generate the correct urls to the action method. From your action method, you can return a json strucutre which has a property for the new url to be redirected.
You can use the UrlHelper class inside a controller to do this.
[HttpPost]
public ActionResult Step8(CreateUser model)
{
//to do : Save
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Stores", "Store");
return Json(new { status = "success", redirectUrl = url });
}
Now in your ajax call's success/done callback, simply check the return value and redirect as needed.
.done(function(result){
if(result.status==="success")
{
window.location.href=result.redirectUrl;
}
else
{
// show the error message to user
}
});
In action you can write this:
if(Request.IsAjaxRequest()) {
return JavaScript("document.location.replace('"+Url.Action("Action", new { ... })+"');"); // (url should be encoded...)
} else {
return RedirectToAction("Action", new { ... });
}
Try
window.location = "/Store/Stores";
Instead.

Resources