Div content load using Ajax and MVC 4 - javascript

I have several buttons which should change content of region on the page. I've read numerous tutorials how can lazy load can be implemented using ajax, but unfortunately with no success. Here is my html:
<div>
<div>
<button id="btn_goals">Goals</button>
<button id="btn_achievements">Achievements</button>
</div>
<div id="region_content"></div>
</div>
and here is my js:
$(document).ready(function () {
$('#btn_goals').on('click', function () {
$.ajax({
url: '#Url.Action("Index", "Goals")',
success: function (data) {
$('#region_content').html(data);
}
});
});
$("#btn_achievements").on("click", function () {
......
});
});
what is the problem?
********** EDIT ************
Well, I changed url in ajax parameters from url: '#Url.Action("Index", "Goals")' to url: '/Goals/Index' and it starts work fine. What is the reason?

Try following the following steps:
Use console.log("Inside Success function"+ data); to test whether the required data is being returned from the controller method.
Use Ctrl+Shift+I in your browser to view the console. If Successful:
Use:
var div = document.getElementById("region_content");
div.innerHTML = div.innerHTML + data;
Make sure your type conversions are done right.
Also specify type: POST in your ajax function.
If you do not see 'Inside Success function' on your console, there might be something wrong with your controller function.

Related

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

jQuery ajax doesn't work with generated markup

We have a search functionality in our application, when user types in something, the result will be generated based on the filter and displayed on page.
Here's the dynamic result after each keyup:
htmlResult = `
<li>
<div>
<img src='${user.avatar}' width='80' alt='${user.fullName}' />
</div>
<a tabindex='0'
class ='btn2'
data-html='true'
data-toggle='popover'
data-content="<div class='list-group'>add
</li>
`;
Here are the event handlers:
$("[data-toggle=popover]").popover();
$(document).on('click', '.btn2', function(event) {
event.preventDefault();
$(this).popover({ html: true });
});
$(document).on('click', '.item', function (event) {
event.preventDefault();
const value1 = $(this).attr('data-val1-value');
const params = {
value1: value1
};
$.ajax({
type: "POST",
url: endPoint,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(params),
success: (result) => {
// refresh
}
});
});
There are two problems with this code:
popover will be displayed after 3 times clicking on .item
jQuery ajax won't succeed, it shows 400 Bad Request error on console.
PS: this code works fine with not-generated markup.
any idea?
For popover you must reinitiate every your dynamic content was append to HTML.
For Ajax 400 this is because the URL not found the route path, please check again your backend requirement for this request.
a) to make sure your url is correct,
1) update your serverside funtion not to accept any parameter just for testing
2) call ajax with data: NULL
3) debug and see if it reaches to server side function.
b) if not reached to server side, check if it is a POST or GET in server side function.
c) if you are sure that server side function is correctly called, data without stringfy.
that might help.

Run JS after div contents loaded from AJAX

There are a ton of proposed answers to my question, but even with all the answers I have found, I can not seem to get any to work. I can make the JS work by adding a delay in execution of the code, but I can't rely on a delay to execute the JS after div has finished loading it's HTML.
I'm creating a page where users can search for an item, and the results are displayed in a div using AJAX. I need some JS to run after the div's html has finished loading. Some of the results data will be hidden until a user clicks on it. The JS code to accomplish this is what I am trying to run once the div finishes loading.
I have tried the following extensively with no luck anywhere:
.load
.ajaxComplete
.complete
.success
.done
Document.ready
I'm sure there are a few others as well, but my brain is just too beat up from dealing with this to remember everything I've tried so far.
My HTML:
<form name ="CardName" method="post" action="">
<div "class="w2ui-field">
<div> <input type="list" Name="CardName" id="CardName" style="width: 80%;"></div>
</div>
<div class="w2ui-buttons">
<input type="submit" name="search" style="clear: both; width:80%" value="Search" class="btn">
</div>
</form>
<div class="Results" id="Results" name="Results"></div>
My JS:
$(function() {
$("#CardSearch").bind('submit',function() {
var value = $('#CardName').val();
$.ajax({
method: "POST",
url: "synergies.php",
data: {value}
})
.success(function(data) {
$("#Results").html(data);
})
.complete(function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
});
return false;
});
});
If there is anything else that could help with this request just let me know!
Thanks in advance!
Note that success and failure are options that you should provide to the $.ajax call, not the returned promise. Also, bind is deprecated in favour of on since jQuery 1.7. Finally, you need to give the value that you're posting to your PHP page a key so that it can be retrieved via $_POST. Try this:
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
},
success: function(data) {
$("#Results").html(data);
},
complete: function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
}
})
});
You can then retrieve the value sent in your synergies.php file using $_POST['CardName'].
If you prefer to use the method provided by the returned promise, you can do that like the below, although the result is identical.
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
}
}).done(function(data) {
$("#Results").html(data);
}).always(function() {
alert("div updated!");
})
});
you can try Synchronous Ajax request, demo code is given below:
$(function() {
$("#CardSearch").bind('submit',function() {
e.preventDefault();
sendData = $('#CardName').val();
reqUrl = "synergies.php";
// this will wait until server request complete
var ajaxOpt = AjaxSyncRequest(reqUrl, sendData);
// after complete server request
ajaxOpt.done(function(data) {
$("#Results").html(data);
});
});
});
function AjaxSyncRequest(reqUrl, sendData) {
var ajaxData = $.ajax({
method: "POST",
url: reqUrl,
data: {
data: sendData
}
});
return ajaxData;
}

Issue populating ajax response into a div

What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

Reload jquery plugin after ajax call

I've this code
jQuery('#select_set').on("change", function() {
var data_id = {
action: 'yasr_send_id_nameset',
set_id: jQuery(this).val()
}
//Send value to the Server
jQuery.post(ajaxurl, data_id, function(response) {
jQuery('#yasr_rateit_multi_rating').html(response);
});
});
The response that i got from ajax is something like this
Qualità birra <div class="rateit" id="yasr_rateit_multi_0" data-rateit-value="" data-rateit-step="0.5" data-rateit-resetable="true" data-rateit-readonly="false">
</div> <br />
I can output just the simple text but i can't output the div: that div call a jquery plugin called "rateit". I think that i should reload the plugin after ajax response but I've not idea how to do this. I'm a total noob in js
jQuery's post() method takes the success function as a parameter, as you've done. Just include your plugin init statement there:
jQuery.post(ajaxurl, data_id, function(response) {
jQuery('#yasr_rateit_multi_rating').html(response);
jQuery('#myElement').rateIt();
});
https://api.jquery.com/jQuery.post

Categories

Resources