How can I pass a function variable in jquery? - javascript

This is my html form I am using.
<label>Your Username:</label><input id="username" name="username" type="text" onchange="return ajax ('username');" />
This is my ajax checking file in php.
if ($_REQUEST['username']) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
And my jquery ajax request...
function ajax (input) {
var val = $('#'+input).val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: val,
},
function (response) {
$('.error, .success').hide();
setTimeout(function(){
$('.loading').hide();
finishAjax(input, response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#'+id).after(response).fadeIn(2000);
}
On my form I call the ajax request with the variable username.
In my ajax.php the correct validation of the username takes place if the request is named username.
I would like to display the variable input in place of username in the jquery code so I can use this script for other validations and pass the variable as email, or password and the script will still run as the value of input will be what it needs to be.
If that makes sense.
Thanks for your time.

var data = {};
data[input] = $('#' + input).val();
$.post("ajax.php", data, function() {...
and
finishAjax(input, response);

check input arg wat ll u get then proceed.....
remove semicolon near to
{username: $('#' + input).val(),}
as ,{ username: $('#' + input).val()},
u ll get o/p

You're declaring val to be the value of "input", but never using it. All the usages of username should have access to that variable val, so use it. Unless I'm misunderstanding your question, something like this (only changed one line):
function ajax(input) {
var val = $('#' + input).val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: val,
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}

Before you call $.post create an empty object.
var data = {};
Use the parameter of the function as the index for the object.
data[input] = val;
In your $.post call use that object instead of the anonymous object literal.
$.post("ajax.php", data, function ...);
If you do things the way you're describing, though, you need to make sure you manage all these parameters you pass in properly. Are you sure that your PHP script is able to handle all the different possible values you may pass into the ajax function?

Related

How to restart recursive function in JS using setTimeout and clearTimeout?

I am trying to build simple chat module in CodeIgniter.
var last_id = 1;
$(document).ready(function(){
loadMsgs();
$("#content").focus();
$("form#chatform").submit(function(){
$.post("<?php echo base_url() ?>index.php/msg/update",{
message: $("#content").val(),
con_id: <?php echo $con['conversation_id'] ?>
}, function(){
$("#content").val("");
$("#content").focus();
loadMsgs();
});
return false;
});
});
function loadMsgs() {
$.getJSON('<?php echo base_url() ?>index.php/msg/backend/<?php echo $con['conversation_id'] ?>/' + last_id, function(json) {
$.each(json, function(i,val){
//console.log(val.id);
if(<?php echo $login_id ?> == val.sender_id){
$("#messagewindow").append('<div class="bubble"><p>' + val.msg + '</p></div>');
} else {
$("#messagewindow").append('<div class="bubble bubble-right"><p>' + val.msg + '</p></div>');
}
});
updateScroll();
var newIndex = json.length-1;
if(typeof(json[newIndex]) != 'undefined'){
last_id = json[newIndex].msg_id;
}
setTimeout('loadMsgs()', 4000);
});
}
function updateScroll(){
var element = document.getElementById("messagewindow");
element.scrollTop = element.scrollHeight;
}
I have function loadMsgs that use $.getJSON to call for controller that grabs last messages from database and then append them to #messagewindow. Last thing in callback is setTimeout so hat is updated every 4 seconds.
On submit action I post new message to controller and in callback call loadMsgs again. As a result of that every time I submit new message additional call is added which is not good.
I tried to clearTimeout adding global variable id, changed var id = setTimeout('loadMsgs()', 4000); and added clearTimeout(id); before calling loadMsgs again after submiting another message. However nothing changes.
If you have a global variable id, and then in your handler you're calling
var id = setTimeout('loadMsgs()', 4000);
you're never touching the global id.
By having var again in your handler, you're defining another (and another...) copy of id, setting a timeout on each. Var defines a NEW variable, and it looks like you're doing that repeatedly. Take out the var in the handler:
clearTimeout(id);
id = setTimeout('loadMsgs()', 4000);
A simple way to solve this, is to pass an argument to loadMsgs when you call it upon submit. Then you test the presence of this argument. If it is present, don't call setTimeout:
$("form#chatform").submit(function(){
// ...
loadMsgs(1);
// ...
});
function loadMsgs(submitting) {
// ...
if (!submitting) setTimeout(loadMsgs, 4000);
// ...
}
What happens if you remove loadMsgs() from the submit action and leave it up to the 4 second JSON to auto-populate the new message?
Maybe use JS to create a dummy container of a new message from the submit but then clear that dummy element when new JSON is captured?

Delete function not working properly - Ajax

I have a pm system and I would like for all checked messages to be deleted. So far, it only deletes one at a time and never the one selected. Instead it deletes the one with the youngest id value. I'm new to ajax and all help is appreciated.
Here's my function:
function deletePm(pmid,wrapperid,originator){
var conf = confirm(originator+"Press OK to confirm deletion of this message and its replies");
if(conf != true){
return false;
}
var ajax = ajaxObj("POST", "php_parsers/pm_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "delete_ok"){
_(wrapperid).style.display = 'none';
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action=delete_pm&pmid="+pmid+"&originator="+originator);
}
You may need to modify your form in order to do this. You have to pass the checkboxes to your PHP script as an array through ajax.
<input type='checkbox' name='pm[]' value='1'>1<br>
<input type='checkbox' name='pm[]' value='2'>2<br>
<input type='checkbox' name='pm[]' value='3'>3<br>
With the checkboxes like this, PHP can handle an array as such:
$_POST['pm'];
You will need to modify your ajax script to be able to send the array, and probably change your PHP script to loop thru the array value it receives. It's probably expecting an integer (a single ID) and you are about to send it an array.
Revised Ajax Method:
$("#submit").on('click',function(e) {
e.preventDefault();
var data = {
'pmIds': $("input[name='pm[]']").serializeArray(),
'action' : 'delete_pm',
'originator' : 'whatever'
};
$.ajax({
type: "POST",
url: 'php_parsers/pm_system.php',
data: data,
success: function(result) {
window.console.log('Successful');
},
});
})

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

Set a delay in a repeating jQuery / Ajax function

I am trying to add a delay to a repeatable query.
I found out that .delay is not the one to use here. Instead, I should go with setInterval or setTimeout. I tried both, without any luck.
Here's my code:
<?php
include("includes/dbconf.php");
$strSQL = mysql_query("SELECT workerID FROM workers ORDER BY workerID ASC");
while($row = mysql_fetch_assoc($strSQL)) {
?>
<script id="source" language="javascript" type="text/javascript">
$(setInterval(function ()
{
$.ajax({
cache: false,
url: 'ajax2.php',
data: "workerID=<?=$row['workerID'];?>",
dataType: 'json',
success: function(data)
{
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
}),800);
</script>
<?php
}
?>
<div id="output"></div>
The code works fine, it outputs the result as asked. It's just loads without the delay. The timout and / or interval doesn't seem to work.
Anybody knows what I am doing wrong?
I've never understood why people always add their AJAX requests in intervals rather than letting the successful AJAX calls just call themselves, all the while risking severe server load through multiple requests and not just making another call once you had a successful one come back.
In this light, I like to write solutions where the AJAX calls just call themselves on completion, something like:
// set your delay here, 2 seconds as an example...
var my_delay = 2000;
// call your ajax function when the document is ready...
$(function() {
callAjax();
});
// function that processes your ajax calls...
function callAjax() {
$.ajax({
// ajax parameters here...
// ...
success: function() {
setTimeout(callAjax, my_delay);
}
});
}
I hope this makes sense! :)
Update:
After reviewing this again, it's been brought to my attention that there was also a problem in the PHP code in the original question that I needed to clarify and address.
Although the script above will work great in creating a delay between AJAX calls, when added to the PHP code in the original post the script will just be echo'd out as many times as the number of rows the SQL query selects, creating multiple functions with the same name and possibly making all AJAX calls simultaneously...not very cool at all...
With that in mind, I propose the following additional solution - create an array with the PHP script that may be digested by the JavaScript one element at a time to achieve the desired result. First, the PHP to build the JavaScript array string...
<?php
include("includes/configuratie.php");
$strSQL = mysql_query("SELECT workerID FROM tWorkers ORDER BY workerID ASC");
// build the array for the JavaScript, needs to be a string...
$javascript_array = '[';
$delimiter = '';
while($row = mysql_fetch_assoc($strSQL))
{
$javascript_array .= $delimiter . '"'. $row['workerID'] .'"'; // with quotes
$delimiter = ',';
}
$javascript_array .= ']';
// should create an array string, something like:
// ["1","2","3"]
?>
Next, the JavaScript to digest and process the array we just created...
// set your delay here, 2 seconds as an example...
var my_delay = 2000;
// add your JavaScript array here too...
var my_row_ids = <?php echo $javascript_array; ?>;
// call your ajax function when the document is ready...
$(function() {
callAjax();
});
// function that processes your ajax calls...
function callAjax() {
// check to see if there are id's remaining...
if (my_row_ids.length > 0)
{
// get the next id, and remove it from the array...
var next_id = my_row_ids[0];
my_row_ids.shift();
$.ajax({
cache : false,
url : 'ajax2.php',
data : "workerID=" + next_id, // next ID here!
dataType : 'json',
success : function(data) {
// do necessary things here...
// call your AJAX function again, with delay...
setTimeout(callAjax, my_delay);
}
});
}
}
Note: Chris Kempen's answer (above) is better. Please use that one. He uses this technique inside the AJAX routine. See this answer for why using setTimeout is preferable over setInterval.
//Global var
is_expired = 0;
$(function (){
var timer = setInterval(doAjax, 800);
//At some point in future, you may wish to stop this repeating command, thus:
if (is_expired > 0) {
clearInterval(timer);
}
}); //END document.ready
function doAjax() {
$.ajax({
cache: false,
url: 'ajax2.php',
data: "workerID=<?=$row['workerID'];?>",
dataType: 'json',
success: function(data) {
var id = data[0]; //get id
var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
}); //END ajax code block
} //END fn doAjax()
I've devised a a wrapper method which adds a custom delay on-top of the default $.ajax method. This is a way to have (on all jQuery ajax calls) a delay, throughout your entire app.
Very handy in simulating real-life random latency.
(function(){
$._ajaxDelayBk = $.ajax; // save reference to the "real" ajax method
// override the method with a wrapper
$.ajax = function(){
var def = new $.Deferred(),
delay = typeof $.ajax.delay == 'undefined' ? 500 : $.ajax.delay,
delayTimeout,
args = arguments[0];
// set simulated delay (random) duration
delayTimeout = setTimeout(function(){
$._ajaxDelayBk(args)
.always(def.resolve)
.done(def.resolve)
.fail(def.reject)
}, delay);
def.abort = function(){
clearTimeout(delayTimeout);
};
return def;
}
})();
USE EXAMPLE:
// optional: set a random delay to all `ajax` calls (between 1s-5s)
$.ajax.delay = Math.floor(Math.random() * 5000) + 1000;
var myAjax = $.ajax({url:'http://whatever.com/API/1', timeout:5000})
.done(function(){ console.log('done', arguments) })
.fail(function(){ console.log('fail', arguments) })
.always(function(){ console.log('always', arguments) })
// Can abort the ajax call
// myAjax.abort();
var takeInput=true;
$('#searchDrug').on('input',function() {
if(!takeInput){return false;}
takeInput=false;
var timer = setTimeout(function() {
$.ajax({
type: 'POST',
url: "{{route('AjaxSearchDrug')}}",
data: {
_token: '<?php echo csrf_token() ?>',
'searchkeyword': searchkeyword,
},
success: function (data) {
//do some logic then let keys be effective once more
takeInput=true;
}
});
}, 700);

Use the result of an ajax request as a variable

I would like to know how I can use the result of an ajax request as an "object". I'll try to explain. I have an ajax request that get a number, every 2 seconds, to an xml file. Then I render it into my html.
Here is my js:
var url = window.location.pathname.split('/');
var id = url[3];
setInterval(function() {
$.ajax({
type: "GET",
url: "http://myxml",
success: parseXml
});
}, 2000);
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
$(".DubScore").html($(this).attr("count"))
}
});
}
and my html:
<div class="DubScore"> </div>
It works find, I have a count displayed to my page.
What I want to do, is to take this number and be able to do whatever I wan't with it in my html. For example, name it "Score", and be able to do "Score" + 2 , and things like that.
I hope my question is clear enough. Thank you for your help.
You can parse the attribute value and store it in a global variable :
var score;
function parseXml(xml){
$(xml).find("user").each(function() {
if($(this).attr("id") === id ) {
score = parseInt($(this).attr("count"), 10);
}
});
}
Afterwards, you may do, for example,
score += 2;
$(".DubScore").html(score);

Categories

Resources