Include an element $id inside ajax query - javascript

When I edit my product, I want to my categories appear inside the dropdown. Currently it's just
-- Select your category --
For example, my $current_category_id = 2, the dropdown must display the good categories.
How to do that ?
tk
<div id="myAjax"><select name="move_to_category_id" id="category_id"><option value="0">-- Select your categorie --</option></div>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
var selectedOptionVal = $('#category_id').val();
$.ajax({
url: '<?php echo $categories_ajax; ?>',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '';
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
var selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>

Your code says, while clicking on the div you are doing an ajax call based on the selected value in the select box. But there will not be any value while clicking since you are updating the select box after that.
Call the ajax on on ready and populate your drop down box.

Related

Write Variable javascript in laravel

i am make ajax request on select box to return cities dependent on countries
but when i return old and test if this id of cities contain on array i can't write
the java script variable " key " that refer to city id on this line
i am attached photo of code with question
please help me
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country_id"]').on('change', function() {
var countryID = $(this).val();
if(countryID) {
$.ajax({
url: '{!! url('/admin/getCities') !!}/'+countryID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="ship_to_ids[]"]').empty();
console.log('ok');
$.each(data, function(key, value) {
$('select[name="ship_to_ids[]"]').append('<option value="'+ key +'" {{ (in_array( key , old( "ship_to_ids",
isset($product) ? ($product->ship_to_ids?:[]) : []))) ? "selected" : " " }}>'+ value +'</option>');
});
}
});
}else{
$('select[name="ship_to_ids[]"]').empty();
}
});
});
</script>
Ok the tricky part is here
{{ (in_array( key , ...
in_array is looking for a variable as first parameter and you gave it a constant key so you need to pass your key variable.
Updated
you can do so in your javascript code
var option = '<option value="'+ key +'" {{ (in_array( ":key" , old( "ship_to_ids", isset($product) ? ($product->ship_to_ids?:[]) : []))) ? "selected" : " " }}>'+ value +'</option>';
option = option.replace(':key', key)
$('select[name="ship_to_ids[]"]').append(option);

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

submitting arrays to php via ajax

I am having issues figuring out how to submit a form via ajax that has items with the same name(this form is dynamically created and has to use the same names for some fields).
This is the JS code that I have
<script>
var toggle123 = function() {
var chair = document.getElementsByName('chair[]');
var item1 = document.getElementsByName('item[]');
var price = document.getElementsByName('price[]');
var table = document.getElementById('table');
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'table='+table+'';
for(i=0;i<item1.length;i++)
{
dataString += + '& item1[]' + '=' + item1[i];
}
for(i=0;i<chair.length;i++)
{
dataString += + '& chair[]' + '=' + chair[i];
}
for(i=0;i<price.length;i++)
{
dataString += + '& price[]' + '=' + price[i];
}
if (chair == '' || item1 == '') {
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
var mydiv = document.getElementById('table1');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
I want it to submit to submit.php and also to hide the div that is open (table1).
I can get it to go to submit.php but I am not sure if the data is actually getting sent there or if it is just blank. It tells me there was an invalid argument for the foreach loop in submit.php.
Here is submit.php
<?php
include('dbconfig.php');
// Fetching Values From the post method
$table = $_POST['table_id'];
foreach($_POST["item1"] AS $key => $val) {
$chair = $val;
$price = $_POST['price'][$key];
$chair = $_POST['chair'][$key];
$query = mysqli_query($dbconfig,"insert into orders(table_id, price, item, chair) values ('$table', '$price', '$item', '$chair')"); //Insert Query
echo "Form Submitted succesfully";
}
?>
This is the javascript for the dynamic form....each time a button is clicked, this adds onto the form:
listholder.innerHTML += "Chair "+row.chair+"-<input type='hidden' id='chair' name='chair[]' value='"+row.chair+"' /><input type='hidden' id='table' name='table' value='"+row.table_id+"' /><input type='hidden' id='item' name='item[]' value='"+row.item1+"' /><input type='hidden' id='price' name='price[]' value='"+row.item1+"' />" + row.item1 + " - " + row.chair + " (<a href='javascript:void(0);' onclick='deleteCar(" + row.id + ");'>Delete Car</a>)<br>";
I think my main issue is probably forming the datastring that gets passed to submit.php. If anyone could help me figure this out, that would be great!
(P.S. toggle123 is activated via a button click (that works fine)

How to retrieve a value of a selected Item from a dropdown List?

How to i get a value of a selected ITEM from a drop down list ? I'm reading my values a SQL Table using a Stored Procedure ,Once the list is populated i want to take the selected ITEM and save the SQL TABLE. Any help will be much appreciated. Here is what i've tried :
function QueryKomaxDetails() {
$.ajax({
url: GET_SCHEDULE_DEPARTMENTS,
data: 'includeInactive=' + null,
dataType: 'json',
success: LoadKomaxDetails
});
}
var LoadKomaxDetails = function (data) {
var dllItems = eval(data);
var komaxDetails = $("#ddlItems").val();
$.each(dllItems, function () {
komaxDetails.append("<option value='" + this.departmentId + "'>" + this.departmentName + "</option>");
});
}
And i managed to get ITEM as a dropdown list.
Here is my HTML code as follows :
<label>Select Komax :</label><select id="ddlItems" name="komax" ></select>
Try this,
var komaxDetails = $("#ddlItems");
$.each(dllItems, function () {
komaxDetails.append("<option value='" + this.departmentId + "'>" + this.departmentName + "</option>");
});

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources