Javascript is not showing desired Values - javascript

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

Related

Destroying a light gallery and re initiating it causing issue

I have a div with id "tempPictures". I want to destroy the gallery and re initiate it when closed and then reopened. It works fine when clicked first time, but second time, it opens the image in the same tab instead of light Gallery. Any1 encountered such an issue?
function getReplyImages(id) {
$formData = {
"_token": $token,
"inmate_reply_id": id
}
ajaxStartStop();
$.ajax({
url: $inmateReplyAttachmentsRoute,
type: 'POST',
data: $formData,
success: function (data) {
var html = '';
Object.keys(data).forEach(function (key) {
html += '<a href="' + data[key].file + '">';
html += '<img src="' + data[key].thumnail + '" />';
html += '</a>';
});
$('#tempPictures').html(html);
if(!$galleryLoaded) {
console.log('loaded');
$('#tempPictures').lightGallery({thumbnail: true});
$('#tempPictures > a:first > img').trigger('click');
}
$galleryLoaded = true;
},
error: function ($error) {
notificationMsg($error, error);
}
});
}
$(function () {
$("#tempPictures > a:first > img").click(function () {
return false;
});
});
$('#tempPictures').on('onCloseAfter.lg',function(event, index, fromTouch, fromThumb){
$('#tempPictures').lightGallery({destroy: true});
$('#tempPictures').html('');
$galleryLoaded = false;
});
I got it. I was not destroying the light gallery properly. It had to be done like this.
$('#tempPictures').data('lightGallery').destroy(true);

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.

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

How can I call ajax array passed from php json encode? zend framework 2

I can't call an arrays passed from the php json encode. I would concatenate 2 select state-contry-city. How can I do this??
This is the code:
I have 2 selects. I send the first value to an action:
php action into my controller:
public function regioniProvinceComuniAction(){
$response = $this->getResponse();
$request = $this->getRequest();
if ($request-> isPost()){
$post_data = $request->getPost();
$regione = (int)$post_data['regione'];
$province = (int)$post_data['province'];
}
if(isset($regione)){
$prov = $this->getProvincia($regione);
}
if(isset($province)){
$com = $this->getComuni($province);
}
$response->setContent(\Zend\Json\Json::encode(array('prov' => $prov, 'com' => $com)));
return $response;
}
This is my js file:
$("select#Regione").change(function () {
var regione = $("select#Regione option:selected").attr('value');
$.ajax({
type: 'POST',
url: '/zf-tutorial/public/regioni-province-comuni',
datatype: 'json',
data: { regione: regione },
success: function (data) {
alert (data);
}
});
});
An example of the alert function is like this:
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
I tried to populate my second select via data.post like this, but the values are "undefined":
success: function (data) {
$('select#Provincia option').each(function(){$(this).remove()});
for(var i=0; i<data.length; i++){
$("select#Provincia").append('<option value="' + data[i].prov.id + '">' + data[i].prov.nome + '</option>');
}
i tried to do
for (var i = 0; i < data.prov.length; i++) {
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
if i set manually the var data, works fine, but with the response data doesn't work. i tried to do:
var prov = data.prov;
$("div#id").html(prov);
but it doesn't work. works only like this:
$("div#id").html(data);
and the output is the same
{"prov":[{"id":"10","nome":"Genova"},{"id":"8","nome":"Imperia"},{"id":"11","nome":"La Spezia"},{"id":"9","nome":"Savona"}],"com":[]}
You need to loop through the items in data.prov. Change your for loop to this:
for (var i=0; i<data.prov.length; i++){
$("select#Provincia").append('<option value="' + data.prov[i].id + '">' + data.prov[i].nome + '</option>');
}
jsFiddle Demo
EDIT
Solution found in comments: Can you try to change datatype in your $.ajax() call to dataType. I'm not sure if the case is important. Sounds like data is a string and not an object

how to use javascript this keyword with change function

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

Categories

Resources