how to use javascript this keyword with change function - javascript

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

Related

Javascript is not showing desired Values

I am trying to manipulate gravity forms with the Custom fields to show the stores(along with assigning email to hidden field) in my form based on the state using the JSON and JavaScript.Same code is working for other website, but not yielding any result when i select state in the form. Please help me in navigating this issue.
I tried searching for similar answer but i didn't have any luck(also I am new so I am not very familiar with JSON).
Let me know if my way of posting question is right or there any edits need to be done?
PHP CODE:
add_action('wp_ajax_state_list_book_appointment','state_list_book_appointment');
add_action('wp_ajax_nopriv_state_list_book_appointment','state_list_book_appointment');
function state_list_book_appointment()
{
$states = get_field('state_options', 'option');
$output = [];
foreach ($states as $state) {
if ($state['booking_Appointment']) {
$output[] = [
'state_name' => $state['store'] . ' (' . $state['state'] . ')',
'state_email' => $state['store_email']
];
}
}
echo json_encode($output);
die();
}
JAVASCRIPT:
$(document).ready(function() {
if ($('#input_1_4').length > 0) {
var store_lists_book_appointment;
$('#input_1_4').on('change', function () {
current_state = $(this).val();
output = '';
state_string = '(' + current_state + ')';
console.log(state_string);
$("#input_1_6").val($("#input_1_6 option:first").val());
$.each($('#input_1_6 option'), function (idx, val) {
// assume state is in option format of ([state])
idx_of_state = $(val).val().indexOf(state_string);
if (idx == 0 || idx_of_state > 0) {
$(val).show();
} else {
$(val).hide();
}
});
});
$.ajax({
type:"GET",
url: my_ajax_object.ajaxurl,
data:{action: 'state_list_book_appointment'},
beforeSend: function(){
$('#catvalue').html('<i class="fa fa-spinner fa-1x" style="color:#000;text-align:center;"></i>');
},
dataType: 'json',
success: function (data) {
//console.log (data);
store_lists = JSON.parse(data);
//console.log(store_lists);
//store_lists_women = JSON.parse(data).women;
output = '<option>-- Please select --</option>';
$.each(store_lists, function (index, value) {
output += '<option style="display:none" value="' + value.state_name + '" data-email="' + value.state_email + '">' + value.state_name + '</option>';
});
$('#input_1_6').html(output);
}
});
$('#input_1_6').on('change', function () {
selected_email = $('#input_1_6 option:selected').data('email');
$('#input_1_10').val(selected_email);
});
// This function is to prevent Chrome frontend validation. It stop working actual submit function of the form
$('#gform_submit_button_1').on('click', function(){
$('#gform_1').submit();
});
}
});

AJAX inside $.when giving fist character of the return string

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

jquery call other self-declared function in autocomplete select event

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.

Adding table rows based on 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.

jQuery AJAX with PHP to upload contents to MYSQL DB

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

Categories

Resources