Ajax continuous pull from database - javascript

I have literally just started programing with Ajax and cant get this to work.
Here is what I have so far:
var oldAction = '';
function updateCheck() {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
if (data.length == '4') {
playSong();
} else {
pauseSong();
}
}
oldAction = data.length;
}
});
}
setInterval('updateCheck();', 1000);
Does anyone know why this would not be working?
Thanks

Sure. length() is looking for an integer, but you are comparing it to a string.
If oldAction really needs to be a string, then you need to do something like this:
if (data.length != Number(oldAction)) {
if (data.length == 4) {
playSong();
} else {
pauseSong();
}
};

try this:
function updateCheck() {
var
oldAction = 0,
callAjax = function () {
$.ajax({
url: 'check_status.php',
success: function (data) {
if (data.length != oldAction) {
(data.length == 4) ? playSong() : pauseSong();
}
oldAction = data.length;
}
});
};
setInterval(callAjax, 1000);
}
updateCheck();
​

Related

rerturning response of an ajax post

i am trying to check if an email exists in the db but the function doesn't return a value.
This is the code:
function checkemail(email)
{
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1)
{
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});
}
else
{
returnVal = 3;
}//email
return returnVal;
}
EDIT: email is send as a string
I short, You can not return values from ajax calls as it is asynchronous by nature, the statement return value executes before
To address such cases, use callback, a function accepted as argument and which is executed when response is been received (when asynchronous action is completed).
Try this:
function checkemail(email, callback) {
var returnVal = "";
if (email.indexOf("#") != -1 && email.indexOf(".") != -1) {
$.post("registreren.php?email=" + email, function(response) {
callback(response);
});
} else {
callback(3);
}
}
checkemail('abc#xyz.com', function(val) {
alert(val);
});
checkemail('INVALID_EMAIL', function(val) {
alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Can you use something simple like below
$.ajax({
url: 'registreren.php',
type: 'post',
dataType: "json",
data: {'email': email},
success: function (response) {
if (response == 1)
{
returnVal = 1;
}
else
{
returnVal = 3;
}
}
});
instead of
$.post( "registreren.php?email=" + email, function( response ) {
if(response == 1) { returnVal = 1; }
if(response == 2) { returnVal = 2; }
});

Javascript does user exists, returning value from ajax to late?

I have a script that tells a visitor if the username is already exist or not before he can proceed,
Below you see a part of my code;
EDIT: Ok I have read what you guys said, and modified it, but I still dont get it to work :S, my teacher doesn't know it either...
<script type="text/javascript">
jQuery(document).ready(function(){
// Smart Wizard
jQuery('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep(){
validateSteps(function (next) { return next; });
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname, callback)
{
    var data = 'user='+ fullname;
    if(fullname) {
        $.ajax({
            type: "POST",
            url: "user_check.php",
            data: data,
async: false,
            beforeSend: function(html) {
                $("#msg_lastname").html('');
            },
            success: function(html){
                $("#msg_lastname").show();
                 $("#msg_lastname").append(html);
if(html.search("red") != -1)
{
callback(false);
}
else
{
callback(true);
}
            }
        });
}
}
function validateSteps(callback){
var isStepValid = true;
// validate step 1
var firstname = $('#firstname').val();
if(!firstname || (firstname.length < 3 || firstname.length > 10))
{
$('#msg_firstname').html('<br/><font color="red">Enter a first name, between 3 and 10 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_firstname').html('').hide();
}
var lastname = $('#lastname').val();
if(!lastname || (lastname.length < 3 || lastname.length > 14))
{
$('#msg_lastname').html('<br/><font color="red">Enter a last name, between 3 and 14 letters.</font>').show();
isStepValid = false;
}
else
{
$('#msg_lastname').html('').hide();
}
var gender = $('#gender').val();
if(!gender || Number(gender) == -1)
{
$('#msg_gender').html('<br/><font color="red">Choose your gender!</font>').show();
isStepValid = false;
}
else
{
$('#msg_gender').html('').hide();
}
var age = $('#age').val();
if(!age || Number(age) > 90 || Number(age) < 21)
{
$('#msg_age').html('<br/><font color="red">Enter a age between 21 and 90.</font>').show();
isStepValid = false;
}
else
{
$('#msg_age').html('').hide();
}
var pin = $('#pin').val();
if(!pin || pin.length > 10 || pin.length < 4)
{
$('#msg_pin').html('<br/><font color="red">Enter a PIN between 4 and 10 numbers.</font>').show();
isStepValid = false;
}
else
{
$('#msg_pin').html('').hide();
}
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
callback( exists );
});
} else {
callback( false );
}
}
jQuery('select, input:checkbox').uniform();
});
</script>
Now the problem is that when I run this script, it returns undefined, I guess because the UsernameExist is not done fast enough, and it seems the return UsernameExist is not waiting for it for some reason...
You are returning UsernameExists before it has been run.
Instead, call UsernameExists like this:
if (isStepValid) {
UsernameExist(firstname + ' ' + lastname, function (exists) {
return exists;
});
} else {
return false;
}
This works because UsernameExists expects a callback function and on success passes either true or false to callback().
you need just to set async option as false
function UsernameExist(fullname, callback) {
var data = 'user=' + fullname;
if (fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function (html) {
$("#msg_lastname").html('');
},
success: function (html) {
//your code after success
}
});
}
}
from jQuery documentation jQuery.ajax
If you need synchronous requests, set this option to false
so you need to execute your ajax call and wait until it's completely finish to execute what you want based on the result
Maybe you should call UsernameExist(fullname, callback) after jQuery load complete.
try this :
getScript('http://code.jquery.com/jquery-1.9.1.min.js', function () {UsernameExist(fullname, callback)});
function getScript(url, callback) {
var script;
script = document.createElement("script");
script.setAttribute('language', 'javascript');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', url);
var done = false;
vObj = script.onload;
script.onload = script.onreadystatechange = function () {
if (!done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
if (typeof callback === 'function')
callback(this.ownerDocument.attributes);
}
};
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);}
Try something like this :
// Smart Wizard
$('#wizard').smartWizard({onFinish: onFinishCallback, onLeaveStep: onNextStep});
function onNextStep() {
var isValid = validateSteps();
alert(isValid);
}
function onFinishCallback(){
alert('Finish Clicked');
}
function UsernameExist(fullname)
{
var data = 'user='+ fullname;
var userAlreadyExists = null;
if(fullname) {
$.ajax({
type: "POST",
url: "user_check.php",
data: data,
async: false,
beforeSend: function(html) {
$("#msg_lastname").html('');
},
success: function(html){
$("#msg_lastname").show();
$("#msg_lastname").append(html);
if(html.search("red") != -1)
{
userAlreadyExists = false;
}
else
{
userAlreadyExists = true;
}
}
});
}
return userAlreadyExists;
}
function validateSteps(){
...
if (isStepValid) {
return UsernameExist(firstname + ' ' + lastname);
} else {
return false;
}
}

confirm box from a controller

Have a requirement to call the confirm box in JSP, following is my code in controller,
if(!(nesting)){
bla.add("Do you want to Load anyway?");
context.getFlowScope().put("bla", bla);
context.getFlowScope().put("uldSelector", uldSelector);
return;
}
h = uloService.processDomBatch(histInfo, dl, items);
the above will add the error to flowscope and returns, but, I wantto call a confirm box instead and then depending yes/no, I should continue through...
is there a way to do this?..any help is greatly appreciated!
Thank you!
Yes #user1609085 you can do it with AJAX and JavaScript something like this:
function question(val) {
var chk = document.forms[0].chk
var box = valBox(chk)
var resp = confirm("Do you want to Load anyway?")
if(resp) {
if(box == null) { return }
else {
$.ajax({
type: 'GET',
url: 'controllerMethod?action=controllerMethod',
data: 'uldSelector='+val,
cache: false,
success: function(data) {
alert("histInfo")
},
error: function(data) {
alert('ERROR: ' + data)
}
})
}
}
}
function valBox(b) {
var cnt = -1
for(var i = b.length-1; i > -1; i--) {
if(b[i].checked) {
cnt = i
i = -1
}
}
if(cnt > -1) return b[cnt].value
else return null
}
And you box only put onclick="question(this.value)"
I hope help you :)

how to start click or change function from inside js

The problem is, $('#menu').val(menu).trigger('change'); and $('.parentcheck').val(0).attr('checked', true).trigger('click'); changes their state but doesn't fire their functions $("#menu").change(function () { and $(".parentcheck").click(function () {. How to deal with that problem?
My js code looks like that
$(document).ready(function () {
$("#parent").hide();
$(".parentcheck").click(function () {
if ($(this).val() === "0") {
$("#parent").hide().find('option:selected').removeAttr('selected');
}
if ($(this).val() === "1") {
if ($("#parent option").length > 0) {
$("#parent").show();
}
}
$("#menu").change();
});
$("#menu").change(function () {
var selectedmenu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
if (selectedmenu != '' && selectedmenu != '0') {
$.ajax({
type: "POST",
url: "processor/optionsgenerator.php",
data: {
menu: selectedmenu
},
success: function (result, status, xResponse) {
if (result != '') {
if (parentcheck == '0' || !$(".parentcheck").is(":checked")) {
$("#parent").hide();
} else {
$("#parent").html(result);
$("#parent").show();
}
} else {
alert('Baza ilə əlaqədə problem var.');
$("#parent").hide();
}
},
error: function (e) {
alert(e);
}
});
} else $("#parent").hide();
});
$('#menu').val(menu).trigger('change');
if(parent==0) {
$('.parentcheck').val(0).attr('checked',true).trigger('click');
}
else {
$('.parentcheck').val(1).attr('checked',true).trigger('click');
$('#parent').val(parent);
}
});
You are triggering the change before you've defined the change handler. Move your triggers to the end of your code block and it'll work fine.

how should i delay the ajax request?

like this jquery code, how should i delay the ajax request? input is a text field...over my head ....thx for help...
var proname = "" ;
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}) ;
You want to use setTimeout.
From your usage, it seems to be a good idea to have a timeout that is being cleared every time another keyup event occurs, to avoid a queue.
var requestDelay;
var proname;
$('input[name=proname]').keyup(function() {
if(e.which == 13 || $(this).val() == proname)
return;
proname = $(this).val();
// postpone the submit another 300 ms upon every new character
window.clearTimeout(requestDelay);
requestDelay = window.setTimeout(function() {
$.ajax(...);
}, 300);
});
I see you are doing some kind of autosearch/autocomplete feature.
Have you considered just using the jQuery UI Autocomplete? http://jqueryui.com/demos/autocomplete/#remote-jsonp
As for the question itself you have already been answered.
Use setTimeout.
var proname = "" ;
$("input[name='proname']").keyup(function(e){
if (e.which == 13) return;
setTimeout(function() {
if ($(this).val() != proname) {
proname = $(this).val();
} else {
return;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
});
}, DELAY_IN_MSECS);
});
$("input[name='proname']").keyup(function(e){
//how should i delay this function on here ?
if (e.which == 13) return ;
setTimeout(function() {
if ($(this).val() != proname)
{
proname = $(this).val() ;
}
else
{
return ;
}
$.ajax({
type: "post",
data: "proname="+proname+"&page=1",
url: "/project/searchrate",
success: function(view){
alert(view) ;
}
}) ;
}, 1000);
}) ;

Categories