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();
}
});
}
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)]
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.
I'm trying to prevent multiple requests when user click on login or register button. This is my code, but it doesn't work. Just the first time works fine, then return false..
$('#do-login').click(function(e) {
e.preventDefault();
if ( $(this).data('requestRunning') ) {
return;
}
$(this).data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
});
Any ideas? Thanks!
The problem is here:
complete: function() {
$(this).data('requestRunning', false);
}
this no longer points to the button.
$('#do-login').click(function(e) {
var me = $(this);
e.preventDefault();
if ( me.data('requestRunning') ) {
return;
}
me.data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
me.data('requestRunning', false);
}
});
});
Use on() and off(), that's what they are there for :
$('#do-login').on('click', login);
function login(e) {
e.preventDefault();
var that = $(this);
that.off('click'); // remove handler
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize()
}).done(function(msg) {
// do stuff
}).always(function() {
that.on('click', login); // add handler back after ajax
});
});
In your ajax callbacks the context (this) changes from the outer function, you can set it to be the same by using the context property in $.ajax
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this, //<-----
success: function(msg) {
//stuffs
},
complete: function() {
$(this).data('requestRunning', false);
}
});
You can disable the button.
$(this).prop('disabled', true);
I have also faced a similar problem.
Just adding $('#do-login').attr("disabled", true); gives me the solution.
$('#do-login').click(function(e) {
e.preventDefault();
$('#do-login').attr("disabled", true);
.........
.........
Here do-login is button id.
I've tried this and worked very fine for me, I was having trouble that $.ajax send more request until results return,
var settings = {
"url": "/php/auth/login.php",
"method": "POST",
"timeout": 0,
"async": false,
"headers": {
"Content-Type": "application/json; charset=utf-8"
},
"data": jsondata, //data pass here is in JSON format
};
$.ajax(settings).done(function (ress) {
try{
console.log(ress, "Result from Ajax here");
}
catch(error){
alert(error);
console.log(ress);
}
});
async : false worked for me.
Thanks.
Or you can do it by $(this).addClass("disabled"); to you button or link and after click is performed, you can $(this).removeClass("disabled");.
// CSS
.disabled{
cursor: not-allowed;
}
// JQUERY
$('#do-login').click(function(e) {
e.preventDefault();
$(this).addClass("disabled");
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
context: this,
success: function(msg) {
//do more here
$(this).removeClass("disabled");
},
});
});
P.S. If you use bootstrap css, you do not need the css part.
I found the approach useful. I've implemented it as a general purpose function for jQuery with ES6.
export default function (button, promise) {
const $button = $(button);
const semaphore = 'requestRunning';
if ($button.data(semaphore)) return null;
$button.data(semaphore, true);
return promise().always(() => {
$button.data(semaphore, false);
});
}
Because $.ajax() returns a promise, you simply pass in the promise and the function takes care of the rest.
Roughly speaking, here's the usage.
import preventDoubleClick from './preventdoubleclick';
...
button.click(() => {
preventDoubleClick(this, () => $.ajax()
.done(() => { console.log("success") }));
});
This function can help you with control multi Ajax requests and it's has timeout function which can return flag status to 0 after ex. 10sec (In case the server took more than 10 seconds to respond)
var Request_Controller = function(Request_Name = '', Reactivate_Timeout = 10000)
{
var a = this;
a.Start_Request = function(){
if(window.Requests == undefined){
window.Requests = {};
}
window.Requests[Request_Name] = {'Status' : 1, 'Time': + new Date()};
}
a.End_Request = function(){
if(window.Requests == undefined){
window.Requests = [];
}
window.Requests[Request_Name] = undefined;
}
a.Is_Request_Running = function(){
if(window.Requests == undefined || window.Requests[Request_Name] == undefined){
return 0;
}else{
var Time = + new Date();
// Reactivate the request flag if server take more than 10 sec to respond
if(window.Requests[Request_Name]['Time'] < (Time - Reactivate_Timeout))
{
return 0;
}else{
return 1
}
}
}
}
To use it:
var Request_Flag = new Request_Controller('Your_Request_Name');
if(!Request_Flag.Is_Request_Running()){
Request_Flag.Start_Request();
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
Request_Flag.End_Request();
}
});
}
for prevent multiple ajax request in whole site. For example: If use ajax request in other ajax page, Using ajax in php loop, etc, Give you multiple ajax request with one result. I have solution:
Use window.onload = function() { ... }
instead of
$(document).ready(function(){ ... });
on the main index.php page. Its will be prevent all multi request. :)
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