Ajax refresh block with templater - javascript

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();
}
});
}

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
}
});

filtration and pagination using ajax call in jquery

I want to do filtration and pagination in one script. I have done filtration and pagination separately. But when I combine this two code snippet pagination is not working. Here I give my code which I have done.
function getusedcarFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
function updateusedcar(opts){
$.ajax({
type: "POST",
url: "filter.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(data){
$('#usedcar1').html(makeTable(data));
displayRecords();
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getusedcarFilterOptions();
updateusedcar(opts);
});
updateusedcar();
// fetching records
function displayRecords(numRecords, pageNum) {
$.ajax({
type: "GET",
url: "getrecords.php",
data: "show=" + numRecords + "&pagenum=" + pageNum,
cache: false,
beforeSend: function() {
$('.loader').html('<img src="loader.gif" alt="" width="24" height="24" style="padding-left: 400px; margin-top:10px;" >');
},
success: function(html) {
$("#usedcar1").html(makeTable(data));
$('.loader').html('');
}
});
}
// used when user change row limit
function changeDisplayRowCount(numRecords) {
displayRecords(numRecords, 1);
}
$(document).ready(function() {
displayRecords(10, 1);
});
</script>
thanks in advance.
You should combine the codes on server side, otherwise the filtered record are not paginated and vice-versa. Otherwise you need to do the pagination on client side but I suppose it would eliminate the main reason of the pagination.

Jquery AJAX with codeigniter, always returns error

I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.

Ajax call not succeeding after function call

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

jquery ajax call execute once function after complete

I am in mobile app. I use ajax calls to receive data from webserver with this code:
$.ajax({
url: 'http://www.xxxxxxxxxxxx',
data: {name: 'Chad'},
dataType: 'jsonp',
success: function(data){
$.each(data.posts, function(i,post){
$.mobile.notesdb.transaction(function(t) {
t.executeSql('INSERT into bill (barcode, buildingcode, buildingaddress, flatname, flatdescription, entryseason, period, amount, pastpayments, todaypayments, receiptno) VALUES (?,?,?,?,?,?,?,?,?,?,?);',
[post.Id, post.Code, post.Address, post.Name, post.Description, post.EntrySeason, post.Period, post.Revenue, post.PastPayments, post.todaypayments, post.receiptno],
function(){
bill = 1;
$('#mycontent').append("bill - OK");
}
);
});
});
}
});
I want bill - OK displayed only once after all data inserted into sqlite.
try this:
success: function(data){
var count = data.posts.length;
$.each(data.posts, function(i,post){
$.mobile.notesdb.transaction(function(t) {
t.executeSql(<...>,
function() {
bill = 1;
if (--count == 0) {
$('#mycontent').append("bill - OK");
}
}
);
});
});
}
try to add:
$.ajax({
url: 'http://www.xxxxxxxxxxxx',
data: {name: 'Chad'},
dataType: 'jsonp',
async: false, //this line here
//...
EDIT
OK, what about:
$.each(data.posts, function(i,post){
//rest of stuff
});
$('#mycontent').append("bill - OK"); //this line outside the each() call

Categories