Populating select in html document using ajax (JQuery) - javascript

Problem : I am trying to populate the 1st SELECT on load. And 2nd SELECT depends on the 1st one.
1st select : populated with states
2nd select : should be populated with districts based on selected states.
jSON file is HERE
Solutions given on other stackoverflow documents didn't meet my requirements\
$(document).ready(function(){
$.ajax({
type:'GET',
header:{' Access-Control-Allow-Origin ':'*'},
datatype:'json',
url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
})
.done(function(response){
console.log(response);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<div class="">
<select class="states" >
</select>
<select class="districts" >
</select>
</div>
<link rel="text/script" href="jquery-3.5.1.js">
<link rel="text/>script" href="index.js">
</body>
</html>

Below example show an example how to load data, first and then store it in
a var to prevent ajax loading every change, then in every change fetch data array to load districts :
( uring raw url load text , so you have to pare json from string at first )
See wokring snippet :
data = [];
$(document).ready(function() {
$(".states").on("change", stateChange);
$.ajax({
type: 'GET',
header: {
' Access-Control-Allow-Origin ': '*'
},
datatype: 'json',
url: 'https://raw.githubusercontent.com/sab99r/Indian-States-And-Districts/master/states-and-districts.json'
})
.done(function(response) {
var resp = JSON.parse(response);
loadStates(resp);
})
});
var loadStates = function(response) {
if (response.states) {
data = response.states;
response.states.forEach(state => {
var option = $('<option/>');
option.attr({
'value': state.state,
}).text(state.state);
$('.states').append(option);
})
}
}
var stateChange = function(event) {
let stateValue = event.target.value;
let state = data.find(state => state.state === stateValue);
$('.districts').html("");
if (state) {
state.districts.forEach(ditrict => {
var option = $('<option/>');
option.attr({
'value': ditrict,
}).text(ditrict);
$('.districts').append(option);
})
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
state :
<select class="states">
</select>
<br> distric
<select class="districts">
</select>

Just set code according to your requirement but you need to set all logic. You need to set when you send state data then you will get all districts
function changeselect(){
$.ajax({
type:'GET',
header:{' Access-Control-Allow-Origin ':'*'},
datatype:'json',
url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
})
.done(function(response){
console.log(response);
response.foreach(function(data){
$("#distr").append("<option>+data+</option>")
})
})
}
$(document).ready(function(){
$.ajax({
type:'GET',
header:{' Access-Control-Allow-Origin ':'*'},
datatype:'json',
url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
})
.done(function(response){
console.log(response);
response.foreach(function(data){
$("#distr").append("<option>+data+</option>")
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<div class="">
<select class="states" onchange="changeselect()">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<select class="districts" id="distr">
</select>
</div>
<link rel="text/script" href="jquery-3.5.1.js">
<link rel="text/>script" href="index.js">
</body>
</html>

I have got a even short code to do it.
We can use ajax GET to get data from the raw of any repository.
Solution to the above question :
$.get('https://raw.githubusercontent.com/aps08/web-development/main/web-dev-series/JSON/indian-states-and-cities.json', // url
function (data1, textStatus, jqXHR) { // success callback
var data1 = JSON.parse(data1);
load(data1);
});
Remember that if u loading data from your local machine then you need to remove
var data1 =JSON.parse(data1) line

Related

How to solve Error 400 on html page post method

I have make a simple html file to get my data and add button to post data but however i am returning error 400
My get method are running fine with displaying the backend data out in the html but however post method i am returning some errors 400 due to my query which i not sure why is there any way i can prevent this error 400 ?
<!DOCTYPE html>
<html>
<head>
<title>Add recycables</title>
<!-- Stylesheet -->
<link rel="stylesheet" href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id = "add"></div>
<P>Add recycables</P>
<p>name: <input type="text" id="name"></p>
<p>type:<input type="text" id="type"> </p>
<button id="add">Add</button>
</body>
<script>
$(document).ready(function(){
var $items = $('#add');
var $name = $('#name');
var $type = $('#type');
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/get",
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"RecyclableGet(0)",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, item, xhr,textStatus) {
//console.log(data)
$.each(data, function(i, item){
$items.append('<li>name: '+item.Name +', type: '+ item.RecyclableType + '</li>');
});
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
$('#add').on('click', function(){
var addRecyclables = {
Name: $name.val,
RecyclableType: $type.val
}
})
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/post",
method:"POST",
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:`RecyclableAdd('${name}','${type}')`,
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, Newitem, xhr,textStatus){
$items.append('<li>name: '+Newitem.Name +', type: '+ Newitem.RecyclableType + '</li>');
},
error:function(xhr,textStatus,err) {
console.log(err);
}
})
})
</script>
</html>
Json file look like
my html on web

JavaScript multiply two ids

I am trying to multiply two values that script get from below two different api. I am using document.getelementbyid to get the two id that I need which is gbp and balance. The api script can display the data get from api. However, the multiply script is not working. Nothing is showing. Help please?
first api
$(function() {
$.ajax({
type: "GET",
url: "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=ETH,GBP,HKD",
dataType: "json",
success: function (data) {
console.log(typeof data);
var json = data;
$('#gbp').html(json.GBP);
$('#hkd').html(json.HKD);
}
});
});
second api
$(function() {
$.ajax({
type: "GET",
url: "https://api.nanopool.org/v1/eth/reportedhashrate/1",
dataType: "json",
success: function (data) {
console.log(typeof data); // -- Object
var json = data;
$('#balance').html(json.data);
}
});
});
multiply javascript:
$(function () {
"use strict";
var $butbut =document.getElementById('gbp').html;
var $siksik =document.getElementById('balance').html;
var $lamlam = $butbut * $siksik;
document.getElementById('money').html=$lamlam;
});
html script
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="Untitled-4.js"></script>
</head>
<body>
<div id="balance"></div>
<div id="money"></div>
<div id="gbp"></div>
</body>
</html>
Getting the inner html of an element is .innerHTML, not .html
var $butbut = document.getElementById('gbp').innerHTML;
var $siksik = document.getElementById('balance').innerHTML;
document.getElementById('money').innerHTML = $lamlam;
Alternatively, you can use jquery
var $butbut = $('#gpb').html();
var $siksik = $('#balance').html();
$('#money').html($lamlam);

How to add parameters in a query string using input type text

I work with the api new york times search engine, my question is simple, i just want to change parameters in my url using a input type text in my html.
How can i do that ?
End date and sort are one of the parameter, i just want to know how can i change the string with an input field in html.
here a copy of my code :
html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel='stylesheet' type="text/css" href="nyt.css">
<link rel='stylesheet' type="text/css" href="font.css">
<link rel='stylesheet' type="text/css" href="grille.css">
</head>
<body>
<div class='container'>
<button type="submit" id='searchButton'></button>
<input type="text" id='searchTerm' placeholder="search">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src='nyt.js'></script>
</body>
</html>
js :
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
var searchTerm = document.getElementById('searchButton');
url += '?' + $.param({
'api-key': "[API KEY]",
'end_date': "19440606",
'sort': "newest"
});
$.ajax({
url: url,
method: 'GET',
q: searchTerm,
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
You can get the value of your input field with the “value” property, like so:
var searchTerm = document.getElementById('searchButton').value;
See also: JavaScript: how to get value of text input field?
function sendRequest(searchTerm) {
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "[API KEY]",
'end_date': "19440606",
'sort': "newest"
});
console.log(searchTerm);
return $.ajax({
url: url,
method: 'GET',
q: searchTerm,
});
}
document.querySelector('#searchButton').addEventListener('click', function(e){
e.preventDefault();
var query = document.querySelector('#searchTerm').value.trim();
if (query.length > 0) {
sendRequest(query)
.done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
}
})

Select HTML5 JSON AJAX JAVASCRIPT

I want to make an html5 select with data given by javascript, and inside this javascript an ajax calling a Json URL. I mean, I´ve got this:
--index.html
<!DOCTYPE html>
<html>
<head>
<script src="functions_app.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body onload="getData()">
<p>Sessions:
<select id="Select"></select>
</body>
</html>
functions_apps.js
function getData(){
$.ajax({
type: "GET",
url: 'http://.../json_offers.php',
async: false,
dataType: "json",
success: function(data){
//alert(data);
$.each(data,function(key, registro) {
var id = "";
var name = "";
$.each(registro, function(key, value) {
//alert(campo + ": " + valor);
if (key == "id") { id = value; }
if (key == "name") { name = value; }
});
});
$("#select").append('<option value='+id+'>'+nombre+'</option>');
},
error: function(data) {
alert('error');
}
});
}
json_offers.php
Json data:
[{"id":"6","name":"FLOWERS"},{"id":"8","name":"GROCERY"}]
But It does not work. It always return:
error: function(data)
I can´t load data given inside html select.
Any Help?
Best Regards
You have <select id="Select"></select>, but you are trying to put options into $("#select_zcas")

How to get data from select tag using AJAX before submitting into PHP?

I want to get the data of the select tag id="departmentselect" so that the values of it will be stored in the mysql database before submitting the form. I heard that you will use AJAX to get the data before you submit the form. Because when I select the College select tag and its corresponding values of the department select tag it will only store a number in the department of the database.
Example MYSQL database:
In the query of mysql, the department did not get the values of the JSON file. It only display the number.
Here is my PHPCode
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="SignupProcess.php" method="POST" onsubmit="return check_password();" id="signupform">
<select id="collegeselect" name="collegeselect">
<option value="">College</option>
<option value="College of CAS">College of CAS</option>
</select>
<select id="departmentselect" name="departmentselect">
<option value="">Department</option>
</select>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="GetCollegeJsonData.js"></script>
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$ajax
({
type: 'POST',
url: 'Signup.php?select' += select,
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
</html>
Script Type
Here is the script for using ajax but it did not seem to have any effect.
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$ajax
({
type: 'POST',
url: 'Signup.php?select' += select,
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
JQUERY Code file name GetCollegeJsonData.js
I get the JSON data from the file and read it into my Jquery file and then link the file using script to my php code
//Get json
$('body').on('change', '#collegeselect', function() {
var selected_college = $(this).val();
$('#departmentselect').html('');
$.getJSON("CollegeAndDepartment.json", function(data) {
$.each(data[selected_college], function(key, val) {
$('#departmentselect').append("<option value='" + key + "'>" + val + "</option>");
});
});
})
Its JSON File
{
"College of CAS": ["Biology", "English", "LIACOM", "Library & Information Science", "Mass Communication", "Philosophy", "Political Science", "Psychology"]
}
Is my Ajax function is incorrect?
Your ajax method code has syntax error and, when you use post method you have to post data using data option not with URL. data should be in json object or query string.
Your ajax function should be
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$.ajax({
type: 'POST',
url: 'Signup.php',
data: {select: $('#departmentselect').val()},
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
I have edited your code as below.
Kindly give it a try.
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="SignupProcess.php" method="POST" onsubmit="return check_password();" id="signupform">
<select id="collegeselect" name="collegeselect">
<option value="">College</option>
<option value="College of CAS">College of CAS</option>
</select>
<select id="departmentselect" name="departmentselect">
<option value="">Department</option>
</select>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="GetCollegeJsonData.js"></script>
<script>
$('#signupform').submit(function(e)
{
if($('#departmentselect').val() != '')
{
$.ajax
({
type: 'POST',
data:{select:$('#departmentselect').val()},
url: 'Signup.php',
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
</html>
For GetCollegeJsonData.js, ihave modified as follows:
//Get json
$('#collegeselect').on('change', function() {
var selected_college = $(this).val();
$('#departmentselect').html('');
$.getJSON("CollegeAndDepartment.json", function(data) {
$.each(data[selected_college], function(key, val) {
$('#departmentselect').append("<option value='" + val + "'>" + val + "</option>");
});
});
})

Categories