I need to have a field that will not allow data to be inputted if it returns a message of "false". The field "ponumber" checks against a DB and if that record already exists I dont want it to allow the user to use that particular PO Number. Basically it blanks it out if they leave the field and displays the message. The script is working perfect except now allowing the input based on the false return from checkponumberajax php file.
$(document).ready(function () {
var validateponumber = $('#validateponumber');
$('#ponumber').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateponumber.removeClass('error').html('<img src="/images/ajax-loader.gif" height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
url: 'includes/checkponumberajax.php',
data: 'action=check_ponumber&ponumber=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateponumber.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
});
<input type="text" name="ponumber" value="<?=#$_REQUEST['ponumber']?>" id="ponumber" />
and my checkponumber.php file returns like this
if ($records != 0) {
$response = array(
'ok' => false,
'msg' => "The selected PO# is not available");
} else {
$response = array(
'ok' => true,
'msg' => "This PO# is free");
}
Edit: Solved!
I ended up thanks to #bourch using this which simply blanks out the field once a value is reached that matches false
if(j.ok != true){$("#ponumber").attr("value", "");}
Try this:
if(j.ok != true){$("#ponumber").attr("disabled", "disabled");
}
Related
I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
I am working on a Cakephp 2.x but I don't think the problem has anything to do with the Cakephp. I want to delete a file without a page refresh.
HTML / PHP :
<div class = "success" style="display:none;">Deleted successfully </div>
<div class = "error" style="display:none;">Error </div>
JavaScript :
function openConfirm(filename, idImage) {
$.modal.confirm('Are you sure you want to delete the file?', function () {
deleteFile(filename, idImage);
}, function () {
});
};
function deleteFile(filename, idImage) {
var filename = filename;
$.ajax({
type: "POST",
data: {
idImage: idImage
},
url: "http://localhost/bugshot/deleteFile/" + filename,
success: function (data) {
if (data == 1) {
$(".success").fadeIn(500).delay(2000).fadeOut(500);
} else {
$(".error").fadeIn(500).delay(2000).fadeOut(500);
}
},
error: function () {
alert("error");
}
});
}
my images which is in foreach loop
this code is displaying the image
foreach($file as $files):?>
<?php $downloadUrl = array('controller' => 'bugshot', 'action' => 'downloadImages', $files['Image']['filename'], '?' => array('download' => true));
$imageUrl = array('controller' => 'bugshot', 'action' => 'downloadImages', $files['Image']['filename']);
?>
<?php echo $this->Html->link(
$this->Html->image($imageUrl),
$downloadUrl,
array('class' => 'frame', 'escape' => false)
);?>
Delete link
The code works great except that after the image or record is deleted the record/image is still displayed on the page until it is refreshed. How do I fix this?
You need to remove it with javascript.
$.ajax({
...
success: function (data) {
if (data == 1) {
$(".success").fadeIn(500).delay(2000).fadeOut(500);
$('img[src="/pathToImg/' + filename + '"]').remove(); // Remove by src
// $('#' + idImage).remove(); // Remove by ID.
} else {
$(".error").fadeIn(500).delay(2000).fadeOut(500);
}
}
...
});
Note : var filename = filename; means nothing because you are assigning filename argument to a new variable with the same name. You can just remove it.
I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.
i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)
try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};
I'm using a script I found for changing a line of text on the go (you click on it and an input shows). It works fine without doing anything to the database but when I add my code for an update, it will update the DB but won't refresh the text after it submits. I'm totally lost now since I've been at it for hours, maybe I'm missing something very basic.
My JS:
$.ajaxSetup({
url: '/ajax/nombreruta.php',
type: 'POST',
async: false,
timeout: 500
});
$('.editable').inlineEdit({
value: $.ajax({ data: { 'action': 'get' } }).responseText,
buttons: '',
cancelOnBlur: true,
save: function(event, data) {
var html = $.ajax({
data: { 'action': 'save', 'value': data.value }
}).responseText;
//alert("id: " + this.id );
return html === 'OK' ? true : false;
}
});
nombreruta.php:
<?php session_start();
$action = isset($_POST) && $_POST['action'] ? $_POST['action'] : 'get';
$value = isset($_POST) && $_POST['value'] ? $_POST['value'] : '';
include $_SERVER['DOCUMENT_ROOT'] ."/util-funciones.php";//for my db functions
$cnx=conectar();
$sel="select * from ruta where id_ruta='".$_SESSION['ruta']."'";
$field=mysql_query($sel, $cnx);
if($row=mysql_fetch_object($field)){
$data = $row->nombre;
}
switch ($action) {
// retrieve data
case 'get':
echo $data;
break;
// save data
case 'save':
if ($value != '') {
$sel="update ruta set nombre='".$value."' where id_ruta=".$_SESSION['ruta'];
mysql_query($sel,$cnx) or die(mysql_error());
$_SESSION['data'] = $value;
echo "OK";
} else {
echo "ERROR: no se han recibido valores.";
}
break;
// no action
default:
echo "ERROR: no se ha especificado accion.";
break;
}
Firebug shows me that after I update my text it returns OK and after I refresh the site it will show the updated text but not before. I started thinking this approach is too much hassle but after so much hours I feel like I'm one step from my solution...
EDIT:
I'm using this plugin: http://yelotofu.com/2009/08/jquery-inline-edit-tutorial/
And my html is just
<span class="editable">Text</span>
Your code works fine for me....
Here's the demo app I put together (asp.net, but basically the same minus the database).
Just to be clear: Press Enter to save. Click off to cancel (since you removed the buttons).
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" ></script>
<script type="text/javascript" src="https://raw.github.com/caphun/jquery.inlineedit/master/jquery.inlineedit.js"></script>
<script type="text/javascript">
$(function(){
$.ajaxSetup({
url: 'Test.ashx?' + window.location.search.substring(1),
type: 'POST',
async: false,
timeout: 500
});
$('.editable').inlineEdit({
value: $.ajax({ data: { 'action': 'get'} }).responseText,
buttons: '',
cancelOnBlur: true,
save: function (event, data) {
var html = $.ajax({
data: { 'action': 'save', 'value': data.value }
}).responseText;
return html === 'OK' ? true : false;
}
});
});
</script>
</head>
<body>
<span class="editable">Test 1</span>
</body>
</html>
C#
public void ProcessRequest(HttpContext context)
{
//Custom Object to Get and Format my Connection String from the URL
QueryStringObjects QSO = new QueryStringObjects(context.Request, "InlineAjaxTest");
//Look for any GET or POST params named 'action'
switch (context.Request.Params["action"])
{
//If 'action' = 'save' then....
case "save":
//Open a connection to my database (This is a custom Database object)
using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
{
//Create a SQL parameter for the value of the text box
DbParameter[] Params = {
new SqlParameter("#val", context.Request.Params["value"])
};
//Execute an Insert or Update
SQL.ExecSQL(#"UPDATE
Test_InlineAJAX
SET
Value = #val
IF ##ROWCOUNT=0
INSERT INTO
Test_InlineAJAX
VALUES
(#val)", Params);
}
//Return OK to the browser
context.Response.Write("OK");
break;
default:
//Open a connection to my database
using (DataBrokerSql SQL = GetDataBroker(QSO.Connstring))
{
//Get Value from my table (there's only one row so no need to filter)
object obj = SQL.GetScalar("Select Value From Test_InlineAJAX");
//If my value is null return "" if not return the value of the object
context.Response.Write(obj != null ? obj.ToString() : "");
}
break;
}
}
SQL
CREATE TABLE [dbo].[Test_InlineAJAX](
[Value] [varchar](255) NULL
) ON [PRIMARY]
Not sure what else to tell you, but maybe something here will give you an idea...