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

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)

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.

How to replace content with javascript from Ajax response

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

Open a page without loading using jquery

I have this webpage i made,just to get started with web, based on this template.
http://ironsummitmedia.github.io/startbootstrap-freelancer/#
where on clicking the thumbnails in portfolio, another webpage opens with more details on the picture. The code i have written is making the page load. I want to implement it exactly as in this template.
html (for thumbnails) :
<div class = "pictures ">
<div class = "container ">
<div >
<center><b><text>PORTFOLIO</text></b></center>
</div>
<div class = "pics">
<div class = "column">
<div class = "col-md-4">
<div class = "thumbnail">
<img data-src = "glass.png" src = "cabin.png" id="cabin" alt="" />
</div>
<div class = "thumbnail">
<img data-src="glass.png" src = "cake.png" id="cake" alt="" />
</div>
</div>
</div>
<div class = "column">
<div class = "col-md-4">
<div class = "thumbnail">
<img data-src = "glass.png" src = "circus.png" id="circus" alt="" />
</div>
<div class = "thumbnail">
<img data-src="glass.png" src = "game.png" id="game" alt="" />
</div>
</div>
</div>
<div class = "column">
<div class = "col-md-4">
<div class = "thumbnail">
<img data-src="glass.png" src = "safe.png" id="safe" alt="" />
</div>
<div class = "thumbnail">
<img data-src="glass.png" src = "submarine.png" id="submarine" alt="" />
</div>
</div>
</div>
</div>
</div>
</div>
Jquery for opening new page :
$(".pictures .thumbnail img").click ( function () {
window.location.href = this.id +".html";
});
What changes should i make to my code which allows me to open pages without loading/refreshing?
thanks in advance!
You should learn some AJAX to achieve this. Read the jQuery Docs on AJAX for more info.
Ajax is a client-side script that communicates to and from a server/database without the need for a postback or a complete page refresh. The best definition I've read for Ajax is “the method of exchanging data with a server, and updating parts of a web page - without reloading the entire page.” Source: Seguetech
Here is some example AJAX and jQuery:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
$("#loadingimg").hide();
}
});
});
});
DEMO
Be dauntless. It looks sort of confusing, especially just starting with jQuery, but trust me it isn't. You'll be glad you learned it.
The template you are referring to uses bootstrap modals. Also to get data on the fly to fill the modal you need to know Ajax. Boy Wonder already gave a definition. But you can also populate the modal without getting data from the server site, it can be static after all. You can learn about bootstrap modals from here http://getbootstrap.com/javascript/#modals

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

Refresh/reload the content in Div using jquery/ajax

I want to reload a div on click of a button. I do not want to reload the full page.
Here is my code:
HTML:
<div role="button" class="marginTop50 marginBottom">
<input type="button" id="getCameraSerialNumbers" value="Capture Again" class="disabled" />
<input type="button" id="confirmNext" value="Confirm & Proceed" class="disabled marginLeft50" />
</div>
On click of <input type="button" id="getCameraSerialNumbers" value="Capture Again"> Button a <div id="list">....</div> should reload without loading or refreshing full page.
Below is the Jquery which I tried, but not working:-
$("#getCameraSerialNumbers").click(function () {
$("#step1Content").load();
});
Please suggest.
Here is the DIV on my page, which contains Pictures and Serial numbers of some products... Which will be coming from database 1st time on the Page Load. But Is User faces some issue he'll click tthe "Capture Again" button "<input type="button" id="getCameraSerialNumbers" value="Capture Again">" which will load those information again.
The HTML Code of Div:-
<div id="step1Content" role="Step1ShowCameraCaptures" class="marginLeft">
<form>
<h1>Camera Configuration</h1>
<!-- Step 1.1 - Image Captures Confirmation-->
<div id="list">
<div>
<p>
<a id="pickheadImageLightBox" data-lightbox="image-1" title="" href="">
<img alt="" id="pickheadImage" src="" width="250" height="200" />
</a>
</p>
<p>
<strong>Pickhead Camera Serial No:</strong><br />
<span id="pickheadImageDetails"></span>
</p>
</div>
<div>
<p>
<a id="processingStationSideImageLightBox" data-lightbox="image-1" title="" href="">
<img alt="" id="processingStationSideImage" src="" width="250" height="200" />
</a>
</p>
<p>
<strong>Processing Station Top Camera Serial No:</strong><br />
<span id="processingStationSideImageDetails"></span>
</p>
</div>
<div>
<p>
<a id="processingStationTopImageLightBox" data-lightbox="image-1" title="" href="">
<img alt="" id="processingStationTopImage" src="" width="250" height="200" />
</a>
</p>
<p>
<strong>Processing Station Side Camera Serial No:</strong><br />
<span id="processingStationTopImageDetails"></span>
</p>
</div>
<div>
<p>
<a id="cardScanImageLightBox" data-lightbox="image-1" title="" href="">
<img alt="" id="cardScanImage" src="" width="250" height="200" />
</a>
</p>
<p>
<strong>Card Scan Camera Serial No:</strong><br />
<span id="cardScanImageDetails"></span>
</p>
</div>
</div>
<div class="clearall"></div>
<div class="marginTop50">
<p><input type="radio" name="radio1" id="optionYes" />Yes, the infomation captured is correct.</p>
<p><input type="radio" name="radio1" id="optionNo" />No, Please capture again.</p>
</div>
<div role="button" class="marginTop50 marginBottom">
<input type="button" id="getCameraSerialNumbers" value="Capture Again" class="disabled" />
<input type="button" id="confirmNext" value="Confirm & Proceed" class="disabled marginLeft50" />
</div>
</form>
Now on click of <input type="button" id="getCameraSerialNumbers" value="Capture Again" class="disabled" /> button, the information which is in <div id="list">... </div> should be loaded again.
Please let me know if you need some more information.
$("#mydiv").load(location.href + " #mydiv");
Always take note of the space just before the second # sign, otherwise the above code will return the whole page nested inside you intended DIV. Always put space.
$("#myDiv").load(location.href+" #myDiv>*","");
I always use this, works perfect.
$(document).ready(function(){
$(function(){
$('#ideal_form').submit(function(e){
e.preventDefault();
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$('#loader3', form).html('<img src="../../images/ajax-loader.gif" /> Please wait...');
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(msg) {
$(form).fadeOut(800, function(){
form.html(msg).fadeIn().delay(2000);
});
}
});
});
});
});
When this method executes, it retrieves the content of location.href, but then jQuery parses the returned document to find the element with divId. This element, along with its contents, is inserted into the element with an ID (divId) of result, and the rest of the retrieved document is discarded.
$("#divId").load(location.href + " #divId>*", "");
hope this may help someone to understand
While you haven't provided enough information to actually indicate WHERE you should be pulling data from, you do need to pull it from somewhere. You can specify the URL in load, as well as define data parameters or a callback function.
$("#getCameraSerialNumbers").click(function () {
$("#step1Content").load('YourUrl');
});
http://api.jquery.com/load/
What you want is to load the data again but not reload the div.
You need to make an Ajax query to get data from the server and fill the DIV.
http://api.jquery.com/jQuery.ajax/
Try this
html code
<div id="refresh">
<input type="text" />
<input type="button" id="click" />
</div>
jQuery code
<script>
$('#click').click(function(){
var div=$('#refresh').html();
$.ajax({
url: '/path/to/file.php',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
})
.done(function(data) {
if(data.success=='ok'){
$('#refresh').html(div);
}else{
// show errors.
}
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
</script>
php page code path=/path/to/file.php
<?php
header('Content-Type: application/json');
$done=true;
if($done){
echo json_encode(['success'=>'ok']);
}
?>
You need to add the source from where you're loading the data.
For Example:
$("#step1Content").load("yourpage.html");
Hope It will help you.
I know the topic is old, but you can declare the Ajax as a variable, then use a function to call the variable on the desired content. Keep in mind you are calling what you have in the Ajax if you want a different elements from the Ajax you need to specify it.
Example:
Var infogen = $.ajax({'your query')};
$("#refresh").click(function(){
infogen;
console.log("to verify");
});
Hope helps
if not try:
$("#refresh").click(function(){
loca.tion.reload();
console.log("to verify");
});
$("#categoryTable").load(window.location + " #categoryTable");
Here i mentioned Table Id where i loading data and after delete. i am calling this code and it will refresh data without whole Page load.
What I did was something like this:
$('#x').html($('#x').html())
$(document).ready(function() {
var pageRefresh = 5000; //5 s
setInterval(function() {
refresh();
}, pageRefresh);
});
// Functions
function refresh() {
$('#div1').load(location.href + " #div1");
$('#div2').load(location.href + " #div2");
}

Categories