How to make HTML option filed in PHP file with jQuery?
I want to integrate simplybook.me api in my website.
The URL of the API is: https://simplybook.me/api/explorer there is Filter performers by service.
I want to make option fields of my services ad services provider list in PHP site.
<script>
var loginClient = new JSONRpcClient({
'url': '//user-api.simplybook.me/login',
'onerror': function (error) {
alert(error);
}
});
var token = loginClient.getToken('narendra', '5501cb0d7052b9d95ba78559ed41cd65c7bc0d3a51e21e259cbe092142f7537e');
var loginClient = new JSONRpcClient({
'url': '//user-api.simplybook.me/login',
'onerror': function (error) {
alert(error);
}
});
var token = loginClient.getToken('narendra', '5501cb0d7052b9d95ba78559ed41cd65c7bc0d3a51e21e259cbe092142f7537e');
var client = new JSONRpcClient({
'url': 'https://user-api.simplybook.me/',
'headers': {
'X-Company-Login': 'narendra',
'X-Token': token
},
'onerror': function (error) {
alert(error);
}
});
var services = client.getEventList();
var performers = client.getUnitList();
var serviceId;
var performerId;
jQuery('#select_event_id').empty();
jQuery('#select_unit_id').empty();
jQuery('#select_event_id').append('<option value=""></option>');
jQuery('#select_unit_id').append('<option value=""></option>');
for (var id in services) {
jQuery('#select_event_id').append('<option value="' + id + '">' +
services[id].name + '</option>');
}
for (var id in performers) {
jQuery('#select_unit_id').append('<option value="' + id + '">' +
performers[id].name + '</option>');
}
jQuery('#select_event_id').change(function () {
// service id
serviceId = jQuery(this).val();
var selectedService = services[serviceId];
// filter available performers
if (selectedService) {
if (typeof(selectedService.unit_map) != 'undefined' &&
selectedService.unit_map.length) {
jQuery('#select_unit_id option').attr('disabled', true);
jQuery('#select_unit_id option[value=""]').attr('disabled', false);
for (var i = 0; i < selectedService.unit_map.length; i++) {
jQuery('#select_unit_id option[value="' +
selectedService.unit_map[i] + '"]').attr('disabled', false);
}
} else {
jQuery('#select_unit_id option').attr('disabled', false);
}
}
jQuery('#eventId').val(serviceId).change();
});
jQuery('#select_unit_id').change(function () {
performerId = jQuery(this).val();
});
And there is my website URL where I can use this code:
http://dev.dissertationconsulting.co.uk/bookingsystem/cllogin.php
Related
I have Javascript code that display dropdownlist from controller :
public async Task<IActionResult> GetSubCategory(Guid id)
{
var SubCategory_List = await _admin.GetGategories();
return Json(new SelectList(SubCategory_List.Where(c => c.ParentId == id), "Id", "CategoryName"));
}
$.getJSON("/AdminPanel/Product/GetFirstSub/" + np.MainCat,
function (data) {
$.each(data,
function () {
$("#firstsub").append('<option value= ' + this.value + '>' + this.text + '</option>');
const idfirst = this.value;
console.log(idfirst);
$("#CategoryId").empty();
$.getJSON("/AdminPanel/Product/GetSecondSub/" + idfirst,
function (data) {
$.each(data,
function () {
$("#CategoryId").append('<option value= ' + this.value + '>' + this.text + '</option>');
});
}
);
});
dropdownlist values are Guide string ...
consol.log display this:
I want to receive these values individually and use them ... How can do this?
I can not rebuild your application exactly because I don't have your json data.
I don't think you can append options like you did it.
Just change the If statement to your needs so it should work.
Please post your getJson response so I try to help you.
var getEmployeeDataFromJson = new Promise(
function(resolve) {
$.getJSON("https://raw.githubusercontent.com/bmehler/employees/main/employees", function(data) {
resolve(data);
});
}
);
var getProductDataFromJson = new Promise(
function(resolve) {
$.getJSON("https://raw.githubusercontent.com/bmehler/product/main/product.json", function(data) {
resolve(data);
});
}
);
getEmployeeDataFromJson
.then(function(data_employee) {
console.log('data-employee', data_employee);
$.each(data_employee, function(index, value) {
$('#firstsub').append($('<option>', {
value: value.id,
text: value.name
}));
});
getProductDataFromJson
.then(function(data_product) {
console.log('data-product', data_product);
$.each(data_product, function(index, value) {
// Change this to your needs
if (value.category == 'Electronics') { // == data_employee[0].id
$('#CategoryId').append($('<option>', {
value: value.category,
text: value.name
}));
}
});
})
.catch(function(error) {
console.log(error.message);
});
})
.catch(function(error) {
console.log(error.message);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="firstsub">
</select>
<select id="CategoryId">
</select>
I write a demo to show my idea here, hope it could solve your problem or come up with some ideas at least.
I think you can prepare all the data when initialize selectors, that means you can finish the init task via 1 http request. And add onchange event on the select DOM.
My view, home.cshtml
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<div>
<select id="city"></select>
<select id="town"></select>
</div>
<script>
$(function () {
initSel();
});
$("#city").change(function () {
var cityid = $("#city option:checked").val();
console.log(cityid);
$.ajax({
url: "https://localhost:44319/home/getTownsById",
data: {
cityId: cityid
},
success: function (data) {
console.info("towns:" + data);
$("#town").html("");
for (var i = 0; i < data.length; i++) {
$("#town").append('<option value= ' + data[i].townId + '>' + data[i].townName + '</option>');
}
}
});
});
function initSel() {
$.ajax({
url: "https://localhost:44319/home/init",
dataType:"json",
success: function (data) {
console.info(data);
for (var i = 0; i < data.cities.length; i++) {
$("#city").append('<option value= ' + data.cities[i].cityId + '>' + data.cities[i].cityName + '</option>');
}
for (var i = 0; i < data.towns.length; i++) {
$("#town").append('<option value= ' + data.towns[i].townId + '>' + data.towns[i].townName + '</option>');
}
}
});
}
</script>
And this is my home controller:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebApplication1.Models;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
public JsonResult init() {
List<City> cities = new List<City>
{
new City{ CityId="city1", CityName="city1"},
new City{ CityId="city2", CityName="city2"},
new City{ CityId="city3", CityName="city3"}
};
var firstCityId = cities[0].CityId;
var towns = getTownsById(firstCityId);
Dictionary<string, object> res = new Dictionary<string, object>();
res.Add("cities", cities);
res.Add("towns", towns);
return Json(res);
}
public List<Town> getTownsById(string cityId) {
List<Town> data = new List<Town>
{
new Town{ CityId="city1",TownId="town1", TownName="town1"},
new Town{ CityId="city1",TownId="town2", TownName="town2"},
new Town{ CityId="city2", TownId="town3", TownName="town3"},
new Town{ CityId="city2", TownId="town4", TownName="town4"},
new Town{ CityId="city3", TownId="town5", TownName="town5"}
};
var towns = data.AsQueryable().Where(town => town.CityId == cityId);
return towns.ToList<Town>();
}
}
}
I use the Google Places API and when I change address it works perfectly in Chrome but doesn't always work in Mozilla Firefox.
I use jQuery, Bootstrap 4 and JS and Symfony 4 for the backend.
function onPlaceChangedEditUser() {
console.log('1');
var place = this.getPlace();
$('.postal_code').val('');
for (var i in place.address_components) {
var component = place.address_components[i];
for (var j in component.types) {
var type_element = $('.' + component.types[j]);
if (component.types[j] == "country") {
$('#country').find('option').attr('selected', false);
$('#country').find('option[data-country="' + component.short_name + '"]').attr('selected', true);
$('#country_iso').val(component.short_name);
$('#country').change();
$('.country-short').val(component.short_name);
if ($('.country').length) {
$.ajax({
url: Routing.generate("front.dashboardbabysitter.find.language"),
type: "POST",
headers: {
"cache-control": "no-cache"
},
async: false,
cache: false,
data: {
'isoCountry': component.short_name
},
success: function(json) {
if (!json.hasError) {
$('.country option:selected').removeAttr('selected');
$('.country option[value=' + json.idLanguage + ']').attr('selected', 'selected');
$('.country').val(json.idLanguage);
}
},
error: function(XMLHttpRequest, textStatus) {
if (textStatus !== 'abort') {
var error = "TECHNICAL ERROR: unable to send login informations \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus;
$.growl.error({
message: error
});
return false;
}
},
complete: function() {}
});
}
if (jQuery.inArray(component.short_name, mp_country_prefix)) {
var phone_number = '+' + mp_country_prefix[component.short_name];
var flag_class = (component.short_name).toLowerCase();
$('#flag').removeClass().addClass('flag position-absolute ' + flag_class);
$('#phone').val(phone_number);
} else {
console.log('there is no iso');
}
}
if (type_element) {
type_element.val(component.long_name);
}
if ($("#latitude").length) {
$("#latitude").val(place.geometry.location.lat());
$("#longitude").val(place.geometry.location.lng());
}
if ($(".latitude").length) {
$(".latitude").val(place.geometry.location.lat());
$(".longitude").val(place.geometry.location.lng());
}
if ($('#address1').length) {
$('#address1').val($('.street_number').val() + ' ' + $('.route').val())
}
if ($('#edit_babysitter_personal_info_address_address1').length) {
$('#edit_babysitter_personal_info_address_address1').val($('.street_number').val() + ' ' + $('.route').val())
}
if ($('#parent_personal_info_address_address1').length) {
$('#parent_personal_info_address_address1').val($('.street_number').val() + ' ' + $('.route').val())
}
}
}
}
function initializeAutocomplete(id) {
var element = document.getElementById(id);
if (element) {
var autocomplete = new google.maps.places.Autocomplete(element, {
types: ['geocode'],
language: _mpop.current_lang
});
if (id == "parent_personal_info_fullAddress" || id == "edit_babysitter_personal_info_fullAddress" ||
id == "address_bb" || id == "home_address") {
google.maps.event.addListener(autocomplete, 'place_changed', onPlaceChangedEditUser);
}
}
}
You can use addEventListener instead of addListener
Reference - link
Identify the browser and apply the event accordingly.
I have a jquery function that has an ajax call. I can't get the total price to come up even though it should be working. The class .cart-price is within .cart-body so I don't think its an issue with the template.
function refreshCart(){
console.log("in current cart")
var cartTable = $(".cart-table")
var cartBody = cartTable.find(".cart-body")
// $(cartBody).empty()
//cartBody.html("<h1>Changed</h1>")
var productRows = cartBody.find(".cart-product")
var currentUrl = window.location.href
var refreshCartUrl = '/api/cart/'
var refreshCartMethod = "GET";
var data = {};
$.ajax({
url: refreshCartUrl,
method: refreshCartMethod,
data: data,
success: function(data){
console.log("success")
console.log(data)
if (data.products.length > 1){
productRows.html(" ")
$(cartBody).empty()
$.each(data.products, function(index, value){
console.log(value)
cartBody.append("<tr><td>" + value.name + "</td><td>" + value.price + "</td></tr>")
})
// console.log(data.total)
cartBody.find(".cart-total").text(data.total)
} else {
window.location.href = currentUrl
}
},
error: function(errorData) {
console.log("error")
console.log(errorData)
}
})
}
})
$(cartBody).empty() was clearing everything in the table body. The solution was to create a new HTML table row outside of the table body.
So I'm working on this Zipline for my free code camp and am pretty much done, i'm just trying to implement a search. I have it working ok but have a couple of bugs.
What i'm doing for the search is that i'm creating a new array then i'm filtering it and comparing it to the text input of the user and if its equal then i will push that value onto a new array then display it on the screen.
is there a better way to do this? so that as the user types it is comparing with the list of arrays I have.
Thanks
Here is the jsfiddle http://jsfiddle.net/wtj7s6c6/2/
$(document).ready(function () {
var img, user, status, channel,
url = "https://api.twitch.tv/kraken/",
/* cb = '?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?',*/
cb = '?callback=?',
//create new array from filtered array
newArray = [],
userList = ["freecodecamp", "maximilian_dood", "UltraChenTV", "habathcx", "TeamSpooky", "Nuckledu", "medrybw"];
/*function updateLog(message) {
$("#log").html($("#log").html() + "<p>" + message + "</p>");
};*/
function addOnlineUser(image, username, status) {
$(".people")
.append('<li><img class="picture" src="' + image + '"/><span class="username">' + username + '</span><span class="isOnline">✔</span><p class="status">' + status + '</p></li>');
};
function addOfflineUser(image, username) {
if (image != null) $(".people")
.append('<li><img class="picture" src="' + image + '"/> <span class="username">' + username + '</span><span class="isOffline">!</span></li>');
else $(".people")
.append('<li><img class="picture emptypic"/><span class="username">' + username + '</span><span class="isOffline">!</span></li>');
};
function clickOnline() {
userList.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream !== null) {
img = data.stream.channel.logo;
user = data.stream.channel.display_name;
status = data.stream.channel.status;
channel = data._links.channel;
addOnlineUser(img, user, status);
}
});
});
};
function clickOffline() {
userList.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream === null) {
$.getJSON(url + 'users/' + name + cb)
.success(function (data2) {
img = data2.logo;
user = data2.display_name;
channel = data2._links.self;
addOfflineUser(img, user);
});
}
});
});
};
function clickSearchOff(array) {
array.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data) {
if (data.stream === null) {
$.getJSON(url + 'users/' + name + cb)
.success(function (data3) {
img = data3.logo;
user = data3.display_name;
channel = data3._links.self;
addOfflineUser(img, user);
});
}
});
});
};
function clickSearchOn(array) {
array.forEach(function (name) {
$.getJSON(url + 'streams/' + name + cb)
.success(function (data4) {
if (data4.stream !== null) {
img = data4.stream.channel.logo;
user = data4.stream.channel.display_name;
status = data4.stream.channel.status;
channel = data4._links.channel;
addOnlineUser(img, user, status);
}
});
});
};
$(".online").on('click', function () {
$(".people").empty();
clickOnline();
});
$(".offline").on('click', function () {
$(".people").empty();
clickOffline();
});
$(".all").on('click', function () {
$(".people").empty();
clickOnline();
clickOffline();
});
$(".all").click();
$('input[type="text"]').keyup(function () {
var searchTerm = $(this).val();
searchTerm = searchTerm.toLowerCase();
console.log("Search term:" + searchTerm);
//empty screen//
$(".people").empty();
var newArray = [];
for (var i = 0; i < userList.length; i++) {
if (userList[i].indexOf(searchTerm) != -1) {
newArray.push(userList[i]);
}
}
console.log("New array: " + newArray);
clickSearchOff(newArray);
clickSearchOn(newArray);
});
})
I suggest (as I may do) implement some kind of buffer on the keyup event in order to not always trigger the comparison, only after one or two seconds pass after the last keyup trigger:
var compareTimeout;
$('input[type="text"]').keyup(function () {
clearTimeout(compareTimeout);
compareTimeout = setTimeout(function () {
var searchTerm = $(this).val();
searchTerm = searchTerm.toLowerCase();
console.log("Search term:" + searchTerm);
//empty screen//
$(".people").empty();
var newArray = [];
for (var i = 0; i < userList.length; i++) {
if (userList[i].indexOf(searchTerm) != -1) {
newArray.push(userList[i]);
}
}
console.log("New array: " + newArray);
clickSearchOff(newArray);
clickSearchOn(newArray);
}, 2000);
});
This would make the function run only after 2 seconds after the last keyup event, and not every time the user types a letter in the input.
I am not sure if this is due to the fact that getJSON is asynchronous or not. I think that would be the most obvious reason, but I don't have a clear understanding of how that works. In my js file, I call the healthCheck method on the body element. Nothing happens. Is my getJSON callback function even getting called? I don't know.
I have uploaded the script on JSFiddle.
The code is also below:
var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
( function($) {
$.fn.healthCheck = function() {
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.getJSON(request, function(data) {
var result = new Object();
$.each(data, function(key, val) {
result.key = val;
if (val == false) {
this.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
this.append(key + " working. <br />");
}
});
});
return this;
};
}(jQuery));
Many thanks in advance. I hope my query is well placed. If anyone knows some good resources to get a better understanding of asynchronous methods in jQuery that would be greatly appreciated, also. I haven't found many that have been easy to follow yet.
Try 1) setting context of jQuery.ajax( url [, settings ] ) to this of $.fn.healthCheck ; 2) create reference to this object at $.each()
var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
(function($) {
$.fn.healthCheck = function() {
// set `this` object within `$.getJSON`
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.ajax({
url:request
, type:"GET"
, contentType: false
, context: this
, processData:false
}).then(function(data) {
// reference to `this` within `$.each()`
var that = this;
var result = new Object();
$.each(JSON.parse(data), function(key, val) {
result.key = val;
if (val == false) {
// `that` : `this`
that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
that.append(key + " working. <br />");
console.log("complete"); // notification
}
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown); // log errors
});
return this;
};
}(jQuery));
$("body").healthCheck();
See also How do I return the response from an asynchronous call?
var baseURL = "https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/62775b7420f8df6b3d83244270d26495e40a1e9d/a.json";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";
(function($) {
$.fn.healthCheck = function() {
var timestamp = new Date().toJSON().toString();
var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
var signature = 123;// CryptoJS.HmacSHA1(request, key);
request = baseURL + request + "&signature=" + signature;
$.ajax({
url:request
, type:"GET"
, contentType: false
, context: this
, processData:false
}).then(function(data) {
var that = this;
var result = new Object();
$.each(JSON.parse(data), function(key, val) {
result.key = val;
if (val == false) {
that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
} else {
that.append(key + " working. <br />");
console.log("complete"); // notification
}
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown); // log errors
});
return this;
};
}(jQuery));
$("body").healthCheck()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>