Ajax sorting through the whole array - javascript

Currently i have a project to create a webpage to show FIFA 2018 Matches and here's where I get the API: http://www.football-data.org/documentation
The connection code goes like this
$.ajax({
headers: { 'X-Auth-Token': 'YOUR_API_TOKEN' },
url: 'sample' ,
dataType: 'json',
data: filter code like ?timeFrame=n1 or ?matchday=1
type: 'GET',
}).done(function(response) {
});
My problem now is I wanted to create an option so users could have the selection to sort the matches according to their match day or a time frame.
My code is basically like this, i changed a part of the ajax call to assign the value
url: $('#selectMatch').val() ,
The select code and function
<select id="selectMatch">
<option value="day1url">1 Day</option>
<option value="day7url">7 Day</option>
<option value="day10url">10 Day</option>
</select>
$(function(){
$('#selectMatch').change(function(){
var matchURL= $(this).val();
return matchURL;
});
But when i click the option it will load the first choice not the other choices

Related

How can I load a list of object into select tag with Ajax through API Controller?

I have a list of options inside a 'select' tag. For whichever option is selected, an 'onchange' function will be activated which carries on the value of that option. A function which activated will use Ajax to call to a controller to get a list of data that I can store into my others 'select' tag. How can I achieve this?
My HTML:
<select id="category-select" onchange="GetEmployee()">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
My JS:
function GetEmployee() {
var MaNguoiDung = 120;
var MaThuMuc = document.getElementById("category-select").value;
$('#employeeDisplay').change(function () {
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien?MaNguoiDung=" + MaNguoiDung + "&MaThuMuc=" + MaThuMuc,
success: function () {
alert('Get Success');
}
});
});
}
The alert was only to test if my ajax can run or not. Apparently, it can't. Also, I need to know how to stored query data into the second 'select'. Like after the URL attribute, I don't know what to write next after that. Sorry but I'm completely new in Ajax. Some referencing and tutorial online mostly shown how to load ajax into the table. There might be more but table is the only thing I can find so I'm very in need of a way to store it into select.
Edit: This is the response data I receive from my Controller
Sample JSON
You have several problems with the code shown.
The <select> you have the onchange in is not the same one you target to get value inside the function.
You are creating a new change event inside the function called by onchange. That new jQuery change() won't fire until next time you edit the <select>
You are manually creating the url query string but also providing a data object. Internally jQuery takes that object and will add it to the query string you manually created, effectively duplicating the parameters
So, lets get rid of the onchange , give the <select> an id and fix the query string in the ajax. Also you want an error handler to help troubleshooting
As for how to handle the response will need to see a sample of it first
HTML
<select id="category-select">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
JS
$(function () {
$('#category-select').change(function () {
var category = this.value;
// I don't know which variable is which in `data`
var MaNguoiDung = 120;// is this category ???
var MaThuMuc = null // confused where this comes from because other select is empty
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien",
success: function (response) {
// ^^ missing argument needed to receive the data
console.log(response)// log it to console for now
alert('Get Success');
},
error: function(xhr, status, message){
console.log('Status: ', status, ', Message: ', message)
}
});
});
});

How to auto select "select" option in html input after ajax request?

I have an AJAX request going to my PHP file to pull data from the database that pertains to the users. I want to autofill the form inputs. I was able to fill most of the inputs, but the HTML "select" option is really stumping me. Does anyone know how to autoselect the value in the database?
HTML
<select class="gender-reg" name="gender-reg">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="optout">Rather Not Say</option>
</select>
AJAX REQUEST
$(function () {
$.ajax({
type: 'GET',
url: 'http://localhost:8090/HELPERSITE/src/php/session.php',
dataType: 'json',
data: '',
success: function (response) {
console.log(response);
$(".username-reg").attr("value", (response['username']));
$(".pwd-reg").attr("value", (response['password']));
$(".email-reg").attr("value", (response['email']));
$(".acct-type").text(response['type']);
$(".fname-reg").attr("value", (response['fname']));
$(".lname-reg").attr("value", (response['lname']));
$(".gender-reg").attr("value", (response['gender']));
$(".street-reg").attr("value", (response['street']));
}
})
});
You can simply use .val():
$(".gender-reg").val(response['gender']);

JQuery Update Options From Json Return

So I have this HTML form:
<select name="finder[4]" id="finder-2--4" class="pffield pf-make">
<option value="0">Please Select...</option>
<option value="52505">Alfa Romeo</option>
<option value="52506">Audi</option>
<option value="52499">BMW</option>
<option value="52501">Ford</option>
</select>
I have this jQuery
<script type="text/javascript">
jQuery("document").ready(function(){
//console.log('on load');
jQuery(".js-ajax-php-json").submit(function(){
//console.log('post');
var data = {
"action": "test"
};
data = jQuery(this).serialize() + "&" + jQuery.param(data);
jQuery.ajax({
type: "POST",
dataType: "json",
url: "/reglookup.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
console.log(data['make']);
//$(".pf-make option:selected").text("Ford");
//$(".pf-make option:contains(Ford)").attr('selected', true);
//$(".pf-make option[text=" + data["make"] +"]").attr("selected","selected");
$(".pf-make").val('52499');
alert("Form submitted successfully.\nReturned json: " + data["make"]);
}
});
return false;
});
});
</script>
I get the following return from the json post
Object {make: "Ford", model: "Focus", year: "2010", engine: 2.5, fuel: "Petrol"}
So the post and call back work fine as these get logged in the console, and I need to be able to take the called back make data["make"] and update the selected option in the select form.
You can see I have tried a number of different options, even hand typing "Ford" into the code, but I always seem to get the following error back in the console:
(index):221 Uncaught TypeError: Cannot read property 'val' of null
For the life of me I cant get this working at the moment.
get the option value using contains, then set the select:-
var ford = $('.pf-make option:contains("Ford")').val();
$('.pf-make').val(ford);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="finder[4]" id="finder-2--4" class="pffield pf-make">
<option value="0">Please Select...</option>
<option value="52505">Alfa Romeo</option>
<option value="52506">Audi</option>
<option value="52499">BMW</option>
<option value="52501">Ford</option>
</select>
A simple solution is to iterate over the options to find the matching text, then access its value.
var $select = jQuery('.pf-make');
var value = 0;
$select.find('option').each(function(){
if(jQuery(this).text() == data.make){
value = jQuery(this).val();
return false;
}
});
$select.val(value);
Instead of $ use jQuery, and also use Instead of data["make"] to data.make
see this updated code. Please take note that it uses ID rather than class name to make it more specific
<script type="text/javascript">
jQuery("document").ready(function(){
//console.log('on load');
jQuery(".js-ajax-php-json").submit(function(){
//console.log('post');
var data = {
"action": "test"
};
data = jQuery(this).serialize() + "&" + jQuery.param(data);
jQuery.ajax({
type: "POST",
dataType: "json",
url: "/reglookup.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
jQuery("#finder-2--4").val(data.make);
}
});
return false;
});
});
</script>

select option value send to php file with ajax

I have a select dropdown box
<select name="status" id="status" onchange="changeStatus()">
<option value="step_1">step_1</option>
<option value="step_2">step_2</option>
<option value="step_3">step_3</option>
<option value="step_4">step_4</option>
</select>
And my javascript
<script>
function changeStatus() {
$('select.changeStatus').change(function(){
$.ajax({
type: 'POST',
url: 'update_status.php',
data: {changeStatus: $('select.changeStatus').val()},
dataType: 'html'
});
});
});
</script>
So I want the value selected from the select dropdown box send to the php file(update_status.php)
Select id using #. Since you are already using javascript onchange event in select field so no need to use jquery change() event. jQuery use # to select id and . to select class. since you are using id="status" so you must use # to select the id. The way you are trying to collect the value of the select field in this line $('select.changeStatus').val() is wrong. Because there are no class named changeStatus there.
function changeStatus() {
$.ajax({
type: 'POST',
url: 'update_status.php',
data: {changeStatus: $('#select').val()},
dataType: 'html'
});
}
$('#status').val() is used to get value of select options.
So try this
<script>
function changeStatus() {
$.ajax({
type: 'POST',
url: 'update_status.php',
data: {changeStatus: $('#status').val()},
dataType: 'html'
});
});
</script>
or
<script>
function changeStatus() {
$.post("update_status.php", {changeStatus: $('#status').val()}, function(data, status){
});
}
</script>
You don't need to mix jQuery and inline JS
HTML - we'll use your selects name in the function. I've removed the inline function call:
<select name="status" id="status">
<option value="step_1">step_1</option>
<option value="step_2">step_2</option>
<option value="step_3">step_3</option>
<option value="step_4">step_4</option>
</select>
jQuery - I have taken the code out of the function you were calling inline, it was not needed.
<script>
$(document).ready(function() {
$('select[name="status"]').change(function(){
var status = $(this).val();
$.ajax({
type: 'POST',
url: 'update_status.php',
data: {changeStatus: status},
dataType: 'html'
});
});
});
</script>
You can directly test when the select changes and grab its value right then. Here is an EXAMPLE
I have also wrapped the jQuery in a document ready handler. Depending on where you're loading the script in your page you may need to do this to make sure that your jQuery is run as soon as the DOM elements have been loaded.
Remove the onchange field from select and put the below code to your script and this is working. Use JQuery post functionality instead.
$("#status").change( function() {
alert($( this ).val());
$.post('update_status.php', { changeStatus: $(this).val()},
function(response) {
console.log( response);
});
});
<select name="status" id="status" onchange="changeStatus(this.value)">
<option value="step_1">step_1</option>
<option value="step_2">step_2</option>
<option value="step_3">step_3</option>
<option value="step_4">step_4</option>
</select>
function changeStatus(value) {
$.ajax({
type: 'post',
url: 'update_status.php',
data: {'get_data:value'},
success: function (response) {
document.getElementById("loadto").innerHTML=response;
}
});
}
I Hope it will be helpful .....

JavaScript failing after second ajax request using submit/selection button

I'm guessing this error has to do with asynchronous programming, but I can't seem to wrap my head around it after looking at various examples on here...
I have a basic form that should do a post request and then it produces a d3 graph based on the form selection value...
<form id="target" method="post">
<select name="len" id="len">
<option value="sel">--Select--</option>
<option value="year">Most Recent Year</option>
<option value="all">All Data</option>
</select>
<input type = "submit"class="btn" value="Submit"/>
</form>
$(document).ready(function(){
$('.btn').on('click',function(){
var myvar = $('select[name=len]').val();
$.ajax({
url: 'dbquery_o2_select.php',
type: 'POST',
data: {'var':myvar},
dataType: "JSON",
success: function (result){
// produce a d3 graph here
},
error: function(jqXHR,textStatus){
alert(textStatus);
}
});
return false; });
});
Upon the second "submit", I get an error saying that 'sampledate' (which is an associated name in the ajax return array named 'result') is undefined.
Thanks in advance for any help. Let me know if you need more info!

Categories