Moving data outside of the scope my jQuery AJAX call - javascript

I have a little AJAX function that asks the server whether a particular checkbox should be checked. I'd like to pass the information to a variable outside of the scope of the AJAX function. Something along the lines of:
isChecked = $.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
return = true;
}
else{
return = false;
}
}
})
or
var isChecked;
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
isChecked = true;
}
else{
isChecked = false;
}
}
})
Neither of those works of course. How do I do this?

var isChecked;
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
isChecked = true;
}
else{
isChecked = false;
}
}
});
alert('isChecked');
in this code even if the 'isChecked' property is set properly in the ajax success function the alert will say undefined because the ajax call is Asynchronous. It will raise the alert before the ajax success function returns. Therefore you need to do your work after the ajax success function like this. You can pass the variable to do the work after ajax success.
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
chek(isChecked);//pass the variable here
}
});
function chek(isChecked){
if(isChecked){
$('#YourCheckbox').attr('checked','checked')
}
else{
$('#YourCheckbox').removeAttr('checked')
}
}

I'd recommend creating an object that has an isChecked property. That's safer than using a simple global variable. For example:
var inputObj = {};
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
inputObj.isChecked = true;
}
else{
inputObj.isChecked = false;
}
}
})

Related

How to use javascript variable within another javascript script?

So in an earlier part of my code, within tags I set the value of variable charge to a different link.
How do I use the value of this variable in the later javascript as 'url: charge' does not work. Do I need to write the variable differently.
'Url: chargesilver.php' works, but 'url: charge' doesn't.
<script>
function setmembershipayment(){
if (usermembershipchoice == "Silver") {
var charge = "chargesilver.php";
alert(charge);
} else if (usermembershipchoice == "Gold") {
var charge = "chargegold.php";
alert(charge);
} else if (usermembershipchoice == "Platinum") {
var charge = "chargeplatinum.php";
alert(charge);
} else {
alert("ERROR");
} // THE MISSED BRACKED!! ;)
}
</script>
.
<script>
$.ajax({
type: "POST",
url: charge,
data: form.serialize(),
success: function(response){
</script>
The easiest way is to make your function return the charge you want to use.
function getMembershipPayment(){
if (usermembershipchoice == "Silver") {
return "chargesilver.php";
} else if (usermembershipchoice == "Gold") {
return "chargegold.php";
} else if (usermembershipchoice == "Platinum") {
return "chargeplatinum.php";
} else {
alert("ERROR");
return "some default value"
} // THE MISSED BRACKED!! ;)
}
$.ajax({
type: "POST",
url: getMembershipPayment() // returns the value of charge,
data: form.serialize(),
success: function(response){}
})
Perhaps call the function from url to return the correct string value. And perhaps use a switch instead of an if/else structure as it's a little easier to read.
function setmembershipayment(usermembershipchoice) {
switch (usermembershipchoice) {
case 'Silver': return "chargesilver.php";
case 'Gold': return "chargegold.php";
case 'Platinum': return "chargeplatinum.php";
default: console.log('error'); break;
}
}
$.ajax({
type: "POST",
url: setmembershipayment(usermembershipchoice),
data: form.serialize(),
success: function(response) {
...
}
});
charge is not global.
Its scope is just within the function
Declare it outside the function
var charge = ''
function setmembershipayment(){
....
Sample
<script>
var charge = ''
function setmembershipayment(){
if (usermembershipchoice == "Silver") {
charge = "chargesilver.php";
alert(charge);
} else if (usermembershipchoice == "Gold") {
charge = "chargegold.php";
alert(charge);
} else if (usermembershipchoice == "Platinum") {
charge = "chargeplatinum.php";
alert(charge);
} else {
alert("ERROR");
} // THE MISSED BRACKED!! ;)
}
setmembershipayment()
$.ajax({
type: "POST",
url: charge, // OR Just return it from the function here and make sure there is a default value
data: form.serialize(),
success: function(response){
</script>
OR Just return it from the function and make sure there is a default value

Using "Bind" for simple ajax up/down vote function

I have a simple ajax up/down vote function.
I would like to rebind this "voteClickEvent" on success of ajax call for the opposite vote. Must I put this in a seperate function in the success call? Or can I do this more elegantly?
var voteClickEvent = function() {
var upOrDown = $(this).attr('id');
var that = $(this);
$.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {upOrDown: upOrDown, action: "updateVote"},
dataType: "json",
success: function(data) {
console.log(data.output);
that.unbind("click");
that.css("cursor", "default");
if (data.output == "up") {
$("#down").bind("click", voteClickEvent);
} else {
$("#up").bind("click", voteClickEvent);
}
}
});
return false;
}
$("#up, #down").bind("click", voteClickEvent);

Call js function only once in javascript

I created js function and now i want that js function to call itself only once, My code is
function view(str){
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/'+str+'/',
success: function(output_string){
//i want to call function from here only once like view(str);
}
});
}
.
How can i do that ? Thanks in advance, Currently it is showing me infinte loop.
Use a flag variable
var myflag = false;
function view(str) {
$.ajax({
type : "POST",
url : '<?php echo base_url()?>index.php/main/' + str + '/',
success : function(output_string) {
if (!myflag) {
view(str);
}
myflag = true;
}
});
}
Try adding a parameter to the function that keeps track of the count:
function view(str, count) {
if (count > 0) {
return;
}
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/'+str+'/',
success: function(output_string) {
view(count + 1);
// i want to call function from here only once like view(str);
}
});
}
Then you would initially call view like this:
view(str, 0);
you are looking for jquery one.
http://api.jquery.com/one/
fiddle http://jsfiddle.net/XKYeg/6/
<a href='#' id='lnk'>test</a>
$('#lnk').one('click', function view(str) {
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/' + str + '/',
success: function (output_string) {
i want to call
function from here only once like view(str);
}
});
});
You can pass a bool as a parameter on whether the function should call itself again:
function view(str, shouldCallSelf){
$.ajax({
type: "POST",
url: '<?php echo base_url()?>index.php/main/'+str+'/',
success: function(output_string){
if (shouldCallSelf)
view(output_string, false)
}
});
}
You should call it with true the first time. It will then call itself with false the second time, will not execute again.

Javascript when to show results

This is my Javascript below I want to show records on load and also show new records when added to the database
showrecords(); displays the records in the database where abouts can I put this in my code where it will work correctly.
$(document).ready(function()
{
//showrecords()
function showrecords()
{
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
}
});
}
$(".comment_button").click(function() {
var element = $(this);
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
// $("#display").after(html);
document.getElementById('content').value='';
$("#flash").hide();
//Function for showing records
//showrecords();
}
});
}
return false;
});
});
Though polluting the global namespace is not recommended. Here is what I would recommend for your code. Move the showRecords() out of Document ready function and refactor the update ajax code to another function 'updateRecords()'. Have only the event bindings inside the document ready function.
You could return the entire comments as response to POST 'demo_insert.php' service and call 'showRecords()' in the update service success callback.
i've pasted below (untested) code that i think should get the job done. in order to call functions you've got to define them in an accessible area, whether in the "global" (can be called from anywhere) namespace as i've done below, or as part of an another object.
you also need to make sure your functions are defined before you try to call them, as everything works in a top down manner.
function showrecords() {
$.ajax({
type: "POST",
url: "demo_show.php",
cache: false,
success: function (html) {
$("#display").after(html);
$('content').val('');
$("#flash").hide();
}
});
}
function addComment() {
var test = $("#content").val();
var dataString = 'content=' + test;
if (test == '') {
alert("Please Enter Some Text");
}
else {
$("#flash").show();
$("#flash").fadeIn(400)
.html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function (html) {
//$("#display").after(html);
$('content').val('');
$("#flash").hide();
//Function for showing records
showrecords();
}
});
}
}
$(document).ready(function () {
showrecords()
$(".comment_button").click(function () {
addComment();
return false;
});
});

Ajax : only call the ajax if element existing

for example i have a .ajax() function like below:
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
It works fine,but i'd like to add a if statement to detect whether the $(".numberOfProfile0").html() exist or not, and will only execute when the $(".numberOfProfile0").html()exist
I tried below but it doesn't seem right
if ($(".numberOfProfile0").length) {
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
- UPDATE:
Let's show the whole application
This is the function:
if($(".numberOfProfile0").html().length){
function trend1() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
$.when(trend1()).done(function(trend1_data) {
//do something
}
Please remember jQuery selector is not a string. Using jQuery, the correct way to do this is something like $('.selector').val().length , $('.selector').html().length
Use $(".numberOfProfile0").html().length > 0 in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="numberOfProfile0">lorem</div>
<script>
if ( $(".numberOfProfile0").html().length > 0 ) {
alert("success");
// your function:
//function trend() {
//return $.ajax({
// url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + //$(".numberOfProfile0").html(), //getting the api
// type: 'get',
//success: function(data) {
//}
// });
// }
}
</script>
I think it should be
function trend() {
if ( $(".numberOfProfile0").length ) {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}//if()
else
{
return false; //or any other appropriate value
}
}//trend()
use ($(".numberOfProfile0").html() !== '') that mean if element with class .numberOfProfile0 is not empty
function trend() {
if ($(".numberOfProfile0").html().trim() !== '') {
$.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
}
You are doing it wrong! You are defining the function inside the if, where as you should be calling it inside if.
First define the function.
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
Then call it.
if ($(".numberOfProfile0").length) {
trend();
}
OR
You can put the if check inside the function.
function trend() {
if ($(".numberOfProfile0").length) {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(), //getting the api
type: 'get',
success: function(data) {
}
});
}
else{
return -1;
}
}
You can use .is() within $.when() at ternary to return trend() if element exists, else return null to $.when(); handle element not existing in DOM. Note, you can remove success option at $.ajax() if response is handled at .done()
function trend() {
return $.ajax({
url: "/dashboard/getTrend'"
+ "?period=30d"
+ "&profileId="
+ $(".numberOfProfile0").html(), //getting the api
type: "get"
});
}
$.when($(".numberOfProfile0").is("*") ? trend() : null)
.done(function(trend1_data) {
if (trend1_data === null) {
// handle `$(".numberOfProfile0")` not existing in `DOM`
} else {
// handle `trend1_data` not being `null`, element exists
// do something
}
})
You should check the existence of the element inside the before_send callback for aJax and cancel the aJax request if not.
function trend() {
return $.ajax({
url: '/dashboard/getTrend' + '?period=30d' + "&profileId=" + $(".numberOfProfile0").html(),
type: 'get',
before_send: : function( xhr ) {
if ($(".numberOfProfile0").length > 0 && $(".numberOfProfile0").html().trim() == ''){
return false;
}
}
success: function(data) {
}
});
}
The above code snippet should work in your case.

Categories

Resources