Ajax request inside an other ajax - javascript

So i made an ajax request for get my "home" page and my "about" page in a "container" on click menu link button inside my index.php, and now i have three link in my "home" page, and i also want open each of these links inside my div "container" to replace the "home" page, so how can i make an ajax request after the first ajax call ?
This is my php request in the index.php:
<div id="container">
<?php
$d="contenu/";
if(isset($_GET['p'])){
$p=strtolower($_GET['p']);
if(preg_match("/^[a-z0-9\-]+$/",$p) && file_exists($d.$p.".html")){
include $d.$p.".html";
}
else{
include "pages/404.html";
}
}
else{
include "pages/home.html";
}
?>
</div>
In here my ajax:
$(document).ready(function(){
$("#menu a").click(function(){
page=$(this).attr("href");
$.ajax({
url: "pages/"+page,
cache:false,
success:function(html){
afficher(html);
},
error:function(XMLHttpRequest,textStatus, errorThrown){
afficher("erreur lors du chagement de la page");
}
});
return false;
});
});
function afficher(data){
$("#container").fadeOut(500,function(){
$("#container").empty();
$("#container").append(data);
$("#container").fadeIn(1200);
});
}
and finally my home.html ( i just show you the links ):
<div class="section vs-section" data-speed="0.4">
<div class="vs-transform title " data-speed="0.4"><h3>projet1</h3></div>
<div class="vs-transform title" data-speed="0.38"><h3>Projet2</h3></div>
<div class="vs-transform title" data-speed="0.4"><h3>projet3</h3></div>
</div>

Yes you can, you should just use event delegation on() to deal with the new HTML tags added dynamically to the DOM by the first ajax request :
$('body').on('click', '.vs-transform a', function(){
//Second ajax request
})
Hope this helps.

Related

How to post form inside load() div

I have form with $_POST type from second page,on first page i've loaded the form with this code :
<div class="option_dialog" id="search">
<div class="close_option">Search <img onclick="search()" style="float:right;height:20px" src="img/close.png">
</div>
<div id="search_content" style="overflow:scroll;max-height:400px">
<script>
$('#first_page_div').load('second_page.php #second_page_form');
</script>
</div>
</div>
When the function search() called using onclick the above code will excuted and load the form from second page...then i submit the form using this code :
$(function () {
$('#form_id').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'second_page.php',
data: $('#form_id').serialize(),
success: function () {
$('#first_page_search_result').load('second_page.php #searched_result');
search_result();
}
});
});
});
When form submited via ajax on first page,the second page should process his/her request and return the searched result on first page and execute search_result() which is another hidden div will be shown after returned result.
please tell me how to make this work?regards

How do I toggle content between tabs through ajax/php?

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.

Jquery serialize form not iniating,

I am loading a form via jquery load, which populates the content div, the form etc is showing up fine, but when I go to update the form with values it doesn't trigger my on("submit"
My jquery
<!-- process update profile form without refreshing, then load the div with the new information !-->
$("#content").on("submit", "#update_profile_form", function() {
alert("jfjf");
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: $(this).serialize(),
success: function(data) {
if(data.success == "false"){
$.notify(data.error, "error");
}else{
$.notify(data.success, "success");
$("#content").load("<?php echo Config::get('URL'); ?>user" + " #inner_main_content");
}
}
});
return false; <!-- important: prevent the form from submitting !-->
});
<!-- end process update profile form without refreshing, then load the div with the new information !-->
My form:
<form action="<?php echo Config::get('URL'); ?>/user/update_personal_information" method="POST" id="update_profile_form">
<!-- inputs here !-->
<input type="submit" class="btn vd_btn vd_bg-green col-md-offset-10" name="submit" id="submit" value="<?php echo System::translate("Update"); ?>">
<span class="menu-icon">
<i class="fa fa-fw fa-check"></i>
</span>
I am simply loading the form in to content via this code:
//populate the div
$('.list-group-item').click(function(e){
e.preventDefault();
var link = $(this).attr('href');
$('#content').fadeOut('slow', function(){
$("#content").load( link + " #inner_main_content", function(){
$('#content').fadeIn('slow');
});
});
The alert trigger in the on submit isn't even popping up which makes me beleive that it's not triggering, and I am receiving no errors neither. I am binding the on submit to the content id because that's the main div it loads to, so how can I iniate the form to work?
Here's the full form: http://pastebin.com/iGsPZmWT
I'm not sure to clearly understand the whole of your architecture, nor the precise case of your issue, but here is how I can summarize what I understand:
#content part includes the #submit element
#content part is first the direct content of the initial page, and is functional (triggers on submit)
when submit happens, #content part is overwritten by the .load() process
then #content part becomes non-functional (nothing happens on submit)
If it is really so, then the issue is pretty "normal": the submit event you attached to #content is lost when you load a new #content content (sorry for the repeat, but it comes from the id you'd choosen!).
Even if the new content also includes a #submit element, this one has no event attached to it now.
One solution is to execute the attachment again when a new content has been loaded, like this:
function attachSubmit() {
$("#content").on("submit", "#update_profile_form", function() {
alert("jfjf");
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: $(this).serialize(),
success: function(data) {
if(data.success == "false"){
$.notify(data.error, "error");
}else{
$.notify(data.success, "success");
$("#content").load("<?php echo Config::get('URL'); ?>user" + " #inner_main_content");
attachSubmit(); // <<-- here we attach event again to new content
}
}
});
return false; <!-- important: prevent the form from submitting !-->
});
}
(note that you also have to initially invoke attachSubmit() somewhere in a $(document).ready() sequence)
Alternatively you might attach a delegated event, so once is enough. In this case, though, you'll have to attach it to a parent element of #content, instead of #content itself, something like this:
// Here #parent is supposed to be a parent of #content
// The on() method got a #submit arg, as selector for delegation
$("#parent").on("submit", "#submit", "#update_profile_form", function() {
alert("jfjf");
$.ajax({
// ... same as YOUR previous version (nothing added)
});
return false; <!-- important: prevent the form from submitting !-->
});

HTML Links do not work after AJAX POST

Background: I am working on a small web application. AJAX will successfully POST the data to the action(create.php) and create.php will execute the necessary mysql query. Once AJAX is done, I append a message to the div id="container"></div> informing the user of a successful execution then clear the content "container" for future use; however, here in lies the problem.
Problem: After AJAX executes, I can not click on any HTML links already loaded onto the page(page.php). I have to refresh the page in order to click on any links and follow them to their destination. What is causing this to happen and how can I fix it?
AJAX does not need to return a result. It only needs to execute the specified jQuery code once the request is done. On a hunch, I altered create.php to echo the $_POST array and have AJAX return that as a result. Once AJAX loads the result into the "container" I still can not click on any links loaded on page.php
Answer: The DOM was not being reloaded after AJAX calls causing bootstrap dropdown menus to not function properly. The bootstrap dropdown class had to be manually reinitialized after each call. This has already been answered in detail here
create.php
<?php
if($_POST){
//run mysql query
}else{
//do nothing
}
?>
form.php
<form id="new-items">
<input type="text" name="item" />
<input type="button" onclick="create_item()" name="Submit" value="Submit" />
</form>
page.php
<html>
<head>
<script>
$(document).ready(function(){
$("#add_items").click(function(){
event.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow");
}, 5000);
setTimeout(function(){
$("#content").empty();
}, 8000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>
Link1
Link2
Add New Items
</nav>
<div id="content"></div>
</body>
</html>
After you fadeOut the #content element, it remains hidden. The next time you call your AJAX function, it's loading create.php into an invisible element.
Try:
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
Other issues: <div class="content"> should be <div id="content">; you didn't include jquery.js at the top of your script; you didn't pass the event object e to your click handler.
page.php should now look like:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#add_items").click(function(e){
e.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>Add New Items</nav>
<div id="content"></div>
</body>
</html>
The anchor links in the <nav> will natually 'refresh' the page with the new content.
If you want to load the content via an ajax request then you should try the following:
Add a common class to the links
<nav>
Link1
Link2
Add New Items
</nav>
Then attach a click event to each link which intercepts the default page refresh with e.preventDefault(). The you can perform the ajax request using the href attribute of that link.
$(function(){
$(".anchor").on('click', function(e){
e.preventDefault();
var $this=$(this);
$("#content").load($this.attr('href'));
});
});
The DOM was not being reloaded after AJAX call. Boostrap dropdown module has to be manually reinitialized after each call. Detailed answered here: answer

when loading a page content through ajax post and codeigniter load functions, some jquery functions are in the head section cannot be called

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.

Categories