How does the browser load content of the previous page? - ajax

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.

Related

Spring controller does not load view

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>

AJAX: if right click to open a new tab, render the whole page

I use AJAX on a link to insert data into a certain <div> in the same page. However, if the user right-clicks and opens in a new tab, the new page will contain only the data, without other page elements. How can I do to render a whole page for a right-click-new-tab?
HTML:
<a class=".updateContent" href="...">The link</a>
...
<div id="content></div>
AJAX:
$(document).ready(function() {
$('.updateContent').click(function() {
var url = $(this).attr('href');
$('#content').load(url);
return false;
});
});
Don't use an href. With an href the user has the option to open in a new tab/window or copy/paste no matter what you do (except maybe disable right click entirely but that's annoying). I suggest something like the following:
<a class="updateContent" data-url="...">the link</a>
Then your jQuery
var url = $(this).data('url');

Bootstrap popover and loading content with ajax and django

I know it has been given some answers but I will go for it :). As the title says i want to add popover bootstrap but with ajax loaded content. my html, but i want a Loading message to appear first and then the content.
<p class='entry' data-adjaxload = '/calendar/entry/1'>Title1</p>
<p class='entry' data-adjaxload = '/calendar/entry/2'>Title2</p>
<p class='entry' data-adjaxload = '/calendar/entry/3'>Title3</p>
my django view is the following
def entry_details(request, entry_id):
entry = get_object_or_404(Entry, pk=entry_id)
args = dict(entry=entry, user=request.user)
if request.is_ajax():
return render_to_response('mycal/ajax/entry_details.html', args)
else:
entry_form = EntryForm(instance=entry)
args.update(entry_form=entry_form)
return render_to_response('mycal/entry_details.html', args)
Pretty simple. I am using the same view to either load html content via ajax in the popover, or a details page via normal get request
the ajax details page:
<div class="entry">
<p>{{entry.title}}</p>
<p>{{entry.date}}</p>
<p>{{entry.customer}}</p>
</div>
and the script
$(document).ready(function(){
$('p.entry').each(function (){
var i = $(this);
$(i).bind('mouseenter', function(){
i.popover({
html:True,
title:i.html(),
content:'Loading'
}).popover('show');
$.ajax({
url:i.data('ajaxload'),
dataType:'html',
success:function (data){
i.popover({content:data}).popover('show');
}
});
});
$(i).bind('mouseleave', function(){
i.popover('hide');
});
});
});
But whilst it does run tha ajx and fetches the html, it won't load them onto the popover. How can I change that?
Just fiddled what you are looking for with popover content being updated dynamically using echo/json.
Just roll over the p element and wait for the 3 second delay.
If as you say, the data is being loaded properly then the only change needed is:
var popover = i.data('popover');
popover.options.content = data.text;
i.popover('show');

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