Call js function only once in javascript - 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.

Related

my ajax post method works but i can not catch the value by php

post method , it can post value, my success alert is working but i can not echo in my php. i tried to send to same page and another page. Both they haven't work. Here is my ajax code :
<script>$( "#il" ).change(function() {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: { aa1 : 'mynameis'},
success: function () {
alert($("#il").val());
},
});
});
</script>
and here is my php code to catch :
<?php
$aa = $_POST['aa1'];
if($aa != ""){
echo $aa;
} else { echo "puuf";}
?>
In order to catch the data returned from the PHP echo you need to add a parameter to the success method for javascript to place the value in for you to then make use of
<script>
$( "#il" ).change(function() {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: { aa1 : 'mynameis'},
success: function (data) {
// - - - - - - - - ^^^^
alert($("#il").val(data));
// - - - - - - - - - ^^^^
}
});
});
</script>
You'll have to define a data parameter on the success callback, because the echoed data have to be passed as argument to it. So,
The client script:
<script type="text/javascript">
$("#il").change(function () {
var aa = $("#il").val();
$.ajax({
url: 'never.php',
type: 'POST',
data: {
aa1: 'mynameis'
},
success: function (data) {
alert(data);
},
});
});
</script>
And the PHP:
<?php
$aa = $_POST['aa1'];
if (isset($aa) && !empty($aa)) {
echo $aa;
} else {
echo "puuf";
}
?>

How to stop setInterval in a do while loop in jquery

I want to do is stop setInterval after the do while loop meet the condition.
My problem is even the while loop condition is meet the setInterval is still running.
do
{
setInterval(
Vinformation();
,500);
}while($('#emailCodeResult').val() !='')
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"JSON",
success: function (result) {
}
});
return false;
}
You don't need while loop here at all. In combination with setInterval it doesn't make sense. What you need is probably just setInterval:
var interval = setInterval(Vinformation, 500);
function Vinformation() {
if ($('#emailCodeResult').val() == '') {
clearInterval(interval);
return;
}
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType: "JSON",
success: function (result) {
}
});
}
Use clearInterval function to stop interval.
Also note, that setInterval expects function reference as the first argument so this setInterval(Vinformation(), 500) is not correct, because you immediately invoke the Vinformation function.
var itvl1= window.setInterval(function(){
Vinformation();
},500);
function Vinformation(){
var data = {};
data.emailCodeResult = $('#emailCodeResult').val();
if(data.emailCodeResult !=''){
window.clearInterval(itvl1);
};
$.ajax({
type: "POST",
url: "Oppa.php",
data: data,
cache: false,
dataType:"Jenter code hereSON",
success: function (result) {
}
});
return false;
}

Javascript status loop

Ok, simple thing in javascript that I could not solve even searching on the web. I guess I even found the right thing but could not put on the right place.
This code tells me if a stream is online or offline. But how do I do to the status and keep updating every 5 seconds?
$(function () {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else {
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
});
Example :
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
var ResInterval = window.setInterval(myAjaxCall, 60000); // 60 seconds
To Stop:
window.clearInterval(ResInterval);
use set time out function
setTimeout(function(){
//your function
foo();
},1000);
Try this out:
function checkStatus() {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else{
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
}
$(function() {
setInterval(checkStatus, 5000);
});
This calls the function checkStatus every 5000 milliseconds (5 seconds).

cant pass the value from data using ajax

this is very frustrating, 2 hours passed and still can't get it working.
I just want to test on how to pass a value to my method using ajax.
Code:
Javascript
$('#form-payment').submit(function () {
var request = $.ajax({
url: "<?php echo site_url(array('home', 'update_credit_card')); ?>",
type: "POST",
data: 'someNumber=12'
});
request.done(function(data) {
console.log('boom' + data);
});
request.fail(function(jqXHR, textStatus) {
console.log('error' + textStatus);
//print_r(jqXHR);
});
});
PHP
function update_credit_card()
{
var_dump($_POST['someNumber']);//returns NULL value
$somenumber = $_POST['someNumber'];
if ($somenumber == '12') {
print "Number is 12";
} else {
print "Number is not 12";
}
}
The code is very simple but for the life of me can't get it to work. T_T.
Badly need help.
You can also use like this.
var values={};
values['arg1'] = 1;
values['arg2'] = 2;
$.ajax({
type:'POST',
url:'....',
data: values,
success:function(){}
});

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

Categories

Resources