I have divided my content in two tabs and switching between two tabs with javascript.
<div class='tab-container'>
<div class='tab-1'>
<?php
$sql="SELECT * FROM posts WHERE status='tab1'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
<div class='tab-2'>
<?php
$sql="SELECT * FROM posts WHERE status='tab2'";
echo "<div class='db'
<h2>post</h2></div>";
?>
</div>
</div>
Php code divides content between tabs through WHERE clause select * from posts where status='tab1'; so to remove post from one tab ajax request given below triggers php code which updates status of content from tab1 to tab2.
<script type="text/javascript">
$(function() {
$(".restore").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Restore?"))
{
$.ajax({
type: "GET",
url: "restore.php",
data: info,
success: function(){
}
});
$(this).parents(".db").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
So that post is removed from tab1. Idea here is to move post from one tab to another through ajax. javascript works good on removing post from one tab however for making that post appear in another tab I have to reload page as I haven't used ajax for that. So problem is I don't get how to add that post dynamically to another tab through ajax without refreshing page.
To get content from ajax call, you have to echo it in server side.
May be something like this
echo "hi, this is new content";
Now in ajax success
success: function(data){
alert(data); this will alert what was echoed in php(hi, this is new content)
}
If you want to add the content to some div in view,
$("class or id for the div").html(data);
In restore.php, you should get the selected post and then then update the status of that post to tab2. And append that result in main php page. You can append the same via restore.php.
Try this
HTML
<div class="tabs" id="d-tab1"></div>
<div class="tabs" id="d-tab2"></div>
<a href="#" class="restore" id="tab1">
<a href="#" class="restore" id="tab2">
JS
$('.restore').click(function(e){
e.preventDefault();
var $tab = $(this);
$.post('restore.php',{id: $tab.attr('id')},function(html){
$('.tabs').hide();
$('#d-'+$tab.attr('id')).html(html).show();
})
})
Or use Jquery tabs https://jqueryui.com/tabs/
Agree with #Niranjan N Raju. But want to add some addition.
Use console.log(data) instead alert(data) as last don't shows object info.
Related
I have a site built using wordpress as the cms and the index has a long accordian style list of post titles and once you click on this heading the content for that post is loaded via ajax into the index page.
I have the problem that when the heading is clicked again, it loads the post content again and if you click a different heading it won't close and remove the previous one that has been clicked.
I am new to working with ajax and unsure how to go about fixing this. Is there a way to make the content be removed once the heading is clicked a second time to close the accordion or another heading is clicked to expand and open. Live site is here: http://www.minervasydney.com/
Below is the code for my ajax and the part in my index file that lists the headings. If anyone has ideas it would be greatly appreciated. Thank you!
AJAX
$("a.exhibitionInformation").on("click", function(event) {
var exhibitionContainer = $(this).parent(".exhibition");
var url = $(this).attr("href");
var doc = $(this).next(".exhibitionDocuments");
var title = convertToSlug($(this).text().split("\n")[1]);
var slug = $(this).attr("data-slug");
$(this).toggleClass("selected");
if($(doc).is(':not(:hidden)')) {
$(doc).slideToggle();
} else {
$.ajax({
url: url,
type: "GET",
success: function(data) {
var content = $(data).find(".single-document");
$(doc).append(content).slideToggle(300);
$("html, body").animate({ scrollTop: exhibitionContainer.offset().top - 26 });
window.location.hash = slug;
}
});
}
event.preventDefault();
});
//ajaxstarStop Loading
$( document ).ajaxStart(function() {
$( "#loading" ).fadeIn(100);
});
$( document ).ajaxStop(function() {
$( "#loading" ).fadeOut();
});
function convertToSlug(Text)
{
return Text
.toLowerCase()
.replace(/ /g,'-')
.replace(/[^\w-]+/g,'')
;
}
INDEX
<section class="exhibition">
<a class="exhibitionInformation" href="<?php the_permalink(); ?>" data-slug="<?php echo $post->post_name; ?>">
<span class="dates"><?php echo types_render_field("dates", array("argument1"=>"value1")); ?></span>
<span class="opening"><?php echo types_render_field("opening", array("argument1"=>"value1")); ?></span>
<span class="title">“<?php the_title(); ?>”</span>
<span class="artist"><?php echo types_render_field("artist", array("argument1"=>"value1")); ?></span>
<span class="extra"><?php echo types_render_field("extra", array("argument1"=>"value1")); ?></span>
</a>
<article class="exhibitionDocuments">
</article>
</section>
Within your ajax request:
$.ajax({
url: url,
type: "GET",
success: function(data) {
var content = $(data).find(".single-document");
$(doc).append(content).slideToggle(300);
$("html, body").animate({ scrollTop: exhibitionContainer.offset().top - 26 });
window.location.hash = slug;
}
});
On the second line under success, change .append to .html.
The line should now be:
$(doc).html(content).slideToggle(300);
It will load the content AND remove previous if there was.
EDIT
To close a previously opened .exhibitionDocuments:
$(document).find(".exhibitionDocuments").hide();
Place it on top of your success callback.
(right before var content = $(data).find(".single-document");)
I have a php page that i call a calendar class function to show the calendar. which is just
$calendar->show(true);
It has another function that lets you call it by
$calendar->show('July 2015')
So what i am trying to do is create a header on top that shows next and previous and then have it be a link, but i am trying to figure out how i can click on the previous link that when i click on it, just reruns the function with the date specified instead of reloading the whole page again and using url parameters. I've been looking into ajax and jquery, it seems possible, but it only shows how to post to a php page. I can't find a way to just rerun a function if thats even possible.
you need code like this:
HTML:
<div id='next' class='year'></div>
<div id='next' class='month'></div>
<div id='prev' class='day'></div>
<div id='date'></div>
<div id='next' class='day'></div>
<div id='next' class='month'></div>
<div id='next' class='year'></div>
jQuery:
$('.day, .month, .year').click(function() {
var a = $(this).attr('id'); // find prev or next clicked
var b = $(this).attr('class'); // find day or month or year clicked
$.ajax({
type: 'post',
url: //your php url,
data: {act: a, which: b, /* your other data */},
cache: false,
success: function(c) {
$('#date').html(c);
}
}):
});
and PHP:
<?php
include //your class
echo $calendar->show('$_POST['data']')
?>
I know My question Title is not perfectly describe my question extremely sorry about that. I don't know how to tell this as a summery. anyway this is my question.
I am making a admin panel to change some of the content in my web page. this scenario is for change slideshow images.
ok then after someone logged into my page I am loading three pages. like this.
$this->load->view('admin/header');
$this->load->view('admin/menu');
$this->load->view('admin/table_and_editor_holder');
all the page contents I have mentioned below. so basic path is like this. once someone logged he can click the button [slide manage] to load the images and details of already inserted slides. these are getting from a database. so once he clicked the menu button. this jquery function is executing.
$('.menu-item > a').on('click', function() {...})
this function simply getting a html page. filled with previous slide details. this is the controller function handle the menu request.
function slider_edit_delete() {
$sdata['slide_imgs'] = $this->admin_basic_curd->get_all_items('sider_images');
$slide_manager = $this->load->view('admin/slider_manager', $sdata, TRUE);
echo $slide_manager;
}
so previous jquery function is then appending this page content to a div like this.
$('#table_container').html(data);
so inside this page content I have a buttons call edit for each slide already inserted. so by clicking on of this button I can edit that slide image or some test content of it. that button is like this.
<a class="onclick_post_by_a" href="<?php echo base_url() . 'adm_edit_this_slide/' . $sl->id; ?>">
<button class="btn btn-info"> Edit </button>
</a>
so by clicking this button must execute this function in the header section and this function must add a html form (in a separate page) to the #editor-form-container div as previously
$('.onclick_post_by_a').on('click', function() {...})
but the problem is once I click the edit button it couldn't find this function. so it is opening the content as a separate page
How can I make this to work? Thank you
the header page contains all the css and js file links. and some jquery functions. like this.
<script>
$(document).ready(function() {
$('.menu-item > a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#table_container').html(data);
});
return false;
});
$('#editor-form-container').css({
display: "none"
});
function posting_url(url, pdata) {
return $.ajax({
url: url,
data: pdata
});
}
$('.onclick_post_by_a').on('click', function() {
var url = $(this).attr('href');
var pdata = "";
var rdata = posting_url(url, pdata);
rdata.success(function(data) {
$('#editor-form-container').css({
display: "block"
});
$('#editor-form-container').html(data);
});
return false;
});
$('.post_with_image').on('submit', (function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log("success");
console.log(data);
},
error: function(data) {
console.log("error");
console.log(data);
}
});
}));
});
</script>
</head>
then I have load menu page. it is like this.
<div class="admin-navi">
<div class="menu-item">
Home
</div>
<div class="menu-item">
Side Manage
</div>
</div>
<div class="clearfix"></div>
table_and_editor_holder.php page. it is like this.
<div class="col-lg-12">
<div class="col-lg-2"></div>
<div id="table_container" class="col-lg-8">
</div>
</div>
<div id="editor-form-container" class="col-lg-6">
</div>
Dynamically created element does not respond to direct call to events like below -
$('.onclick_post_by_a').on('click', function() {...})
So you have to write like this
$(document).on('click', '.onclick_post_by_a', function() {...})
Just try it out.
I have a dynamically changing span on a page displaying the number of votes a project has received. On another (target) page i have a list of projects. i want to be able to display that vote count there. i know how to grab the text from the span on the page.
it would be something like this.
<span id="count1"></span>
var prj1c = $("#count1").text;
in know that on the other page i end up using
<?php echo $prj1c(this being after i assign the prj1c var to php somewhere) ?>
i also know i could create a php include page and call it on the target page, though i would like not to create a separate page for each of these instances.
so to sum up: how do i change a JS var to php and call it from another page- remember the text in the span changes (when users vote up or down)?
Try this, use .text() instead of .text
var prj1c = $("#count1").text(); //instead of var prj1c = $("#count1").text;
$.ajax({
type: "POST",
url: "yourpage.php",
data: {count :prj1c},
success: function(response) {
alert("Response "+response);
}
});
in yourpage.php add this <?php echo $_POST['count']; ?>
Update:
$(function(){
$("#count1").click(function(){
window.location='page2.php?count='+$(this).text();
});
});
in page2.php:
<ul>
<li id="projectName">
<img><span>vote count goes HERE: <?php echo $_GET['count']; ?></span>
</li></ul>
You can try with jQuery Ajax request. When user vote up/down you can make an ajax call to the target page.
Eg.
var prj1c = $("#count1").text();
$.ajax({
type: "POST",
url: "targetPage.php",
data: "count="+prj1c,
success: function(response) {
alert("Response "+response);
}
});
Get the prj1c value in targetPage.php
$prj1c = $_REQUEST['count'];
// Follow appropriate steps later in targetPage.php
I am trying to display data after being submitted with ajax. The ajax works so far when submitting, but I have to refresh to see it.
Here's the jquery:
$('#submit-quote').live("submit", function(){
var formdata = $(this).serialize();
$.post("add.php", formdata, function(data) {
console.log("success");
});
return false;
});
The php in add.php:
require('includes/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Here's the HTML/PHP that I use to fetch the data and display it:
<?php
require("includes/connect.php");
$result = mysql_query("SELECT * FROM entries", $link);
while($row = mysql_fetch_array($result)){ ?>
<div class="quote-wrap group">
<span>Like</span>
<div class="quote">
<p>
<?php echo htmlentities($row['quote']); ?>
</p>
</div><!-- /.quote -->
</div><!-- /.quote-wrap -->
<?php } ?>
If needed, here's the form:
<form id="submit-quote" method="post" >
<h2> Submit A Quote </h2>
<textarea name="quote">
</textarea>
<input type="submit" name="submit" value="Submit!">
</form>
Ajax works when submitting, but I need to display it after being sent also, how can I do this?
The data variable in your success callback function stores the server response. So to add the server response to the DOM:
$(document).delegate("'#submit-quote'", "submit", function(){
$.post("add.php", $(this).serialize(), function(data) {
$('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + data + '</p></div></div>');
});
return false;
});
If you need to use event delegate (e.g. the form isn't always present in the DOM) then use .delegate() instead of .live() as the latter has been depreciated as of jQuery 1.7.
Also you don't really need to cache $(this).serialize() in a variable since it is only being used once (creating the variable is unnecessary overhead).
Since your PHP code is outputting echo $quotes . "Added to database";, the server response will be the quote with "Added to database` appended to the string, which will be added to your list of quotes.
UPDATE
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
$('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + quoteVal+ '</p></div></div>');
});
return false;
});
Notice that I am no longer referencing the server response (in fact I removed the data variable all together). Instead I am saving the value of the name="quote" element within the form being submitted and using it after the AJAX request comes back (this way the quote is added to the database before being added to the DOM). You could move the .append() code outside the success callback to run it right as the form is submitted (in the submit event handler).
UPDATE
If you want to create a DOM element to append rather than concocting a string:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
//create parent div and add classes to it
$('<div />').addClass('quote-wrap group').append(
//append the "like" span to the parent div
$('<span />').text('Like');
).append(
//also append the .quote div to the parent div
$('<div />').addClass('quote').append(
//then finally append the paragraph tag with the quote text to the .quote div
$('<p />').text(quoteVal)
)
//then after we're done making our DOM elements, we append them all to the .inner element
).appendTo('.inner');
});
return false;
});