Second ajax request doesn't work - javascript

I made an ajax website calling pages from /pages folder inside an ajax-container div in my index.php.
Now i want to make a second ajax request after the first ajax request success but the second request will be only on certains page,
for example: i call the page work.php and inside this page i want to call a page work-slider from the same folder and replace the work.php page by work-slider.php in my ajax-container div when i click on images link-in
but i can't find a solution for make it,
This is my actual code:
index.php:
<div id="ajax-container">
<?php
$d = "pages/";
if (isset($_GET['p'])) {
$p = strtolower($_GET['p']);
if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".php")) {
include $d . $p . ".php";
} else {
include $d . "404.php";
}
} else {
include $d . "home.php";
}
?>
</div>
Ajax function:
var afficher = function(data) {
$('#ajax-container').fadeOut(250, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});
});
};
var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
lastRequest = $.ajax({
url: "pages/" + page,
cache: false,
success: f$.ajax({
url: "pages/" + page,
cache: false,
success: function(resultFirst) {
afficher(resultFirst);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
$.ajax({
// How can i define pageIn variable ??
url: "pages/" + pageIn,
cache: false,
success: function(resultSecond) {
afficher(resultSecond);
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.php');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
// link inside index.php
$('.link').bind('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
loadPage(page);
return false;
});
// second link inside called page
$('.link-in').bind('click', function(e) {
e.preventDefault();
var pageIn = $(this).attr('href');
loadPage(pageIn);
return false;
});

If that .link-in tag if dinamically inserted into the DOM after the page loads, the bind() method will fail: bind() attach listeners to elements it find when called. If you add a new elemenent after the bind call, it will not receive the listener binding.
In order to prevent that when dinamically inserting html code in a page, you should use the on() method:
$('body').on('click' , '.link-in', function(e) {
e.preventDefault();
var pageIn = $(this).attr('href');
loadPage(pageIn);
return false;
});
And now, every .link-in tag you push dinamically inside body will respond to the click listener. A discussion on using on() by default instead of bind() is in fact found in the bind() documentation.

Related

AJAX script disappears after live refresh

so I've got 2 AJAX scripts and one of them disappears when the first script is fired.
Script 1:
function myFunction<?php echo $product['sku'] ?>() {
// AJAX CALL
var url = "remove.php?isbn=<?php echo $product['sku'] ?>";
$.ajax({
url: url,
success: function(data){
$('#refresh').load(location.href + ' #results');
bs4pop.notice('Το προϊόν αφαιρέθηκε με επιτυχία', {position: 'topcenter', type: 'success'});
},
complete: function(){
}
});
};
Script 2:
$('#insert').on('click', function () {
var $this = $(this);
var loadingText = '<i class="spinner-border float-right spinner-border-sm"></i> Παρακαλω Περιμενετε...';
if ($(this).html() !== loadingText) {
$this.data('original-text', $(this).html());
$this.html(loadingText);
}
//Disable our button
$('.btn-dis').attr("disabled", true);
$('.checked').attr("disabled", true);
//The URL that we are sending an Ajax request to.
var url = "insert.php?woocommerce";
$.ajax({
url: url,
success: function (data) {
bs4pop.notice('Η εισαγωγή έγινε με επιτυχία', {
position: 'topcenter',
type: 'success'
})
$this.html($this.data('original-text'));
},
complete: function () {
$('#refresh').load(location.href + ' #results');
$('.btn-dis').attr("disabled", false);
$('.checked').attr("disabled", false);
}
});
});
They are both wrapped into two divs $('#refresh').load(location.href + ' #results');, when i click the button that fires the first script the second script disappears.
What seems to be the problem?
Thank you and regards.
Ok so i got it working, i moved the button which fired the second script outside the refresh div and it worked like a charm.

div.load() causing full page postback

After saving form data, need to load the div only not whole page refresh but it first goes to Main Page Action Controller and then the DIV Load Partial Action Controller. I am unable to find the reason why it is posting whole page.
I have added the preventDefault() command too.
$("#btnSave").click(function (e) {
e.preventDefault();
var url = "#Url.Action("Save", "Note")";
var id = "1";
var model = {
modelfields.....
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json",
success: function (data) {
if (data == "True") {
// Load div
var settings = { editUrl: '#Url.Action("Get", "Note", new { ID = "-1" })' };
settings.editUrl = settings.editUrl.replace("-1", id);
$("#divNoteDetails").load(settings.editUrl);
}
else if (data == "False") {
alert('not saved');
}
},
error: function () {
alert('error');
}
});
return false;
});
if your button is inside a form then its default type is submit. see the spec for details
try adding type="button" to the button, or event.preventDefault() on an event handler attached to the form itself.

Getting a post variable inside a function

I have a case where I want to pass a variable inside a function.
The code gives more clarity:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
function loadData(page){
$.ajax({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page }),
success: function(msg) {
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings) {
$(\"#subscritor #container\").html(msg);
});
},
error: function(){
alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function() {
var page = $(this).attr('p');
loadData(page);
});
$('#subscritor #go_bt').live('click',function() {
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>";
?>
As shown in the code,
I would like to know how could I pass $id inside the loadData(page) function .
I get this variable from a post request made with ajax, and need to use it inside the function to pass it has variable to loadSubscritor.php
Any idea on how to do it?
EDIT 1: I guees I wasnt very clear on what I wanted, i want to do this :
function loadData(page){
$.ajax({
data: ({ page:page id:$id }),
Thanks in advance.
Well, if I understood what you are trying to achieve you could replace this :
$id=$_POST['id'];
By this :
$id = isset($_POST['id']) ? $_POST['id'] : 1;
And this :
loadData(1); // For first time page load default results
By this :
loadData($id);
For explanation, if it's first time page load, $id will be set to "1".
Else, this will come from $_POST['id'].
Inside your jquery code you can call a php variable in following way
var current_page = "<?php echo $id; ?>" ;
You can make a local variable and easily use as below:
<?php
$id=$_POST['id'];
echo "
<script type=\"text/javascript\">
var id = \"".$id."\";
$(document).ready(function(){
function loadData(page){
$.ajax
({
type: \"POST\",
url: \"loadSubscritor.php\",
dataType: \"html\",
data: ({ page:page
}),
success: function(msg)
{
$(\"#subscritor #container\").ajaxComplete(function(event, request, settings)
{
$(\"#subscritor #container\").html(msg);
});
},
error:
function()
{ alert('alertErr');
}
});
}
loadData(1); // For first time page load default results
$('#subscritor #container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(id);
});
$('#subscritor #go_bt').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(id);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val(\"\").focus();
return false;
}
});
});
</script>
<h3>Subscritor</h3>
<div id=\"subscritor\">
<div id=\"container\">
<div class=\"pagination\"></div>
</div>
</div>
";
?>

Call html and Php pages with Ajax

I made an ajax function that call my html pages inside an ajax-container div in my index.php, so now how can i do if i also want to call php pages in ajax?
There is my code:
htaccess rewrite
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule ^([a-zA-Z0-9\-]*).html$ index.php?p=$1 [L]
index.php
<div class="link" href="page2.html">go html</div>
<div class="link" href="page3.php">go php</div>
<div id="ajax-container">
<?php
$d = "pages/";
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 $d . "404.html";
}
}
else
{
include $d . "home.html";
} ?>
</div>
And this is my ajax function calling html pages from folder pages/
var afficher = function(data, page) {
$('#ajax-container').fadeOut(100, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});
});
};
var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
lastRequest = $.ajax({
url: 'pages/' + page,
cache: false,
success: function(html) {
afficher(html, page);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.html');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
$(document).ready(function() {
$('.link').bind('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
loadPage(page);
return false;
});
});
If you want to execute php and display what it returns on a div you can use jQuery and ajax:
$(function(){
$(".myDivClass").load('yourPHPFile.php');
}());

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

Categories

Resources