Can I call a function in autocomplete select event?
I have a function call getResult() which will retrieve data from database, the function is working smooth, just I fail to call this function in autocomplete's select event. Below is my code:
Auto-complete code:
$(function()
{
//auto complete for facultyID
var availableTags = <?php
$sql = "SELECT FacultyID from tblfaculty";
$result = mysql_query($sql, $DBLink) or die("Error " . mysql_error($DBLink));
$id_list = array();
while($row = mysql_fetch_array($result))
{
$id_list[] = $row['FacultyID'];
}
echo json_encode($id_list); ?>;
$("#FacultyID").autocomplete(
{
source: availableTags,
autoFocus:true,
select: function(event, ui)
{
getResult();
}
});
});
getResult() function:
function getResult()
{
$(function()
{
var Semester = $('#Semester').val();
var Year = $('#Year').val();
var Course = $('#Course').find(":selected").val();
var Subject = $('#Subject').find(":selected").val();
var FacultyID = $('#FacultyID').val();
var TimeSlot = $('#TimeSlot').val();
var Location = $('#Location').val();
$.ajax(
{
type: 'POST',
url: 'ajax_get_time_table.php',
data: {Semester:Semester+", "+Year, Course:Course, SubjectID:Subject, FacultyID:FacultyID, TimeSlot:TimeSlot, Location:Location},
dataType: 'json',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
//do something
}
else
{
//do something
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
}
Is there any wrong with my code?
You don't have to put everything in a doc ready block in getResult() function:
$(function(){});
because the DOM is already loaded and you are able to call this function inside autocomplete's select event.
Related
I'm calling an AJAX using a $.when to wait till that ajax completes and return to process the next ajax inside.
This is where $.when calling happens:
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1[0])); //this is in the attached screen shot
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}
Above code is calling below ajax method function:
function getCreditorID(){
id = "";
var creditorcodex = document.getElementById('creditorcode').value;
// console.log("getCreditorID input: " + creditorcodex);
var urlx = "functions/getCreditorID.php";
return $.ajax({
type: 'POST',
url: urlx,
data: {
creditorcode: creditorcodex,
},
success: function(data) {
console.log("Result : "+data); //this is in the attached screen
}
});
}
Above function calling getCreditorID.php to get data:
getCreditorID.php:
<?php
include '../config/dbConn.php';
$creditorcode = $_POST["creditorcode"];
// $creditorcode = $_GET["creditorcode"];
$result="";
$sql = "SELECT intCustomerID FROM lms.tblcustomers WHERE varCustomerName='".$creditorcode."';";
mysql_select_db('$dbname');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
$result=-999;
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$result=$row["intCustomerID"];
}
echo $result;
mysql_close($conn);
?>
Problem is:
If return from getCreditorID.php is '44' then console.log("Result : "+data); inside getCreditorID() function will output in console as 'Result : 44' and this is working fine. But the same function is getting returned in loadAllData() function and using the value returned for next ajax. Here if we print the return value using console.log("cx id is : " + parseFloat(a1[0])); output is '4' which should be '44'. Which means it's only giving the first character as output and ignoring the rest.
Screenshot of running console:
Please find a way out.
In your function loadAllData(), use a1 instead of a1[0] and update your code accordingly
function loadAllData(){
$.when(getCreditorID()).done(function(a1){
console.log("cx id is : " + parseFloat(a1)); // did correction here
var urlx = "functions/getCustomerData.php";
$.post(
urlx,
{
selectedValue: a1[0],
},
function(data) {
$("#payduedate").val(data[0].duedate);
document.getElementById('portcode').value = data[0].portcode;
document.getElementById('currencycode').value = data[0].currencycode;
document.getElementById('convertion').value = data[0].conversion;
},
"json"
);
});
}
I'm new with JSON. I have a select box and JavaScript change() trigger on it. I execute MySQL query with Ajax based on selected value. Query results will be printed as a new row in HTML table.
But the new row isn't appending. What am I doing wrong?
HTML
<select id="orderAddProduct">
<option value=""></option>
<option value="0001">Product 1</option>
<option value="0002">Product 2</option>
</select>
<table id="orderTable">
<tr><th>ID</th><th>Name</th></tr>
</table>
JavaScript
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "POST",
url: "orderAddProduct.php",
data: {option: selectedValue},
datatype: "json",
success: function (data) {
alert("OK");
orderAddRow(data);
},
error: function () {
alert("ERROR");
}
});
});
function orderAddRow($item) {
$.each($item,function(index,value) {
var row = '<tr><td>'+value.id+'</td>'
+'<td>'+value.name+'</td></tr>';
$('#orderTable').append(row);
)};
}
PHP
try {
$pdo = new PDO(DB_TYPE . ':host=' . DB_HOST . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("SET NAMES utf8");
$productId = $_REQUEST['option'];
$sql = $pdo->prepare("SELECT * FROM products_view WHERE id = ?");
$sql->execute(array($productId));
$row = $sql->fetch(PDO::FETCH_ASSOC);
$json_array = array("ID" => $row['id'], "name" => $row['name']);
echo json_encode($json_array);
Variable names?
function orderAddRow($item) {
^^^^^^----
var row = '<tr><td>'+value.id+'</td>'
^^^^^----
You define a $item parameter, but never use it in the function. Instead there's this mysterious/undefined value.
Ok, the master problem is that I didn't have JSON.parse() function in my code. Below is my finally working code.
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "GET",
url: "orderAddProduct.php",
data: {option : selectedValue},
datatype: "json",
success: function (response) {
response = JSON.parse(response);
if(response === undefined) {
alert("undefined");
} else {
orderAddRow(response);
}
},
error: function () {
alert("ERROR");
}
});
return false;
});
function orderAddRow($data) {
$.each($data,function(index,value) {
var row = '<tr><td>' + value.ID + '</td>'
+ '<td>' + value.name + '</td></tr>';
$('#orderTable').append(row);
});
}
success: function (data) {
alert("OK");
orderAddRow(data);
},
You are missing out the returned value.
I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>
I'm having a trouble using change function. I have a 2 different dropdowns attached to each other. When the first one is changes, the second one changes too. I did it using jquery ajax. But when i use ID's jquery can only work one time. So i did a research about javascript's this,parent and children keyword but i can't find the suitable way.
so my javascript is like below :
<script>
$(document).ready(function() {
// alert('js working');
$(".catSelectedClass").change(function() {
// alert('i'm inside the function dude');
function ustCat() {
alert(this);
var mainCatID = $(this).val();
alert('mainCatID captured');
var id = $(this).parent().$(".catIDClass").val();
// alert(id);
// alert(mainCatID);
$.ajax({
type: "POST",
url: "panel/catGroupPost.php",
data: {id: id, mainCatID: mainCatID}
}).done(function(data) {
var responseData = data;
alert(responseData);
$('#subCat').html($(data));
});
}
ustCat();
});
$(".subCatClass").change(function() {
function subCat() {
var mainCatID = $(this).val();
var id = $('#catID').val();
$.ajax({
type: "POST",
url: "panel/subCatPost.php",
data: {id: id, mainCatID: mainCatID}
}).done(function() {
alert('its done. its gone. Yes Mr.Frodo. Its all over now !!');
});
}
subCat();
});
});
</script>
And this is how a fill dropdowns :
while ($cat = mysql_fetch_array($cat_query)) {
$catTable.= '<label>' . $cat['name'] . '</label>';
$catTable.= '<div class="catContainer"><div id="catPost" class="catPostClass">';
$catTable.= '<input type="text" id="catID" class="catIDClass" value="' . $cat['id'] . '"><select id="catSelected" class="catSelectedClass" name="catSelected"><option value="0">Seçiniz...</option>' . catOption($cat['mainCatID']) . '</select></div>';
$kategoriTablosu.= '<div id="subCat"><select id="subCatID" class="SubCatClass"><option value="0">Seçiniz...</option>' . subCatOption($cat['mainCatID']) . '</select></div></div>';
}
My both functions:
function catOption($id) {
$query = mysql_query("SELECT * FROM mainCats WHERE id=mainCatID") or die(mysql_error());
$arrCat = "";
while ($row = mysql_fetch_array($query)) {
$arrCat .= '<option value="' . $row['mainCatID'] . '"';
if ($row['id'] == $id) {
$catSelected = 'selected="selected"';
} else {
$catSelected = "";
}
$arrCat .= '' . $catSelected . '>' . $row['name'] . '</option>';
}
return $arrCat;
}
And :
function subCatOption($subID) {
$subCat = mysql_query("SELECT * FROM mainCats WHERE mainCatID='$subID' ORDER BY id ") or die(mysql_error());
$subArrCat = "";
while ($row = mysql_fetch_array($subCat)) {
$subArrCat .= '<option value="' . $row['mainCatID'] . '"';
if ($row['mainCatID'] == $subID) {
$catSelected = 'selected="selected"';
} else {
$catSelected = "";
}
$subArrCat .= '' . $catSelected . '>' . $row['name'] . '</option>';
}
return $subArrCat;
}
Thanks for any help !
You need to change your code as
$(".catSelectedClass").change(function() {
var mainCatID = $(this).val();
//Rest of code....
});
Instead of
$(".catSelectedClass").change(function() {
// alert('i'm inside the function dude');
function ustCat() {
var mainCatID = $(this).val();
//Rest of code....
}
});
Same with $(".subCatClass").change(function() {
General Syntax
$(selector).change(function() {
//do something
});
If you have already defined function use
$(selector).change(your_defined_function);
in your case you can use
$(".catSelectedClass").change(ustCat);
the problem is that you call a function in the event handler. If you instead put the code inside the event handler or you turn the function in the handler it should fix your problem. I suggest to make the function the event handler. So just put the ustCat on its own and use the following to make the function the handler
$(".catSelectedClass").change(ustCat);
You don't need the functions inside the change function. You can simply do:
$(".catSelectedClass").change(function () {
// alert('i'm inside the function dude');
alert(this);
var mainCatID = $(this).val();
alert('mainCatID captured');
var id = $(this).parent().$(".catIDClass").val();
// alert(id);
// alert(mainCatID);
$.ajax({
type: "POST",
url: "panel/catGroupPost.php",
data: {
id: id,
mainCatID: mainCatID
}
}).done(function (data) {
var responseData = data;
alert(responseData);
$('#subCat').html($(data));
});
});
$(".subCatClass").change(function () {
var mainCatID = $(this).val();
var id = $('#catID').val();
$.ajax({
type: "POST",
url: "panel/subCatPost.php",
data: {
id: id,
mainCatID: mainCatID
}
}).done(function () {
alert('its done. its gone. Yes Mr.Frodo. Its all over now !!');
});
});
The way you did it this was in the wrong scope. this would be window.
Several ways to do it.
You don't really need to define ustCat, you can just put the code inside the change function :
$(".catSelectedClass").change(function() {
var mainCatID = $(this).val();
....
});
Or assign the parent before you call your inner function :
$(".catSelectedClass").change(function() {
(function ustCat(self){
var mainCatID = self.val();
......
})($(this));
});
Or put the ustCat function elsewere and just pass it to the change handler :
function ustCat(){ var mainCatID = $(this).val(); ...... };
$(".catSelectedClass").change(ustCat);
I have utilized on key up function with ajax to check in my database if the course name already exist. A prompt then will be showed to the user after a match is found. I have used the distinct query in my model and then the controller returns the right value to the ajax however the returned value were duplicated or even multiple values are returned causing the pop up message in my page to show multiple times also. What is wrong with this? Thanks for the help.Here are my codes
View (Javascript):
<script>
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData={
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>courses/check_course_name_existince",
dataType:'json',
data: postData,
success: function(data)
{
if(data.msg == 'Exist')
{
console.log(data.msg);
$("#alert_exist").fadeIn(100);
$("#alert_exist").delay(3000).fadeOut(1000);
var a = 0;
$("input[type=radio][value=" + a + "]").attr("disabled",true);
document.getElementById('course_desc').disabled=true;
document.getElementById('userfile').disabled=true;
document.getElementById('is_public').disabled=true;
document.getElementById('submit').disabled=true;
}
else
{
console.log(data.msg);
var a = 0;
$("input[type=radio][value=" + a + "]").attr("disabled",false);
document.getElementById('course_desc').disabled=false;
document.getElementById('userfile').disabled=false;
document.getElementById('is_public').disabled=false;
document.getElementById('submit').disabled=false;
}
}
});
</script>
Controller:
function check_course_name_existince()
{
$course_name = $this->input->post('course_name');
$session_id = $this->session->userdata('username');
$result = $this->
course_booking_model->check_course_name_exist($session_id,$course_name);
if($result)
{
$msg="Exist";
}
else
{
$msg="Available";
}
echo json_encode(array('msg'=>$msg));
}
Model:
function check_course_name_exist($tennant_id,$course_name)
{
$where = array(
'tennant_id' => $tennant_id,
'course_name' => $course_name
);
$this->db->distinct();
$this->db->select('course_name');
$this->db->where($where);
$this->db->group_by('course_name');
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
Image Output:
The console log function returns 2 identical values resulting to 2 message pop up.
Try adding some checks before setting a new timeout to prevent multiple triggers to your ajax call
var typingTimer = null;
var doneTypingInterval = 3000;
$('#course_name').keyup(function () {
if (!typingTimer) {
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
}
});
$('#course_name').keydown(function () {
if (typingTimer) {
clearTimeout(typingTimer);
typingTimer = null;
}
});