Redirecting to a page via ajax - javascript

I am trying to Ajaxify a normal page redirect.
ASPX (View: Parent.aspx):
<a id="GetContent" href="#">Go to Content Page</a>
ASPX (View: Content.aspx):
<div id="content">
...
</div>
Controller (ContentController.cs):
public ActionResult Index(id)
{
var content = _db.GetContent(id);
return View("Content");
}
JS:
$(document).on("click", "#GetContent", function () {
location.href = "/Index/3";
});
I tried this. This works, however, the url in the URL bar does not change.
$(document).on("click", "#GetContent", function () {
$("#content").load("/Index/3");
});
So when you click on the link, currently it posts back normally and then redirects to ~/Content/3 (i.e. no ajax). What I want is to immediately go to the Content page, and then display a loading indicator while the content is being fetched. I know I probably have to use jQuery.load() to do this, but not quite sure how to put things together.
Any help is appreciated!

I think this is what you are looking to do...
Index.aspx:
<div id="content">
...
</div>
<script>
$(document).ready(function() {
$.ajax({
url: '/Content/Details/3', // <-- Can use #Html.ActionLink here, to utilize routing a bit.
success: function(data) {
$('#content').html(data);
}
});
});
</script>
ContentController.cs:
public ActionResult Index(id)
{
return View("Index");
}
public ActionResult Details(id)
{
var content = _db.GetContent(id);
return PartialView("_Details", content);
}
If you put a loader.gif in the div initially I think you'll get the behavior you are looking for. You'll also need to make sure you have the _Details view created, and displaying whatever is in your model (var content).

i would link jquery (through
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
) and then use
var checking = "<img src='ajax-loader.gif'/>";
$("#content").innerHTML=checking
$("#content").load("/content/3");
to load it in the page

Related

Updating page content except one div using Ajax

I am trying to make a website that loads all pages using AJAX. Here's a simple piece of JS that does that:
$.ajax({
url: url,
type: 'GET',
success: function(html) {
document.open();
document.write(html);
document.close();
}
});
This obviously works and updates my current page content.
The problem is I want to keep one div unchanged (let's call it .player-wrapper). This div is actually an <audio> wrapper which I want to keep playing (and this is the reason I AJAXified the entire website). Is this possible?
Every time you render a page, you can initialize plugins/libraries like this:
const App = function() {
return {
init: function() {
// Do all your JS stuff here
console.log('App initialized.');
},
render: function(url) {
$.get(url, data => {
$('main').html(data);
}, 'html').done(() => {
this.init();
});
}
};
}();
$(function() {
App.init();
$(document).on('click', '[data-page="ajax"]', function (e) {
e.preventDefault();
const url = $(this).attr('href');
App.render(url);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<audio class="player-wrapper" src="https://www.free-stock-music.com/music/alexander-nakarada-wintersong.mp3" controls autoplay></audio>
<main>
<h1>Initial page.</h1>
</main>
<nav>
Go to dummy page
</nav>
If you want to keep the audio tag with the player-wrapper class let's take this html as our base:
<body>
<audio class="player-wrapper"></audio>
<div class="page-content"></div>
</body>
Then with the following code you can place the html you received from the ajax request:
document.querySelector('.page-content').innerHTML = html;
Just don't write the html to the document, but place it in an already existing element like the div with the page-content class in this example.
And when you need to execute script tags in the html you can use jQuery's append method (since you are already using jQuery)
$('.page-content').append(html);
One thing you can do is copy the .player-wrapper before you write.
$(".overridebutton").on("click", function () {
var html = '<div class="override">Im a new div overriding everything except player-wrapper</div>';
var exception = $(".player-wrapper").html();
console.log(exception);
document.write(html + exception);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="everything">
<div class="sub-1">
Hello Im sub-1
</div>
<div class="sub-2">
Hello Im sub-2
</div>
<div class="sub-3">
Hello Im sub-3
</div>
<div class="player-wrapper">
I am player wrapper
</div>
</div>
<button class="overridebutton">Override</button>

Check for change in inner html by html Tag

I currently load a html page into a <DIV> in my page. using this code
$.ajax({
url: 'myApi.php?user=' + user + '&url='+ URL2add,
success: function(html) {
var newHTML = "<object id='webloader' data='" + html + "'></object>";
$("#exweb").fadeOut(500, function () {
$("#exweb").html(newHTML).fadeIn(5000, function() {
alert("done");
});
});
}
});
So i want to do a check or preferably get a alert once that page loaded changes. which is in the data tag that comes from the html coining back from the ajax call.
I have tried document.getElementsByTagName
I know there has to be a way to get the new data info in that object .
i would prefer an alert each time the page changes from what comes back from the ajax call
i have updated the code like this...
$(document).on('contentchanged', '#exweb', function() {
alert('WOO?');
});
$.ajax({
url: 'Api.php?user=' + user + '&url='+ URL2add,
success: function(html) {
var newHTML = "<object id='webloader' data='" + html + "'></object>";
$("#exweb").fadeOut(50, function () {
$("#exweb").html(newHTML).fadeIn(50, function() {
$('#exweb').trigger('contentchanged');
});
});
}
});
But this is only working on initial change
i need to know when that page changes again.. say if someone clicks on a link that will change the page in DIV or if its a redirect page.
i want to know whenever that page changes to something after i loaded it from my ajax call
should it not be as easy as getting the information between data=""
<object id="webloader" data="http://google.com"></object>
and how do i get back that info? i have tried document.getElementsByTagName
you can do something like this after ajax.
$.ajax({...}).done(function() {
alert('page loaded');
});
$.ajax({/* your AJAX */}).done(function() {
alert(/*your text*/"page loaded!");
});
I think you could try this $("div").load("your_url.php?parameters"); the page you want to load could have the following <body onload="alert('Page Loaded')">
Update:- if you dont have the access of the webpage then use this $("div").load("your_url.php?parameters",function(){alert("Page loaded")});

Refresh view page without reloading the page manually

I have to refresh view page without clicking on refresh button.
Javascript code:--
<script type="text/javascript">
$(function () {
var metaId = $("#ID").val();
var img = $("##name input[type=hidden]").val();
if ("#found" == "False") {
$.post(rootURL + "Picture/AddThumb", { guidOrName: img, meta: metaId, id: contentId }, function (data) {
//arrangePoster([data]);
});
}
});
</script>
Post sometimes doesn't work.
It is better to use ajax jquery method.
http://api.jquery.com/jquery.ajax/
Then on Picture/AddThumb add printing parameters.
Use done to show data resulted ( to test also if it works correctly )

Load external pages using jquery

I'm trying to use jQuery to load external pages into the current page without the user seeing the page load.
When I call the page 'info.php' it is loaded into the #content div. That's what the script is supposed to do. The problem is that in the main page, which contains the script and the #content div, I already have some code that I want it to be executed when someone visits the page and not to be called from any external page. This is working but when I click on one of the links in the menu, I can't go back to the initial content.
Here is an except of my code:
<script>
$(function() {
$('#nav a').click(function() {
var page = $(this).attr('href');
$('#content').load(page + '.php');
return false;
});
});
</script>
<ul id="nav">
<li>Page1</li>
<li>About</li>
<li>Contact</li>
<li>Info</li>
</ul>
<div id="content">
Here I have some code that I wanted to be attributed to the "Page1"
</div>
I'm not very familiar with load(), but in this case, I think you should be using ajax to load the page without refresh.
var page = $(this).attr('href');
$.ajax({
url: page + '.php',
success: function(data)
{
$('#content').html(data);
}
})
EDIT: with you said "when I click on one of the links in the menu, I can't go back to the initial content", did you mean you have some code within the div #content and onclick you've overwritten its contents?
Here is example:
$(function()
{
var content = $('#content');
$('#nav a').click(function(e) {
e.preventDefault();
var page = $(this).attr('href');
content.children().hide();
var pageContent = content.find("#" + page);
if(pageContent.length > 0)
{
pageContent.show();
}
else // put ajax here
{
content.append($('<div>').attr('id', page).text('New page ' + page));
}
});
});
Demo: jsfiddle.net/3jLjw/

jquery redirects to page element, but nothing is displayed? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to display jquery page(inside a div) using javascript?
here is my javascript code
function loginPostData(jsonRequest)
{
alert("hello");
$.post("http://localhost:8080/edserve/MobileServlet",
JSON.stringify(jsonRequest),
function(data)
{
var obj = JSON.stringify(data);
alert(obj);
if(data.status=="success")
{
<!--problem lies here-->
$.mobile.changePage( "#mainMenu");
//$('#result').load('index.html#mainMenu');
// . load also give the same result
}
else
{
if(data.message=="user not verified")
{
//display verification page
}
}
}, "json");
}
PROBLEM: the jquery loads the main menu page, but nothing is displayed, untill i refresh the page
just a quick reference of my page
<div data-role="page" id="login">
// other page content
<div id="divrightButton">
<!-- calling loginSubmit which calls loginPostData method/function-->
<a class="bluebutton" href="#" onclick="loginSubmit(); return false;">Login</a>
</div>
</form>
</div>
<!--main page-->
<div data-role="page" id="mainMenu">
Main menu
</div>
i also came to know that there is some issue in jquery with same page transition
https://github.com/jquery/jquery-mobile/issues/2529
but how to fix these issue, i dont have any clue on this node
just in case, i have also tried the following for redirection/loading
$.mobile.changePage("#mainMenu",{allowSamePageTransition: true });
$('#result').load('index.html#mainMenu');
$.mobile.changePage( $("#mainMenu"));
none is working, what i mean is it works but results are same, nothing is displayed
Try Using this Should Work
function loginPostData(jsonRequest)
{
alert("hello");
$.post("http://localhost:8080/edserve/MobileServlet",
JSON.stringify(jsonRequest),
function(data)
{
var obj = JSON.stringify(data);
alert(obj);
if(data.status=="success")
{
$('#mainmenu').children().remove(); //clears div
$('#mainmenu').html(data); //Loads data
}
else
{
if(data.message=="user not verified")
{
//display verification page
}
}
}, "json");
}
try this..
if( data.status == "success" ) {
window.location = 'index.html#mainMenu';
return;
}
After refresh your page only html can run and only display your html not your server responce after refresh your page..And if you want to show your server response on your mainMenu div so you need to use Ajax call and after getting response so you write the code to display data in html..
use this code to redirect/display the particular div element
$.mobile.changePage("#mainMenu",{allowSamePageTransition: true });
and also download following css file, its a must for transitioning between pages/div elements
jquery.mobile.transitions.css

Categories

Resources