Spring controller does not load view - spring

I calling a controller via button click using ajax. I want it to load hello.html page but I want spring to do it not ajax.
What happens after I click the button is nothing but I'm sure the controller is being hit.
Here is the controller I'm calling via button click using ajax.
#RequestMapping(value="/submitName", method=RequestMethod.GET)
public String submitName(#RequestParam String name, Model model) {
System.out.println(name);
model.addAttribute("name", name);
return "hello";
}
Here is the ajax call.
$('#submit-button').on('click', function() {
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()}
});
});
Funny thing is in the chrome network tab it shows the page that I'm expecting. Here is a snippet.

I think everything is ok here, except you didn't mention how you want to show your page or where. You have to declare a container where your html returned from controller would appear, like under a div id or something like that.
So, just in your current html page, declare a new tag, may be <div id="current-page-id"></div>
Now, append the hello.html page to your current page using jquery:
$("#current-page-id").html(responseData);
So, basically, do this:
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()},
dataType: 'html',
success: function (responseData) {
$('#current-page-id').html(responseData);
},
});
Or, simply, load the page as separate html page, not via ajax.
Update:
instead of using ajax-as you asked for in comment section, do this as follows:
function getHtmlPage(String name)
{
location.href = 'submitName/' + name;
}
Now call your method on button click:
$('#submit-button').on('click', function() {
var name=$('#name').val();
getHtmlPage(name);
});

AJAX Calling just send the request to the server (controller) and received a response,
By default, It's dos not responsibility for reloading the page.
In this why when you click the button it hit the server-side but stay on the same page.
Simple there is two way you can load your new page ( hello.html )
1| With AJAX calling:
On the button click method, you have to explicitly load the page (Best practice in Ajax Success block)
adding this window load metbod:
window.location.href = "http://localhost:8080/hello.html";
Like:
$('#submit-button').on('click', function() {
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()}
window.location.href = "http://localhost:8080/hello.html";
});
});
2| Direct Http Call on the Button
HTML
<a class="btn btn-primary btn-lg pull-right" href="http://localhost:8080/hello" role="button">Hello Page</a>
JSP:
<a class="btn btn-primary btn-lg pull-right" href="${pageContext.request.contextPath}/hello" role="button">Hello page</a>
Thymeleaf
<a class="btn btn-xs" th:href="#{/hello})}">Hello Page </a>

Related

How does the browser load content of the previous page?

I'm creating a web page with laravel and the main menu pages contents are loaded with ajax. The problem is when I go back to the previous page with the back button of the browser, the browser loads not only the content received by the ajax call but the entire page. So I get two headers and two footers.
This is my code:
base.blade.php:
<html>
<body>
// list of menu
...
<div class="main">
#yield('main')
</div>
</body>
</html>
page.blade.php:
#extends('base')
#section('main')
<div class="main">
My page content.
</div>
#stop
// user clicks on the menu link and calls this script
script.js:
$(".menu_list").on("click", "a.menu_page", function(e) {
// get some variables
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (result) {
// get only div.main content from result
var mainContent = $(result).find("div.main").html();
// and load this data
$("div.main").html(mainContent);
} ...
I also tried not to return the full page data but only the main section in the controller:
controller.php:
...
if(Request::ajax()) {
return view('page')->renderSections()['main']; }
And in script.js:
success: function (result) {
$("div.main").html(result);
but it did not have any effect.
So I don't understand why the browser loads the entire page into the #yield section after returning to the previous page, although the controller only returned part of the page content.

codeigniter Click button to call a view

I am having a view with 2 buttons in my codeigniter view:
<div class="btn-main col-md-3 col-md-offset-3">
<button id="simu-mono" type="button" class="btn btn-default">SIMULATION MONO SITE</button>
</div>
<div class="btn-main col-md-3">
<button id="simu-multi" type="button" class="btn btn-default">SIMULATION MULTI SITE</button>
</div>
I would like to call another a controller to launch then a view when the button is clicked
I tried out to call the controller simu_mono by javascript, putted on /controller/simu_mono.php but doesn' t work
$(document).ready(function(){
$("#simu-mono").click(function(){
type:'GET',
url:'simu_mono'
});
$("#simu-multi").click(function(){
});
});
simu_mono.php:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$this->load->view('simu_mono');
echo 'Hello World!';
}
}
?>
Thanks for your helps
Cheers
Please, if u want to redirect only use following code:
$(document).ready(function(){
$("#simu-mono").click(function(){
window.location = base_url + "/simu_mono";
});
$("#simu-multi").click(function(){
window.location = base_url + "/simu_multi";
});
});
Note that you might need base_url, use this snippet to load base_url in JavaScript variable
<script>
base_url = <?= base_url()?>
</script>
put code above in some kind of view that is loaded always (before any other JavaScript code is executed)
Additional step would be to set up routes that take care of ugly underscore symbol (_)
something like:
routes.php
$route['simu-mono'] = "simu_mono";
$route['simu-multi'] = "simu_multi";
this way you go to your page and controller following way: yourserver.ufo/simu-mono and yourserver.ufo/simu-multi
You're not doing any class of AJAX call within your javascript. I assume you're using jQuery, so, your call should be something like:
$("#simu-mono").click(function(){
$.ajax({
url: "http://your-url.com/controller/method",
type: 'post', // <- Or get option, whatever you prefer
dataType: 'json', // <- This is important to manage the answer in the success function
//data: { param1: "value1", param2: "value2"}, <- You could add here any POST params you wanted
success: function(data){
if (data.view) {
$('#here_view').html(data.view); // <- '#here_view' would be the id of the container
}
if (data.error){
console.log(data.error);
}
}
});
});
This will call your method, where you will have to indicate you want to pass the view:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$return = array(
'view' => $this->load->view('simu_mono')
);
echo json_encode( $return );
}
}
?>
json_encode will allow you easily pass vars and data from PHP to your javascript, and manage them in the client view. As you see in the javascript, I added data.error, this is just in case you'll have more logic, maybe change the view you're sending, send an error if you sent data and want to control them, etc.
Of course, in your javascript you could take the url from the clicked button, and in data.view parat of the success function, you may print in the screen a modal, send the view to a container, whatever you wanted, XD

Laravel : Ajax delete with bootstrap modal dialog

I have a bootstrap modal dialog (see image below)
The red danger button (marked by xx) is where the action is happening. When that button is clicked - the uploaded file ( in this case - 2013-09-18_16h40_47.png) should be deleted while the modal dialog box is still open which is not what is happening right now. The download id is not getting passed to the controller method and the modal dialog is closed when the red button is clicked.
UI code :
{{ Form::open( array('route' => 'download.deletedownload','method' => 'post','id' => 'form-add-setting') ) }}
{{Form::hidden('downloadId',$download->id)}}
<button id="downloadDelete" type="submit" class="btn btn-xs btn-danger">xx</button>
{{Form::close()}}
The route looks like this
Route::post('deletedownload', array('uses' => 'DownloadsController#deletedownload', 'as'=>'download.deletedownload'));
and the controller method look like this
public function deletedownload()
{
if(Request::ajax()) {
dd("this is an ajax request");
};
var_dump('i am in the deletedownload method of the DownloadsController class');
$id = Input::get('id');
dd($id);
return Redirect::back();
}
Javascript :
$('#downloadDelete').click(function (e)
{
$.ajax({
type: 'POST',
url: '<?=URL::to('/')?>/deletedownload',
data: 'dataString',
dataType:'json',
success: function(result)
{
console.log(result);
}
})
});
and this is the output
string(66) "i am in the deletedownload method of the DownloadsController class" NULL
Notice that "this is an ajax request" is not getting echoed. Hence i have reasons to believe that is not an ajax request.
Any help would be well appreciated.
thanks
Where is your Javascript ? Ajax request should be sent explicitly with Javascript or jQuery from the client side. I don't know if Ajax is already attached on that modal button ?
UPDATE:
As I can see you are using named route on a server side, but in Ajax request you are pointing to URL ?

Render different Zend forms based on Ajax post request

I am trying to display different forms based on user type using Ajax post request. The request response works fine but I don't know how to display the form. For example, if the user selects parent then I want the parent form to be displayed and so on. I'm using ZF 1.12.
public function init() {
$contextSwitch = $this->_helper->getHelper('AjaxContext');
$contextSwitch =$this->_helper->contextSwitch();
$contextSwitch->addActionContext('index', 'json')
->setAutoJsonSerialization(false)
->initContext();
}
public function indexAction() {
$this->view->user = $this->_userModel->loadUser($userId);
//if($this->_request->isXmlHttpRequest()) {
//$this->_helper->layout->disableLayout();
//$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isPost()){
$type = $_POST['type'];
$this->view->userForm = $this->getUserForm($type)->populate(
$this->view->user
);
}
}
And here's what I have on the client side. What do I need to write in the success section?
<script type="text/javascript">
$(document).ready(function(){
$('#userType').on('change', function(){
var type = $(this).val();
select(type);
});
});
function select(type) {
$.ajax({
type: "POST",
url: "admin/index/",
//Context: document.body,
data: {'type':type},
data: 'format=json',
//dataType: "html",
success: function(data){
// what to do here?
},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
});
}
</script>
<form id="type" name="type" method="post" action="admin/index">
<select name='userType' id='userType' size='30'>
<option>admin</option>
<option>parent</option>
<option>teacher</option>
</select>
</form>
<div id="show">
<?php //echo $this->userForm;?>
</div>
If your ajax request form returns you the HTML from the Zend_Form, you could simply write the HTML in the #show div.
In you view you will need to do this :
echo $this->userForm;
This way, all the required HTML will be written on the server side, before sending the response to the HTML page. In the HTML page you then just have to write the response in the right location with the method $('#show').html(data). You also have to make sure that each of your forms has the right action when you render them.
The other option would be to have all three forms hidden in your page (through Javascript) upon loading and based on the select (Generated with JS), display the right form. This way you don't have to load data from an external source and if someone have JS disabled, he still can use the application. On the other hand, this method will have each page load about 1/2 a KB more of data.

codeigniter and tab contents

I have some tabs whose contents are fully functional parts of my website.
For instance, in my admin area, I have tabs [add/delete album][add photo][delete photo]. I'm technically dividing the admin area via tabs.
I'm using ajax to load the content into these tabs. tab content area is a div.
The view that is inside the tab content area also uses ajax to load stuff.
These are ajax calls that operates inside the tab content area.
Everything works fine as long as the view inside the tab content area stays same or only part of it changes. But when certain interactions inside tab content area return a whole new view, tab content area would not show them.
I know what happens is that this new view that is returned is not passed into the tab content area div.
In firebug, I can see that ajax success function response shows the new view that is returned.
But I do not know how to pass that new view to the tab content area.
I would appreciate it if someone could help me out in explaining how this could be solved or how contents inside tabs are managed in CI.
adminTabsview.php
<ul id="adminTabs">
<li ><?php echo anchor('#album_addDelete', 'Album Add/Delete'); ?></li>
</ul>
<div id="adminTabsContent"></div>
$(document).ready(function(){
$('#adminTabs a').on({
click: function (evt){
evt.preventDefault();
var page = this.hash.substr(1);
adminTabsAjaxCall(page);
}
});
});
function adminTabsAjaxCall ($data){
$.ajax({
type: "POST",
url: "index.php/adminsite_controller/"+ $data + "/",
dataType: "html",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
function adminTabContent (data){
$('#adminTabsContent').html(data);
}
albumsEditDeleteView.php
(this is a view that gets loaded into the tab contentarea div)
<div id="adminTabsContent">
<div id="albumList">
<ul>
<li>
Asdf
<a class="add" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/add_album/301/Asdf/1/28/0">[ add ]</a>
<a class="delete" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/delete_album/301/Asdf/1/28/0">[ delete ]</a>
</li>
</ul>
</div>
</div>
$(document).ready(function(){
$('#albumList').on({
click: function (evt){
evt.preventDefault();
var $clickedElement = evt.target.tagName;
if ($clickedElement == 'A' ){
var urlarray = url.split('/');
$chosen.albumid = urlarray[8];
$chosen.albumname = urlarray[9];
$chosen.lft = urlarray[10];
$chosen.rgt = urlarray[11];
$chosen.nodeDepth = urlarray[12];
if ($class == 'add'){
albumajaxcall($chosen);
}
if ($class == 'delete'){
deleteajaxcall($chosen);
}
}
}
});
});
function albumajaxcall($data){
$.ajax({
type: "POST",
url: "index.php/Adminsite_Controller/add_album/",
dataType: "json",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
}
function adminTabContent(data){
$('#adminTabsContent').html(data);
}
//heres the view file that has to replace the original view inside
//tabcontent area
//addnode_view.php
<?php echo form_open('Albums_Controller/update_albumSet');?>
<input type="text" name="newAlbum" id="newAlbum" value=""/>
<input type="submit" name="submit" value="Submit" />
<?php echo form_close();?>
<?php
//heres the controller function
function add_album(){
$levelData ['albumid'] = $this->input->post('albumid');
<!-- removed-->
$levelData ['main_content'] = 'addnode_view';
$this->load->view('includes/template', $levelData);
}
//And heres the controller method that loads
//the original page (albumsEditDeleteView.php) - this is the original view
//that gets loaded into the tab- I get stuck when this view
//has to be **totally** replaced through links in the view)
function album_addDelete(){
$allNodes ['myAlbumList'] = $this->Albums_Model->get_albumList();
echo $this->load->view('albumsEditDelete_view', $allNodes);
}
thanx in advance.
basically what you need to do is load whatever new view youll be putting in the tab in the controller function(adminsite_controller/whatever function) that is handling your ajax.
this will basically echo out the view file, which will be viewed as the success variable of your ajax function.
so you have something like this then for the success part of your ajax
success:function(msg){adminTabContent(msg);}
and in your controller in codeigniter you'll load a view the standard way, but since this will be only loading a piece of the page you may need to create a new view file thats just the div that will be there. You will do all your data gathering the same way you would if it wasn't ajax.
$data['some_data'] = $this->some_model->some_function();
$this->load->view('someview', $data);

Resources