How to replace content with javascript from Ajax response - javascript

I wan't to replace a section from div in my index view with new data that I get from partial View. I get a correct responce, which I see in firebug. For now I only display on success an alert window, that says it's working. Bellow is my Ajax code and a part of response which i get(20 list-group items inside an ul). So do I have to write for every div javascript code just like in my view or is there another option? Maybe some examples please?
Regards!
<script>
function testAjax() {
debugger;
$.ajax({
url: "#Url.Content("~/Controller/MyAction")",
data: "searchString=search",
type: "Post",
beforeSend: function () {
//Code for before send whatever you have to do.
},
success: function (data) {
alert("It's Working!");
},
error: function (response) {
//Your code when error ocure
alert(response.responseText);
},
failure: function (response) {
//your code for failure
alert(response.responseText);
}
})
}
</script>
my response:
<ul class="list-group infinite-scroll">
<li class="list-group-item col-md-6">
<div class="noo-event-featured-item grow">
<div class="sc-event-content">
<h3>text</h3>
<div class="bottom">
<div class="create-date">
<span>
date
</span>
</div>
</div>
</div>
<div class="sc-event-item">
<div class="event-thumbnail">
<a href="link" >
<img src="image link">
</a>
<div class="sc-meta">
<span class="sc-date"><i class="fa fa-clock-o"></i><span> text</span></span>
<span class="sc-address">
<i class="fa fa-map-marker" style="padding-left: 3px;"></i>Place<span class="tribe-address">
<span class="tribe-street-address">Street</span><span class="tribe-delimiter"
>, </span>
<span class="tribe-locality">Country</span>
</span>
</span>
</div>
</div>
</div>
</div>
</li>
</ul>

Thank you all, I have figured it out. You have to use a dot before divid $(".divid").replaceWith(data);

If your response its a html code(in plain text) you can try use something like this in your success function:
$('yourDiv').html(data);//replace child nodes

Related

Why does my view function render data but it won't show up in the browser? (AJAX/Django)

I have finally achieved that my Javascript on 'click' function and AJAX work handy in collaboration with my view function that calls data from an API. But now I have one more issue:
The data from the API is forwarded smoothly to the html containers that contain the according variables. But in my browser I don't see the content being displayed?!
Why is that?
I don't have a success function set up in AJAX so far, since I understood that the view function renders the frontend so there is no need for AJAX success function in that case?
In advance thank you so much for your inputs.
View
import requests
from django.shortcuts import render
import json
def team_update(request):
team_id = request.GET.get('team')
response = requests.get(f'http://www.api-football.com/demo/api/v2/teams/team/{team_id}')
team_data = response.json()
teams = team_data.get('api', {}).get('teams', [])
if teams and len(teams) == 1:
teams = teams[0]
return render(request, 'index.html', {
'name': teams['name'],
'country': teams['country'],
'founded': teams['founded'],
'logo': teams['logo'],
'venue_capacity': teams['venue_capacity'],
})
Javascript/Ajax:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
url: "/dashboard/",
data: {'team': team_id},
success: function(response) {
console.log(response)
}
});
});
HTML (the key part):
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="{% static "images/club_flags/Clubs/Germany/FC Bayern München.png" %}" alt="Manchester United">
</div>
<div class="selectedClub">{{ name }}</div>
</div>
</div>
<!---End of Top Row and Start of Second row--->
<div class="secondRow">
<div class="column">
<p class="heading">Founded in</p>
<p class="figure" id="founded">{{ founded }}</p>
</div>
Debug:
You need to utilise the response data from within your success function, rather than simply logging it. I'll make some assumptions about your page, say for example you currently have the following
<body>
<!-- all your other stuff on the page -->
<div id="container-element">
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="" alt="">
</div>
<div class="selectedClub"></div>
</div>
</div>
<!---End of Top Row and Start of Second row--->
<div class="secondRow">
<div class="column">
<p class="heading">Founded in</p>
<p class="figure" id="founded"></p>
</div>
</div>
</body>
If that was how your page is currently set up, then in your success function of your AJAX call, you could do this:
$.ajax({
method: "GET",
url: "/dashboard/",
data: {'team': team_id },
success: function(response) {
$('container-element').html(response);
}
});
Which will replace the content inside your actual page.

onClick for link element doesnt work when trying to invoke a js function (Uncaught TypeError: Cannot set property 'onclick' of null)

Here I'm trying to send a http request to my spring controller once an icon is clicked that is displayed with a validation for a model attribute.
<div class="col-sm-4 col-sm-offset-1 page-title-section"></div>
<c:if test="${viewUsers}">
<div class="col-sm-4 page-actions-section">
<div class="page-actions">
<div class="page-action">
<a id="loadUserIcon">
<i class="fa fa-plus fa-2x"></i>
<h5>Add User</h5>
</a>
</div>
</div>
</div>
</c:if>
<c:if test="${viewRoles}">
<div class="col-sm-4 page-actions-section">
<div class="page-actions">
<div class="page-action">
<a id="loadRoleIcon">
<i class="fa fa-plus fa-2x"></i>
<h5>Add Role</h5>
</a>
</div>
</div>
</div>
</c:if>
</div>
The js to send the request once the icon is clicked :
(function() {
document.getElementById("loadUserIcon").onclick = function() {
window.location = 'loadUser?id=' + 0;
};
})();
(function() {
document.getElementById("loadRoleIcon").onclick = function() {
window.location = 'loadRole?id=' + 0;
};
})();
So now the separate icons are displayed with each model attribute validation and the first function is invoked once the 'Add User' icon is clicked but i cant seem to invoke this second function even though the icon is displayed with the model attribute validation. What could have been gone wrong here?
The error on the console once the 'Add Role' icon is clicked :
Uncaught TypeError: Cannot set property 'onclick' of null
at load:496
at load:500
these line numbers are directed to the second js function
Any error on console ?
Where you put the scripts?
You should put them into body.onload handler or just before the end tag </body>.
Include your JavaScript code, either at below the </body> tag, or load the functions upon DOM ready or onload.
I changed the code a bit for JSFiddle and its working fine, check here: https://jsfiddle.net/045L2xvj/
<div class="col-sm-4 col-sm-offset-1 page-title-section"></div>
<div class="col-sm-4 page-actions-section">
<div class="page-actions">
<div class="page-action">
<a href="#" id="loadUserIcon">
<h5>Add User</h5>
</a>
</div>
</div>
</div>
<div class="col-sm-4 page-actions-section">
<div class="page-actions">
<div class="page-action">
<a href="#" id="loadRoleIcon">
<h5>Add Role</h5>
</a>
</div>
</div>
</div>
And JS code:
(function() {
document.getElementById("loadUserIcon").onclick = function() {
alert('Add user');
};
})();
(function() {
document.getElementById("loadRoleIcon").onclick = function() {
alert('Add role');
};
})();
I just needed to wrap the js functions too with the model attribute validation to eliminate elements getting null.
<c:if test="${viewUsers}">
<script>
document.getElementById('loadUserIcon').onclick = function () {
window.location = 'loadUser?id=' + 0;
};
</script>
</c:if>
<c:if test="${viewRoles}">
<script>
document.getElementById('loadRoleIcon').onclick = function () {
window.location = 'loadRole?id=' + 0;
};
</script>
</c:if>

How can I avoid an undesired URL address change after a form submission?

I am working on a bootsrap3 template, which is Ajax based.
My index file has a leftside menu and a conent block middle of the page, every time I click on a subelement of this left menu, an Ajax laod will put the page content in this block(ajax-content).*
Any time I call any page, my URL normally looks something like this /index.php#page-one.php, except when the page contains form submission.
The Problem happens when I add an action attribute (acion="page-one.php") to my form tag.
After the form submission my URL turns to /page-one.php ;
consequently I get a white page containing the page-one.php elements whitout any CSS styling and of course no index-file's elements.
What is the correct and best way to come a cross this issue?
index.php:
<body>
<!--Start Container-->
<div id="main" class="container-fluid">
<div class="row">
<div id="sidebar-left" class="col-xs-2 col-sm-2">
<ul class="nav main-menu">
<li class="dropdown">
<a id="configuration" href="#" class="dropdown-toggle">
<i class="fa fa-gears"></i>
<span class="hidden-xs">Menu-element</span>
</a>
<ul class="dropdown-menu">
<li><a class="ajax-link" href="page-one.php">Menu-Subelement-one</a></li>
<li><a class="ajax-link" href="page-wo.php">Menu-Subelement-two</a></li>
</ul>
</li>
</ul> <!-- end of main-menu-->
</div>
<!--Start Content-->
<div id="content" class="col-xs-12 col-sm-10">
<div class="preloader">
<img src="img.gif" class="loader" alt="preloader"/>
</div>
<!--inside this div a short description/introduction(simple text inside a <p> tag) about the Menu-element will be shown-->
<div id="content-header"></div>
<!--inside this div the page content of the Menu-subelement will be shown-->
<div id="ajax-content"></div>
</div>
<!--End Content-->
</div>
</div>
<!--End Container-->
<script src="plugins/jquery/jquery-2.1.0.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="plugin/jquery.form.js"></script>
<script src="js/script.js"></script>
And here is my script.js:
//
// Function for load content from url and put in $('.ajax-content') block
//
function LoadAjaxContent(url){
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: url,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
//////////////////////////////////////////////////////
document.ready
//////////////////////////////////////////////////////
$(document).ready(function () {
var ajax_url = location.hash.replace(/^#/, '');
if (ajax_url.length < 1) {
ajax_url = 'home.php';
}
LoadAjaxContent(ajax_url);
$('.main-menu').on('click', 'a', function (e) {
var parents = $(this).parents('li');
var li = $(this).closest('li.dropdown');
var another_items = $('.main-menu li').not(parents);
another_items.find('a').removeClass('active');
another_items.find('a').removeClass('active-parent');
if ($(this).hasClass('dropdown-toggle') || $(this).closest('li').find('ul').length == 0) {
$(this).addClass('active-parent');
var current = $(this).next();
if (current.is(':visible')) {
li.find("ul.dropdown-menu").slideUp('fast');
li.find("ul.dropdown-menu a").removeClass('active')
}
else {
another_items.find("ul.dropdown-menu").slideUp('fast');
current.slideDown('fast');
}
}
else {
if (li.find('a.dropdown-toggle').hasClass('active-parent')) {
var pre = $(this).closest('ul.dropdown-menu');
pre.find("li.dropdown").not($(this).closest('li')).find('ul.dropdown-menu').slideUp('fast');
}
}
if ($(this).hasClass('active') == false) {
$(this).parents("ul.dropdown-menu").find('a').removeClass('active');
$(this).addClass('active')
}
if ($(this).hasClass('ajax-link')) {
e.preventDefault();
if ($(this).hasClass('add-full')) {
$('#content').addClass('full-content');
}
else {
$('#content').removeClass('full-content');
}
var url = $(this).attr('href');
window.location.hash = url;
LoadAjaxContent(url);
}
if ($(this).attr('href') == '#') {
e.preventDefault();
}
});
$('#formSubmit').ajaxForm();
});
page-one.php:
<!--some php code here-->
<form class="validateForm" id="formSubmit" action="page-one.php" method="get">
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" />
</div>
<div class="form-group">
<div class="col-sm-offset-5 col-sm-8">
<button type="submit" class="btn btn-primary btn-label-left">
<span><i class="fa fa-save"></i> Save</span>
</button>
</div>
</div>
</form>
Thanks!
I had the same issue to solve for the intranet I work on.
For me, the good way to do this is to avoid using submit method and use instead an input button with a js function to send the form data.
In my case, I did this:
<!-- At the top of my webpage -->
<script language='Javascript'>
function loadingAjax(div_id,user,date1,date2)
{
$("#"+div_id).html('<br><center><img src="images/loading.gif"><br><br><font color="#006699" face="arial" size="4"><b>Loading data<br>VPlease wait ...</b></font></center>');
$.ajax({
type: "POST",
url: "activities.php?USER="+user+"&DATE1="+date1+"&DATE2="+date2,
success: function(msg){
$("#"+div_id).html(msg);
}
});
}
</script>
<!-- And here is my form -->
<form id='date_form'>
<input type='text' id='user'><input type='text' id='date1'><input type='text' id='date2'>
<input type='button' onclick="loadingAjax('myDiv',document.getElementById('user').value,document.getElementById('date1').value,document.getElementById('date2').value);">
</form>
This allow to send your form in a separate DIV without having to show to everyone your URL.
MORE: you can even use this function to manage your left side menu selection so that your URL would stay '/index.php' all the time.
Hope this help
Regards
Nico
How do you want to submit the form, using ajax?
If you want to use ajax, you should cancel the default action like you do with your links using e.preventDefault();. Post the javascript that handles the form submit if you need help with that.
If you want to post to page-one.php without using ajax, you could add a header() redirect after the php code that processes the form to redirect to the page that you would like to show after the form gets submitted.
As you are loading content by ajax,
You can post content to page-one.php and redirect user to it's previous page. But it will be difficult manage and show error, success, notification message like form validation errors etc.
Another and I think best solution is to use ajax form submission

How to remove and display this elements when ajax success?

How to remove and display this elements when ajax success ?
i want to remove this elements when success
<a class="hyper" id="1234567890">
<div class="mine">
<img src="moo.png"/>
</div>
</a>
and display this elements when success
<a class="success" id="1234567890">
<div class="sura">
<img src="naa.png"/>
</div>
</a>
and this is my ajax post code
$('body').on('click','.hyper',function() {
var my_id = $(this).attr('id');
var postData = 'mydata='+my_id+'&time=now';
$.ajax({
type: "POST",
url: "my_post.php",
data: postData,
cache: false,
success: function()
{
}
});
})
When i use follow Zentoaku
$('#1234567890').removeClass('hyper').addClass('success').html('<div class="sura"><img src="naa.png"/></div>');
after success my element display
<a class="hyper" id="1234567890">
<div class="mine">
<img src="moo.png"/>
</div>
<a class="success" id="1234567890">
<div class="sura">
<img src="naa.png"/>
</div>
</a>
</a>
but after success i want to see this
<a class="success" id="1234567890">
<div class="sura">
<img src="naa.png"/>
</div>
</a>
how can i do ?
To Hide you can use following:
success: function()
{
$('.hyper').hide();
}
You can also use remove() method to completely remove the elements from DOM.
To show use this:
success: function()
{
$('.success').show();
}
You can use Id as well as your selector, if you use different ids for both the elements.
NOTE: This solution will be applicable when you have your html code already exists on your page which you have shown in your question.
jQuery has a toggle function, with which you can toggle the visibility of an item.
http://api.jquery.com/toggle/
Your code then could look like this:
$('body').on('click','.hyper',function() {
var my_id = $(this).attr('id');
var postData = 'mydata='+my_id+'&time=now';
$.ajax({
type: "POST",
url: "my_post.php",
data: postData,
cache: false,
success: function(my_id)
{
$('#'+my_id+'.hyper').toggle();
$('#'+my_id+'.success').toggle();
}
});
})
$('#1234567890').removeClass('hyper').addClass('success');
$('#1234567890 > div').removeClass('mine').addClass('sura');
$('#1234567890 > div > img').attr('src', 'naa.png')
OR
$('#1234567890').removeClass('hyper').addClass('success').html('<div class="sura"><img src="naa.png"/></div>');

How to call a ASP function from onclick in the HTML?

I have 3 link in my HTML. When I click one of these a variable in the session must change.
How can I do that?
<div id="eng">
<a href="#" onClick="setLanguage('en')";>
<img id="eng_img" src="bandiera01.png" />
</a>
</div>
<div id="rus">
<a href="#" onclick="setLanguage('ru');">
<img id="rus_img" src="bandiera02.png" />
</a>
</div>
<div id="ted">
<a href="#" onclick="setLanguage('de');">
<img id="ted_img" src="bandiera03.png" />
</a>
</div>
setLanguage(txt) is a JavaScript function but I want to use it in ASP to save it in session.
You need send the information to server, you can post by a normal link or send by ajax. I think with in this case, is better you send by normal link, for example:
<div id="eng">
<a href="ChangeLanguage.asp?language=en">
<img id="eng_img" src="bandiera01.png" /></a>
</a>
</div>
<div id="rus">
<a href="ChangeLanguage.asp?language=ru">
<img id="rus_img" src="bandiera02.png" />
</a>
</div>
<div id="ted">
<a href="ChangeLanguage.asp?language=de">
<img id="ted_img" src="bandiera03.png" />
</a>
</div>
In the page of destination, you get the "language" information of the link.
You can address this issue in a couple of way:
Turn your links into submit buttons, put them inside a form, submit the page server side to manage the language change business logic. This is a classic asp approach. You have to rebuild the page server side.
Let the setLanguage() fire an ajax call to an asp page that retrieves the localized resources. On success, the resources are mapped into the corresponding elements of the DOM: maybe set this logic into a different function:
HTML
<div class="lang">
en
</div>
<div class="lang">
ru
</div>
<div class="lang">
de
</div>
SCRIPT
(function($){
window.setLanguage = function(langCode){
$.ajax({
type: "GET",
url: "myLanguageHandler.asp",
data: { "languageCode": languageCode },
async: true,
error: function (req, status, message) {
//manage the error
},
success: function (data) {
mapPage(data);
}
});
/*
* for demo purpose only
* console.log('Set language: ' + langCode);
*/
};
$('.lang a').bind('click', function(e){
window.setLanguage($(e.target).attr('data-lang'));
return false;
});
})(jQuery)

Categories