Update a Div with a PartialView - html

I'm trying to update the Div's value with a Partial-View, but I have no idea what to write into the .html().
My Controller-Methode:
public IActionResult UpdateDiv()
{
return View("_PartialView1");
}
My Javascript function:
$.ajax({
url: "/home/UpdateDiv/"
}).done(function () {
$("#UpdateDiv").html();
})
The div:
<div id="UpdateDiv" style="width: 400px; height: 400px;"></div>
My Partial-View:
<h1>Hello</h1>

Have you tried to add a respone param to done callback function? Something like the below code snippet:
$.ajax({
url: "/home/UpdateDiv/"
}).done(function (response) {
$("#UpdateDiv").html(response);
});

$.get("/home/UpdateDiv/", function(data) {
$(".UpdateDiv").html(data);
});
Try this way. It uses GET method to receive HTML from your action. Once it's done loading, it updates your update div element.

Related

How to call my ajax function/fetch with a btn

Im learning how to use API's with ajax in jquery.
I fetched "bored api" in my html page, and I want to update it or run the function again, by pressing a button and without refreshing the page.
I know I would write the function name in my onclick method, but I can't see where the function name should be placed or is.
<p id="activity"></p>
<script>
$(function () {
$.ajax({
type: 'GET',
url: "https://www.boredapi.com/api/activity",
success: function (data) {
console.log("Success", data)
document.getElementById("activity").textContent = data.activity;
}
})
})
</script>
</form>
<button onclick="()">Click me</button>
Have a look on this example from W3 Schools:
Example
It should look something like this:
<p id="activity"></p>
<script>
function doApiRequest() {
$.ajax({
type: 'GET',
url: "https://www.boredapi.com/api/activity",
success: function (data) {
console.log("Success", data)
document.getElementById("activity").textContent = data.activity;
}
});
}
</script>
</form>
<button onclick="doApiRequest()">Click me</button>
You do not need to encapsulate the method inside jquery. and this way, we give it a name, that we can call.

How to fetch a specific div id from an html file through ajax

I have two html files called index.html & video.html
video.html holds coding like:
<div id="video">
<iframe src="http://www.youtube.com/embed/tJFUqjsBGU4?html5=1" width=500 height=500></iframe>
</div>
I want the above mentioned code to be crawled from video.html page from index.html
I can't use any back-end coding like php or .net
Is there any way to do using Ajax?
Try this...
$.ajax({
url: 'video.html',
success: function(data) {
mitem=$(data).filter('#video');
$(selector).html(mitem); //then put the video element into an html selector that is on your page.
}
});
For sure,send an ajax call.
$.ajax({
url: 'video.html',
success: function(data) {
data=$(data).find('div#video');
//do something
}
});
Yep, this is a perfect use case for ajax. When you make the $.ajax() request to your video.html page, you can then treat the response similar to the way you'd treat the existing DOM.
For example, you'd start the request by specifying the URI in the the following way:
$.ajax({
url: 'video.html'
})
You want to make sure that request succeeds. Luckily jQuery will handle this for you with the .done callback:
$.ajax({
url: "video.html",
}).done(function ( data ) {});
Now it's just a matter of using your data object in a way similar to the way you'd use any other jQuery object. I'd recommend the .find() method.
$.ajax({
url: "video.html",
}).done(function ( data ) {
$(data).find('#video'));
}
});
Since you mentioned crawl, I assume there is the possibility of multiple pages. The following loads pages from an array of urls, and stores the successful loads into results. It decrements remainingUrls (which could be useful for updating a progressbar) on each load (complete is called after success or error), and can call a method after all pages have been processed (!remainingUrls).
If this is overkill, just use the $.ajax part and replace myUrls[i] with video.html. I sepecify the type only because I ran into a case where another script changed the default type of ajax to POST. If you're loading dynamic pages like php or aspx, then the cache property might also be helpful if you're going to call this multiple times per session.
var myUrls = ['video1.html', 'video2.html', 'fail.html'],
results = [],
remainingUrls;
$(document).ready(function () {
remainingUrls = myUrls.length;
for (var i = 0, il = myUrls.length; i < il; i++) {
$.ajax({
url: myUrls[i],
type: 'get', // somebody might override ajax defaults
cache: 'false', // only if you're getting dynamic pages
success: function (data) {
console.log('success');
results.push(data);
},
error: function () {
console.log('fail');
},
complete: function() {
remainingUrls--;
if (!remainingUrls) {
// handle completed crawl
console.log('done');
}
}
});
}
});
not tested, but should be something similair to this: https://stackoverflow.com/a/3535356/1059828
var xhr= new XMLHttpRequest();
xhr.open('GET', 'index.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementsByTagName('html').innerHTML= this.responseText;
};
xhr.send();

jquery function runs only once

I have this function below. Works great and is from http://caroufredsel.dev7studios.com/ (by far the best and easiet I have found if anyone else is after a carousel)
<script type="text/javascript" language="javascript">
$(function() {
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
});
</script>
anyway I the carousel loops through a selection of images. Now I have a separate function that reloads the div through an ajax call below. It populates the div with a new set of images based on the users selection of folder.
<script>
function getImages(id)
{
$.ajax({
type: "GET",
url: 'getImage.php',
data: "id=" + id,
success: function(data) {
$('#scrolimg').html(data);
}
});
}
</script>
This too works fine. The problem is when you have clicked a new folder and it reloads refreshes the div the carousel stops completely. Is there anyway based on the success of the ajax call to re fire the jquery function to get the carousel going again?
on the callback function of the AJAX you call, you have to re-apply:
success: function(data) {
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
...
}
If you are using a .html() function or similar to re-write the foo element, you are erasing any event associated to it too, so you have to call it again.
Add something like this into your callback:
$('#foo1').carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
It should work. Respect!
Supposing in your example foo1 == scrolimg, do this:
<script>
function getImages(id)
{
$.ajax({
type: "GET",
url: 'getImage.php',
data: "id=" + id,
success: function(data) {
$('#scrolimg')
.carouFredSel('destroy')
.html(data)
.carouFredSel({
auto: {
pauseOnHover: 'resume',
progress: '#timer1'
}
});
}
});
}
</script>

ASP.NET MVC Show View after Ajax call to a Controller

I have a View with a submit form: when I click it a jquery/ajax function is called. This function has to encode the View Model, call a Controller action and show the View returned.
Now, this is my function:
<script type="text/javascript">
function Analyze() {
var urlact = '#Url.Action("Analysis")';
var model = '#Html.Raw(Json.Encode(Model))';
$.ajax({
data: model,
type: "POST",
url: urlact,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//WHAT HERE??
}
});
}
</script>
And the Analysis action is a kind of
public ViewResult Analysis(IEnumerable<Azienda> aziende) {
Debug.WriteLine(aziende.Count());
return View(aziende);
}
Returning a View!
How can I display that View on success:function(data)?
I tried changing dataType to html and calling on success alert(data) but I had problems with the encoded model, I tried commenting the contentType line but same model-encoding issue.
Does someone know how to do that?
A js/query/ajax workaround-trick is fine, too.
Thanks you all!
Use
return PartialView()
instead of
return View()
in your controller. Then in the success function in your ajax call, use the jQuery .html() function to update the element you wish to update in your html. See Query.html() and View() vs. PartialView()
Create a separate partial view with aziende as its model and return this in your Analysis action and then append the result to a div in your view:
//action returning a partial view
public ActionResult Analysis(IEnumerable<Azienda> aziende)
{
Debug.WriteLine(aziende.Count());
return PartialView("_partialView", aziende);
}
//then append the result to a div in your javascript
success: function (data) {
$("#some-div").html(data);
}

Ajax function not called when included

I have an ajax function that is not run when the ajax script is included in my HTML page like so:
<script type='text/javascript' src='ajax.js'></script>
However, if I place the exact same script in the head portion of the HTML page, then it does run.
Why does this occur, and how can I fix it?
<script type="text/javascript">
$(function() {
$(".a").click(function()
{
$.ajax({
type: "POST",
url: "1.php",
data: dataString,
cache: false,
success: function(html)
{
//stuff
}
});
return false;
});
});
</script>
This might seem trivial but did you remove the <script> tags when using it in an external .js file?
The contents of your ajax.js file should just be:
$(function() {
$(".a").click(function() {
$.ajax({
type: "POST",
url: "1.php",
data: dataString,
cache: false,
success: function(html)
{
//stuff
}
});
return false;
});
});
I have the impression that when you mentioned "exactly", you left the script tags intact in the ajax.js file.
Also if this still doesn't work. try added an alert("hello"); line at the top of ajax.js before everything to see whether it runs at all.
I made a example which worked fine for me. cant see any problems so im guessing its a mistype or something silly.
here is the sample code i used:
HTML:
//double check these paths
<body>
<a class="a" href="#">clicky</a>
</body>
Javascript:
$(function() {
// i noticed you put .a here instead of a, i am assuming you are referring the class
$(".a").click(function()
{
alert("1");
$.ajax({
type: "POST",
url: "1.php",
data: "html",
cache: false,
success: function(data)
{
//stuff
$("body").html(data);
}
});
return false;
});
});
PHP:
echo 'bar';