Ajax change wrapper content - javascript

I'm trying to develop my skills with Ajax
I want to change my wrapper content with a different pages wrapper content without having to refresh the page.
I'm using:
$(function () {
$("#page2btn").click(function () {
$.ajax({
url: 'page2.asp',
data: { id: $(this).attr('id') },
success: function (data) {
$('#Wrapper').html(data);
}
});
});
});
<div id="Wrapper">
<div id="menu">
<a class="navbutton" onclick="MakeRequest1()">Home</a> <span class="navbutton">|</span>
<a class="navbutton" id="Page2btn">Page2</a> <span class="navbutton">|</span>
<a class="navbutton" onclick="MakeRequest3()">Page3</a>
</div>
<h1>Test1</h1>
</div>
and another page called page2.asp
with a different wrapper content saying Test2
But my wrapper wont change when I click the button.
any help would be appreciated.

Try to simplify it to determine if this is a problem with your front-end or back-end code...
Try this and see of it works any better..
$('#Wrapper').load('page2.asp?id='+$(this).attr('id'));

Try this:
$(function () {
$("#page2btn").click(function () {
$.ajax({
url: 'page2.asp',
data: { id: $(this).attr('id') },
success: function (data) {
$('#dynamic_content_div').html(data);//data = <h1>Test 2</h1>
}
});
});
});
HTML:
<div id="Wrapper">
<div id="menu">
<a class="navbutton" onclick="MakeRequest1()">Home</a> <span class="navbutton">|</span>
<a class="navbutton" id="Page2btn">Page2</a> <span class="navbutton">|</span>
<a class="navbutton" onclick="MakeRequest3()">Page3</a>
</div>
<div id="dynamic_content_div">
<h1>Test1</h1>
</div>
</div>

Javascript is case sensitive. You are using lowercase in case of assigning the event -
$(function () {
$("#page2btn").click(function () { //lowercase P
...
});
});
but using uppercase for html id
...
<a class="navbutton" id="Page2btn">Page2</a> <span class="navbutton">|</span> //upper case P
...
so, it never finds the item to bind to, thus nothing happens when you click. Either change js to -
$("#Page2btn").click(function ()
or change html to -
<a class="navbutton" id="page2btn">Page2</a> <span class="navbutton">|</span>
Other than this, I don't see the error.

Try jQuery replaceWith method, like this:
$(function () {
$("#page2btn").click(function () {
$.ajax({
url: 'page2.asp',
data: { id: $(this).attr('id') },
success: function (data) {
$("#Wrapper").replaceWith(data); //try with double qoutes
}
});
});
});
*The link below maybe helpful:
Change content of div using jQuery

Related

How to get values from a hidden field that is created in forEach with different values?

I’ve been working with jquery recently. I need to remove parameters from hidden fields that are created through forEach, that is, under class = "productID", the values ​​are different. How do I click on the button to take the value only from the desired hidden field.
<div id="successAdded" style="color: green">
<h3>${sessionScope.successAdded}</h3>
</div>
<c:forEach items="${sessionScope.allProducts}" var="products">
<div class="col-md-4 fashion-grid">
<a href="single.jsp"><img src="images/product/${products.imageName}" width="250" height="350" alt="" />
<div class="product">
<h3>PRODUCT NAME:</h3>
<input type="hidden" class="productID" value="${products.id}">
<span class="getName">${products.name}</span>
<p>${products.size}</p>
<p>${products.color}</p>
<p>${products.category.name}</p>
<p>${products.manufacturer.name}</p><br></br>
<p><span></span>${products.price}</p>
</div>
</a>
<div class="fashion-view"><span></span>
<div class="clearfix"></div>
<input type="button" class="addProductToCart" style="margin-top: 50%;" value="Add to cart" />
</div>
</div>
jQuery(document).ready(function() {
$('.addProductToCart').on('click', function getPage() {
var id = $(this).find('.productID').val();
alert(id);
$.ajax({
type: "GET",
url: "cart",
data: "productID=" + id,
success: function(page) {
$("#header men").text(page);
$("#productCount").text("(" + page['productCount'] + ")");
}
});
});
I get undefined value in my implementation
You have two issues here. Firstly, the hidden element has a class on it, so you need to prefix the selector with a ., eg. .productID.
Secondly, you're using find() from the clicked button to find the hidden field, yet it's not a child of this element. Instead it's a child of a parent's sibling. As such you need to combine closest(), prev() and find() to retrieve it, like this:
jQuery(document).ready(function() {
$('.addProductToCart').on('click', function getPage() {
var id = $(this).closest('.fashion-view').prev('a').find('.productID').val();
console.log(id);
$.ajax({
type: "GET",
url: "cart",
data: { productID: id },
success: function(page) {
$("#header men").text(page);
$("#productCount").text("(" + page['productCount'] + ")");
}
});
});
});

Javascript function doesn't work after adding content dynamically through ajax

I have a function
function reply(id) {
$('#reply_'+id).toggle();
return false;
}
And Ajax function
<script type="text/javascript">
function post()
{
var comment = document.getElementById("comment").value;
var course_id = document.getElementById("course_id").value;
var user_id = document.getElementById("user_id").value;
if(comment)
{
$.ajax
({
type: 'post',
url: 'comments.php',
data:
{
comment:comment,
course_id:course_id,
user_id:user_id
},
success: function (response)
{
document.getElementById("comment-list").innerHTML=response+document.getElementById("comment-list").innerHTML;
document.getElementById("comment").value="";
}
});
}
return false;
}
</script>
And the content that is added after ajax call
...
...
<p class="text-right"><i class="fa fa-reply"></i> reply</p>
...
...
<div class="row" id="reply_<?php echo $i; ?>" style="display: none;">
...
...
So basically that javascript functions toggle the div and it is working perfectly fine on page refresh but when adding through ajax success call the javascript toggle doesn't work. It will work after I refresh the page.
Anyway to fix this so toggle work when content added through ajax without refresh.
Thanks.
Change your content that is added after ajax call as below:
<p class="text-right">
<a href="#" data-id="<?php echo $i; ?>" class="btn btn-default btn-sm btnReply">
<i class="fa fa-reply"></i> reply</a></p>
and write jquery code as below
$("body").on("click", ".btnReply", function(event){
var id =$(this).attr('data-id');
reply(id);
});

Combine/bind many on change, on click event of many tags with different id or class

In my view I have many tags with differents classed and ids like this:
<!-- html view -->
<div class="panel panel-default">
<ul class="" id="tablist" role="tablist">
<li class="getState active" id="proposed">
<b>Proposed</b>
</li>
<li class="getState" id="current">
<b>Current</b>
</li>
<li class="getState" id="incoming">
<b>Incoming</b>
</li>
<li class="getState" id="finished">
<b>Finished</b>
</li>
</ul>
</div>
<select class="form-control" id="isProduction">
<option value="" disabled selected>Type</option>
<option value="production">Production</option>
<option value="nonProduction">nonProduction</option>
</select>
<div>
<!-- some content here like <p></p> -->
<a href="#validity">
<button class="btn btn-default">Validity</button>
</a>
</div>
<div>
<!-- some content here like <p></p> -->
<a href="#rate">
<button class="btn btn-default">Rate</button>
</a>
</div>
<!-- content appear here -->
<div id="info">
<!-- put some content here following click and selected option change -->
</div>
Using jQuery, I would like to catch all clicks, changes of these tags, more precisely if user click on a <li></li> tag with class .getState, or if user have selected an option of the <select></select> tag which has the id #isProduction or if user have click on the other <button></button> tag wich have <a href="#validity"> or <a href="#rate">.
Like this example:
<script type="text/javascript" charset="utf-8" defer>
$('.getState').bind('click', function sortByState(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
});
</script>
Here I could make a request (php server side) by recovering the state, then I could make a request with this argument.
How can I combine all these event in only one function in order to recover all the argument I need for my php server side using jQuery ?
I see on the doc here, that we could create a bind on multiple event like this:
$( "#foo" ).bind( "mouseenter mouseleave", function() {
$( this ).toggleClass( "entered" );
});
If I understand correctly you want to attach same event to multiple elements, if yes that could be done using comma separator ,:
$('body').on('click','#isProduction, .getState, button.my-btn',function(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
})
NOTE : For the two buttons better if you could add a class to them so you will attach event just to them button.my-btn instead of attaching it to button so that will not infect other buttons click event.
<button class="btn btn-default my-btn">Validity</button>
<button class="btn btn-default my-btn">Rate</button>
Or also you could use separated function and attach events separately but trigger the same action :
$('body').on('click','.getState, button.my-btn',myAction);
$('body').on('change','#isProduction',myAction);
function myAction(){
var infoDiv = $('#info');
$.ajax({
type: "GET",
url: window.location.href,
data: {
state: $(this).attr("id"),
},
success: function(html){
infoDiv.empty();
var newinfoDiv = $(html).find('#info');
infoDiv.append(newinfoDiv);
infoDiv = newinfoDiv;
}
});
}
Hope this helps.
$('body').on('click','.getState, button.my-btn',myAction);
$('body').on('change','#isProduction',myAction);
function myAction(){
alert('myAction');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<div class="panel panel-default">
<ul class="" id="tablist" role="tablist">
<li class="getState active" id="proposed">
<b>Proposed</b>
</li>
<li class="getState" id="current">
<b>Current</b>
</li>
<li class="getState" id="incoming">
<b>Incoming</b>
</li>
<li class="getState" id="finished">
<b>Finished</b>
</li>
</ul>
</div>
<select class="form-control" id="isProduction">
<option value="" disabled selected>Type</option>
<option value="production">Production</option>
<option value="nonProduction">nonProduction</option>
</select>
<div>
<!-- some content here like <p></p> -->
<a href="#validity">
<button class="btn btn-default my-btn">Validity</button>
</a>
</div>
<div>
<!-- some content here like <p></p> -->
<a href="#rate">
<button class="btn btn-default my-btn">Rate</button>
</a>
</div>
<!-- content appear here -->
<div id="info">
<!-- put some content here following click and selected option change -->
</div>
You can use below code to capture trigger click event on whole page and then you can write desired code to be executed:
$('body').bind('click',function(){
//your code here
});

Jquery on('click') not firing after first click

I have some HTML:
<div class="post-container self">
<a href="/user/Wiz">
<img class="avatar" alt="Profile Picture" src="">
</a>
<div class="post-body">
<div class="post" style="margin-left:0px;">
<div class="post-timestamp" style="display:inline-block;float:right">
Oct 31
</div>
<div class="post-functions dropdown displaynone" style="float:right;margin-right:5px;">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:void(0)">
<i class="icon-cog">
</i>
</a>
<ul class="dropdown-menu post-dropdown" role="menu" aria-labelledby="dLabel">
<a class="post-delete" href="javascript:void(0)"><i class="icon-trash"> </i>Delete</a>
</ul>
</div>
</div>
</div>
</div>
And with that, I have some Jquery:
$('.posts-content').on('click', '.post-delete', function(e) {
$('.post-dropdown').dropdown();
if (confirm('Are you sure you want to delete this post?')) {
var $this = $(this);
$.ajax({
url: '/a/delete_post',
type: 'POST',
dataType: 'json',
data: {'p' : post_id},
success: function() {
//...
return true;
}
});
}
return false;
});
Everything works perfectly the first click, but if I go to another post, and try to click .post-delete, the event never fires, and nothing shows up in the console. It also works if I use $.click(), but I need to dynamically create elements. Why does the $.on('click') not fire the second click?
My guess is that dropdown plugin you use change the DOM structure.
$('.post-dropdown').dropdown();
BTW,
$this.parent().parent().parent().parent().parent() this is really really bad practice.
You should use closest instead.
If you are dynamically creating elements try:
$(document).on('click', '.post-delete', function(e) { });

Cannot debug jQuery button

I have this button, and when clicked, it sends an ajax call which changes the value of score_up.
I dont see what the problem is. I tried firbug, but apparently it's not even detecting the javascript? :)) Thanks.
jquery:
$('.stats').delegate('.support', 'click', function(e) {
//stop event
e.preventDefault();
//get the id
var the_id = $(this).closest('.score').attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$(this).siblings("h2.score_up").html(msg).fadeIn();
//remove down button
// and remove support button
}
});
});
html:
<ul class="stats">
<li id="support_23"class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>
//vote down button
<li id="down_23"class="score">
<h2 class="score_down">12</h2>
<span style="text-align:center;">down</span>
</li>
<li>
<button type="submit" value="Actions" class="down" title="down">
<i></i>
<span>down</span>
</button>
</li>
</ul>
It is not valid HTML for a <button> to be a direct child of a <ul>.
Children of <ul> should be <li>. I wouldn't expect things to work properly with invalid HTML.
HTML with <button> inside a <li>:
<ul class="stats">
<li id="topic_23" class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>
</ul>
jQuery, fixing some of the traversal methods:
$('.stats').delegate('.support', 'click', function(e) {
//stop event
e.preventDefault();
// cache a reference to the previous <li> element
// since it is used more than once
var $prevLi = $(this).closest('li').prev('li');
//get the id
var the_id = $prevLi.attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$prevLi.find("h2.score_up").html(msg).fadeIn();
}
});
});
Your HTML is invalid, so I would do:
<form action="javascript:alert('form')";>
<ul class="stats">
<li id="topic_23"class="score">
<h2 class="score_up">12</h2>
<span style="text-align:center;">Supporters</span>
</li>
<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i><span>Support</span></button>
</li>
</ul>
</form>
And then the jQuery (which in your original would not work, since you wanted .siblings() and not .closest() would now be:
var the_id = $(this).closest("li").siblings('.score').attr('id')
.split('_').pop();
and success:
$(this).closest("li").siblings("li.score").find("h2.score_up")
.html(msg).fadeIn();
I think you also run into troubles with prevent default, since you want to prevent default on the form, and in that case you might run into problems with delegate.
Here is what I would do with .live():
// Prevent form from submitting
$("form").live("submit", function(e) {
e.preventDefault(); });
// Run Ajax
$('button.support').live('click', function(e) {
//get the id
var $score = $(this).closest("li").siblings('.score'),
the_id = $score.attr('id').split('_').pop();
//the main ajax request
$.ajax({
context:this,
type: "POST",
data: "action=support&id=" + the_id,
url: "ajax/sa.php",
success: function (msg) {
$score.find("h2.score_up").html(msg).fadeIn();
}
});
});
​
Try it out on this jsFiddle

Categories

Resources