Sorry for the title but I had no idea how to call it.
I got some ajax call function that on success adds some HTML elements to the page:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
},
complete: complete()
});
};
Function does something on success where the most important is the .append and then this ajax function is called in some button .click function like this:
$(function() {
$("#product_list_add_btn").click(function(e){
ajax_submit_append(
form_data = {
product_name: $('.selectpicker option:selected').val(),
amount: $('#amount').val()},
"<?php echo site_url('admin_panel/new_order/add_product'); ?>",
'#add_product_result',
calculateSum
);
return false;
});
});
What I want to achieve is that calculateSum function (sums table columns) is called after .append is done via ajax.
For now, when I add calculateSum to ajax complete event it is still called before new row is added to the table with .append
Edit: I present You calculateSum, but I believe there is nothing faulty there.
function calculateSum() {
var sum = 0;
// iterate through each td based on class and add the values
$(".countit").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
$('#total_price').text(sum);
alert("test");
};
If I had to guess, I would say its something with click event?
How to fix this?
Try using jqXHR's done() method:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
}
}).done(complete);
};
Related
i am creating two ajax functions one in the traditional method and one with jquery. but when i do this the traditional method gets called first and in return i dont get some of my desired outcomes. how can i make the traditional ajax method to be translated into jquery?
here is my traditional ajax method:
function countFollowers() {
var xmlHttp = GetXmlHttpObject();
var url = "checkFollowers.php?username=" + document.followForm.follow_id.value;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var r = xmlHttp.responseText.trim();
if (r != "error") {
document.getElementById('followersCount').innerHTML = xmlHttp.responseText;
error = true;
return false;
}
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
if (error == true) {
return false;
}
}
here is my jquery ajax:
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow=" + follow_id,
success: function(data) {
}
});
});
});
here is what i come up with so far to make the two ajax functions in the same on click function:
jQuery(document).ready(function($){
$('.msg-icon').on('click', function(e){
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow="+follow_id,
success: function(data) {
}
});
$.ajax({
data: follow_id,
type: "post",
url: "checkFollowers.php?username="+follow_id,
success: function(data) {
}
});
});
});
but it is still not executing the response text that is coming from my php file
php code:
<?php
include("functions.php");
include("session.php");
require("connection.php");
if(isset($_GET['username'])){
$username =$_GET['username'];
$result= $db->prepare("SELECT * FROM users WHERE username=?");
$result->bindValue(1,$username);
$result->execute();
$row = $result->fetch();
if($result){
echo "Followers </br>". $row["followers_count"];
}
else{
echo "error";
}
}
?>
how will i get it to echo the $row["followers_count"] inside my span element?
You said in the comments you wanted to run the two requests sequentially instead of in parallel. Here's an all-round better way to organise your code which both allows that, and makes the code more re-usable, more maintainable and testable, and easier to understand in general.
I've used the Promise/Deferred interface provided by jQuery and AJAX as the way to chain the requests in sequence. Notice how each call is separated into each own function (so it's re-usable), but that function returns the Deferred object from the AJAX request, so you can use it to do something else when the request finishes.
Also based on your PHP I think the call to checkfollowers needs to be a GET (because PHP checks $_GET for the input value, and that's what your original XHR call was), and also you need to set the data with an explicit "username" parameter name so it'll be recognised.
It's not clear whether your call to followingsystem.php is correct or not because I can't see the PHP code for it.
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
var request = follow(follow_id); //run the initial request, get back the Deferred object representing that request.
request.done(function() { //when the first request is done, run the second one.
checkFollowers(follow_id);
});
});
});
function follow(follow_id) {
return $.ajax({
data: { follow: follow_id},
type: "post",
url: "followingsystem.php?follow=" + follow_id
});
}
function checkFollowers(follow_id) {
return $.ajax({
data: { username: follow_id },
type: "get",
url: "checkFollowers.php",
success: function(data) {
document.getElementById('followersCount').innerHTML = data;
}
});
}
Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.
I have an issue with calling ajax request with jquery.
The order that I'm doing this in is:
click the button
do ajax post
when the ajax request is finished I call a function that is out side the scope.
For some reason and supecting that it has to do with the fact that i am in the on click callback that the load function is out of scope. But I don't even see the console.log message either. But I do see the ajax call.
Any ideas? Maybe I'm doing this the wrong way???
Here's the prototype code that resembles what I'm trying to do:
$(document).ready(function(){
$('#button').on('click',function(evt){
var data = {};
ajax('index.html', data).done(function(){
console.log('Fire Please'); // this does not fire after the ajax call!!!
load(); // this does not fire after the ajax call!!!
});
});
function load(){
// do another ajax call and add to the dom
}
function ajax(url, data){
return $.ajax({
url: url,
type: 'post',
dataType: 'json',
data: data
});
}
});
And Here's the Actual Code I'm trying to use
$(document).ready(function(){
// add onclick event to the Add Unit Button
addUnitButt.on('click', function(evt){
var data = {
id: id,
dept_no: dept_no.val(),
dept: dept.val()
};
evt.preventDefault();
dept.val('');
dept_no.val('');
$(this).prop('disabled', true);
ajax('index.html', data).done(function(){
load();
});
});
function load(){
var data = {
id: 575
};
// show loading
showLoading();
// reset the table dom
$("#listTable").find("tr:gt(0)").remove();
// do initial load of the list data
ajax('index.html', data)
.done(function(units){
var data = toJSONObject(units);
for(var x = 0; x < data.length; x++){
if((x & 1) == 0){
addRow(data[x], data.length, 'odd');
}else{
addRow(data[x], data.length, 'even');
}
}
// hide loading
hideLoading();
});
}
// ajax function to call for data
function ajax(url, data){
return $.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: url
});
}
});
Thanks in advance!
Maybe the code of your index.html is not valid JSON
.always() must be called.
Make sure your server response have the right headers like Content-Type. And the response body is valid JSON.
I want to display Updated records count when Ajax process is going on. When i click on start process button updateRecords()function will execute and it will update records status from open to waiting status one by one in database.So at the same time i want display the waiting records count .For this when user click on strat process button i want to call displayWaitingRecords() using setinterval.
I am calling that function like this from updateRecords()
clear_Process = setInterval(function(){displayWaitingRecords()},200);
But displayWaitingRecords() will not call until updateRecords() process completes.But my requirement is displayWaitingRecords() also will execute simaltaniously with updateRecords().
Function to display updated record count
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
async: false,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}
Function when i click on start process button
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: false,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
Where i am doing wrong? Any help would be greatly appreciated.
You have set async: false. So the ajax call will process synchronized. Set it to false or leave it out (because true is default):
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: true,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
If you leave it out you have the same result:
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}
For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});