Ajax call not succeeding after function call - javascript

I am attempting to load dynamic data based on the specific URI segment thats on the page.
Heres my Javascript:
$(document).ready(function() {
$(function() {
load_custom_topics();
});
$('#topics_form').submit(function() {
var topic = document.getElementById('topics_filter').value
$.ajax({
type: "POST",
url: 'ajax/update_session_topic',
dataType: 'json',
data: { topic: topic },
success: function(){
load_custom_topics()
}
});
return false;
});
function load_custom_topics(){
$.ajax({
type: "POST",
url: 'ajax/load_custom_topics',
dataType: 'json',
data: {},
success: function (html) {
$('div.topics_filter').html(html['content']);
get_threads();
}
});
}
function get_threads(){
var page = document.getElementById('page').value
$.ajax({
type: "POST",
url: 'ajax/get_threads',
dataType: 'json',
data: {page: page},
success: function (html) {
$('div#thread_list').html(html['content']);
}
});
}
});
So, as you can see, on page load, it kicks off load_custom_topics which runs just fine. Its then supposed to call get_threads(). This is where the thing stops, and I get no data.
Get_threads()
public function get_threads()
{
$session = $this->session->userdata('active_topic');
if ($this->input->post('page') == '1')
{
$data['list'] = $this->right_model->thread_list_all();
$data['test'] = "all";
} else {
$data['list'] = $this->right_model->thread_list_other($session);
$data['test'] = "not all";
}
if ($data['list'] == FALSE)
{
$content = "no hits";
} else {
$content = $this->load->view('right/thread_list', $data, TRUE);
}
$data['content'] = $content;
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
While I create the 'page' dynamically, the HTML outputs to this:
<div name="page" value="1"></div>
Any reason why get_threads() is not running?

This does not have an ID. It has a name.
<div name="page" value="1"></div>
This means that your request for getElementById is failing. So this line of code should be showing a TypeError in your console.
var page = document.getElementById('page').value

Related

Update javascript variables after ajax call

I'm attempting to dynamically update a notice after the cart is updated via ajax. I can't seem to figure out how to re-update all variables so the calculation loop could run again. I tried wrapping the if statement into a function and calling that again inside of updated_wc_div but that didn't work.
Any suggestions?
( function($) {
var membership_price = membership.price;
//grab cart total from html
var total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
compared_price = parseInt(membership_price) - total;
//everything runs fine on load.
if ( total < membership_price ) {
message = 'For <strong>$'+ compared_price +'</strong> more, gain access to unlimited downloads. Become a member!';
notice = '<div class="woocommerce-info">' + message + '</div>';
$('.woocommerce-notices-wrapper').html(notice);
}
//running this to know when ajax is called
$(document.body).on('updated_wc_div',function( event ){
$('.woocommerce-notices-wrapper').empty();
total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
//I believe problem is here, it doesn't update variable so it could loop again.
});
} )(jQuery);
this is how I dynamically update an object after ajax call is being called:
function getCart(user_id) {
$.ajax({
type: "POST",
url: "get_total_cart.php",
data: {
'user_id': <?php echo $user_id; ?>
},
beforeSend: function() {},
success: function(response) {
var user = JSON.parse(response);
var total_cart = parseInt(user.total_cart);
$("#total_cart").html(total_cart);
}
});
}
function addCart(product_id, user_id) {
$.ajax({
type: "POST",
url: "add_cart.php",
data: {
'product_id': product_id,
'user_id': user_id
},
beforeSend: function() {},
success: function(response) {
getCart(user_id);
}
});
}
$(document).ready(function() {
$(".se-pre-con").fadeOut("slow");
getCart(<?php echo $user_id; ?>);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_cart">Total Cart</div>
<input type="button" name="add_cart" id="add_cart" value="Add to Cart" onclick="addCart('<?php echo $product[id]; ?>', '<?php echo $user_id; ?>')" class="btn btn-info">
I hope this helps.
Cheers.
Simply you have to put your function inside the ajax function or make the ajax function "async:false"
$.ajax({
type: "POST",
url: "",
async:false, // <======== remove asynchronous property
data: {},
success: function(result) {
}
});
////////////////////////////////////////////////
$.ajax({
type: "POST",
url: "",
data: {},
success: function(result) {
// Or put your function here
}
});

Javascript on change not working (Ajax to load filtered items)

I am in shopify and trying to Ajax a filter. I have a dropdown and the dropdown onchange should use Ajax to replace the contents of a bunch of products in the #collection div.
My onchange can't find my update products function. What is wrong with my syntax?
<script>
$(function() {
var popped = ('state' in window.history && window.history.state !== null),
initialURL = location.href;
//function to handle the scenarios where back and forward buttons used in browser
$(window).bind("popstate", function(e) {
// Ignore inital popstate that some browsers fire on page load
var initialPop = !popped && location.href == initialURL;
popped = true;
if (initialPop) {
return;
}
ajaxLoadPage(location.href);
});
//the ajax function that does the AJAX calls to get the products and load them into the grid
var ajaxLoadPage = function(url) {
$.ajax({
type: 'GET',
url: url,
data: {},
complete: function(data) {
$('#collection').html($("#collection", data.responseText).html());
history.pushState({
page: url
}, url, url);
}
});
}
}
function update_flavors(ajax_page) {
$.ajax({
type: "GET",
url: ajax_page + "?view=flavors-field",
success: function(html) {
$("#collection").html(html);
}
});
}
function update_products(ajax_page) {
$.ajax({
type: "GET",
url: ajax_page + "?view=products",
data: {},
success: function(html) {
$("#collection").html(html);
history.pushState({
page: ajax_page
}, "", ajax_page);
}
});
}
</script>

Ajax refresh block with templater

i need refresh page after POST ajax submit.
Try this, but not successful
function show()
{
$.ajax({
url: "engine/modules/eshop_cart.php",
cache: false,
success: function(html){
$("#result").html(html);
}
});
}
function addCart(){
var price = $("#price_id").text();
var name = $("#name_id").text();
$.post(
"engine/ajax/eshop_cart.php",
{
price: price,
name: name
},
onAjaxSuccess
);
}
function onAjaxSuccess(data)
{
show();
}
File engine/modules/eshop_cart:
$myip = $_SERVER["REMOTE_ADDR"];
$select = $db->query("SELECT * FROM ".PREFIX."_shop_cart WHERE ip='$myip'");
while($row = $db->get_row($select)){
$tpl->load_template("eshop/cartitems.tpl");
$tpl->set("{r_name}", $row["name"]);
$tpl->set("{r_price}", $row["price"]);
$tpl->set("{r_count}", $row["count"]);
$tpl->compile("cartlist");
$tpl->clear();
}
$tpl->load_template("eshop/cart.tpl");
$tpl->set("{old_cart}", $tpl->result["cartlist"]);
$tpl->compile("cart");
$tpl->clear();
If im use my code, after POST submit block with id = result are null.
in terms of bollean.. Help and sorry for my bad english
Try This ...
function show()
{
$.ajax({
url: "engine/modules/eshop_cart.php",
cache: false,
success: function(html){
$("#result").html(html);
location.reload();
}
});
}

Why Html dialog opening data from cache

I have dilaog box which loads data in success function of an ajax call as follows.
$.ajax({
url: '#Url.Action("GetPolicyPremiumAllocation", "Policy")',
data: { policyID: selPolicyId },
type: 'POST',
success: function (data) {
if (data.length > 0) {
alert(data);
document.getElementById("modal_dialog").innerHTML = "";
// $("#modal_dialog").empty();
$("#modal_dialog").load(data,function( ) {
$("#close-button-id").on("click", CloseDialog);
});
$("#modal_dialog").dialog("open");
}
}
});
First time the div of dilaog is loading correct data.But Second time,it just shows the old data. I have tried to clear cache in the index action of my controller.Unable to figure out how to solve this.Please help.
Set ajax cache option to false:
$.ajax({
url: '#Url.Action("GetPolicyPremiumAllocation", "Policy")',
data: { policyID: selPolicyId },
cache:false,
type: 'POST',
success: function (data) {
if (data.length > 0) {
alert(data);
document.getElementById("modal_dialog").innerHTML = "";
// $("#modal_dialog").empty();
$("#modal_dialog").load(data,function( ) {
$("#close-button-id").on("click", CloseDialog);
});
$("#modal_dialog").dialog("open");
}
}
});
Or decorate your Action with [OutputCache(NoStore = true, Duration = 0)]

How to referesh the DataTable

How to refresh the DataTable after changing in server side
Here i have define the dataTable when isData= 1 at server side mqsql(DB)
function one()
{
var DataTableApp = $('#DataTableApp').dataTable({
"sAjaxSource": "php/getAppDetails.php",
....
....
}
when click the some one in DataTable. I have changed isData=0, It is in ajax calling in another function.
After changing isData=0, I want to referesh the table..
How to referesh the DataTable
$.ajax({
type: "GET",
url: "php/removeApp.php",
data: data,
dataType: "json",
success: function (data) {
json_objApp = data;
if(json_objApp.isSuccessful == true)
{
document.getElementById('removeAppSucc').innerHTML = "Successfully Removed";
document.getElementById('collapseFive').setAttribute("class", "collapse");
DataTableApp.fnDraw();
DataTableApp._fnAjaxUpdate();
}
else
{
document.getElementById('removeAppSucc').innerHTML = "App is not removed"
}
},
});

Categories