[英]Use Ajax call to pass array into Javascript code
I am using a datepicker and I want to query a MySQL database when it is clicked to make certain dates unavailable. 我正在使用日期选择器,我想查询MySQL数据库,单击该数据库以使某些日期不可用。 How to I pass this array into my JavaScript code where it says "AJAX CALL CODE NEEDS TO GO HERE"?
如何将此数组传递到我的JavaScript代码中,其中显示“需要在此处输入AJAX调用代码”?
Here is my code for the Javascript date picker 这是我的Javascript日期选择器代码
$(function() {
$('input[name="start_date"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
},
isInvalidDate: function(date) {
var dateRanges = [
AJAX CALL CODE NEEDS TO GO HERE
];
return dateRanges.reduce(function(bool, range) {
return bool || (date >= range.start && date <= range.end);
}, false);
}
});
$('input[name="start_date"]').on('apply.daterangepicker', function(ev, picker) {
document.getElementById("start_date").value = picker.startDate.format('MM/DD/YYYY');
document.getElementById("end_date").value = picker.endDate.format('MM/DD/YYYY');
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
Here is the code that needs to be inserted into that code in the PHP file for the ajax call: 这是需要将代码插入PHP文件中用于ajax调用的代码:
<?php
include 'dbconfig.php';
$sql="SELECT start_date, end_date FROM date_ranges ";
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)) {
echo "{ 'start': moment('" . $row['start_date'] . "'), 'end': moment('" . $row['end_date'] . "') },";
mysqli_close($conn);
}
?>
edit: new code with the help of Emiel Zuurbier 编辑:在艾米尔·祖尔比耶的帮助下的新代码
$(function() {
var dateRanges = null;
$.ajax({
url: 'getdaterangepicker.php',
method: 'GET',
dataType: 'json',
success: function(response) {
if (response) {
dateRanges = $.parseJSON(response);
}
}
});
$('input[name="start_date"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
},
isInvalidDate: function(date) {
return dateRanges.reduce(function(bool, range) {
return bool || (date >= range.start && date <= range.end);
}, false);
}
});
$('input[name="start_date"]').on('apply.daterangepicker', function(ev, picker) {
document.getElementById("start_date").value = picker.startDate.format('MM/DD/YYYY');
document.getElementById("end_date").value = picker.endDate.format('MM/DD/YYYY');
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
Returns error "TypeError: null is not an object (evaluating 'dateRanges.reduce')" 返回错误“ TypeError:null不是对象(正在评估'dateRanges.reduce')”
Since you are using jQuery we'll use the $.ajax
function of jQuery. 由于您使用的是jQuery,因此我们将使用jQuery的
$.ajax
函数。
In your PHP file change the contents of the while loop to the code below. 在您的PHP文件中,将while循环的内容更改为以下代码。 It will create an associative array to store the
start
and end
value in, without moment
because that is JavaScript, and send the array as JSON . 这将创建一个关联数组存储
start
和end
的值,不moment
,因为这是JavaScript和发送数组作为JSON 。 Because it is an associative array it will be turned into an object which we can use in JavaScript. 因为它是一个关联数组,所以它将变成一个我们可以在JavaScript中使用的对象。
// Create empty array.
$date_ranges = array();
// Add every row to array;
while($row = mysqli_fetch_array($result)) {
// Create an associative array to store the values in.
// This will later be a JavaScript Object.
array_push($date_ranges, array(
'start' => $row['start_date'],
'end' => $row['end_date']
));
mysqli_close($conn);
}
// Send the $date_ranges as JSON.
$json = json_encode($date_ranges); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
In the JavaScript prepare for storing the dateRanges
. 在JavaScript中准备存储
dateRanges
。 Create a variable before your AJAX call which will hold the result. 在AJAX调用之前创建一个变量,它将保存结果。
Now you can make your AJAX request. 现在,您可以提出AJAX请求。 This has to be sent to the PHP file in which you defined your logic for getting the result.
这必须发送到PHP文件中,您在其中定义了获取结果的逻辑。 We want to get something from the server, so use the
GET
method. 我们想从服务器上获取一些东西,所以使用
GET
方法。 Instruct the AJAX request to expect JSON and handle it accordingly. 指示AJAX请求使用JSON并进行相应处理。 Set the
dataType
to 'json'
. 将
dataType
设置为'json'
。
When the request is send do something with your response. 发送请求后,请对您的回复进行处理。 This can be done by setting the
success
property to a function. 这可以通过将
success
属性设置为一个函数来完成。 This function will receive the response and opens it up for us to use. 此函数将接收响应并将其打开以供我们使用。 Decode the response from JSON to JavaScript and voila, you have your result.
将响应从JSON解码为JavaScript和voila,即可得到结果。
Edit: Put the AJAX call inside a wrapper function. 编辑:将AJAX调用放入包装函数中。 This way you can use this function multiple times when you deem necessary.
这样,您可以在必要时多次使用此功能。 Also it creates a way to fire a callback function from which we can access our data.
它还创建了一种触发回调函数的方式,我们可以从中访问数据。
// AJAX request wrapper function.
// Call this function to get the dates from the server.
function getDateRanges(callback) {
$.ajax({
url: '/yourphpfile.php', // Change this to the uri of your file
method: 'GET', // Use the GET method
dataType: 'json', // Expect a JSON response
success: function(response) { // What will happen when the request succeeds
if (response) { // Check if there is a response
callback(response); // Pass the response into the callback
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
}
});
}
So now you can call the server any time you like. 因此,现在您可以随时调用服务器。
You need your dates before you call the daterangepicker
function. 在调用
daterangepicker
函数之前,需要日期。 Before the edit the code would call the AJAX function, but before any value was returned, because it can take a second, the daterangepicker
was already called and used the null
value before it had any time to update that null
value. 在编辑之前,该代码将调用AJAX函数,但在返回任何值之前(因为可能要花一秒钟的
daterangepicker
),已经调用了daterangepicker
并使用了null
值,然后才有时间更新该null
值。
This is because of the A in AJAX , which stands for Asynchronous . 这是因为AJAX中的A代表“ 异步” 。 That means that when the
$.ajax
function is fired it does not wait for it to complete, but goes on executing the rest of the script. 这意味着在
$.ajax
函数被触发时,它不会等待它完成,而是继续执行脚本的其余部分。 Whenever the $.ajax
function gives a response the success
function is triggered. 只要
$.ajax
函数给出响应,就会触发success
函数。 But we weren't waiting for it to finish. 但是我们没有等待它完成。 So we'll adjust that.
因此,我们将对此进行调整。
Put the code where you set the datepicker
into the callback of the now created getDateRanges
function. 将您设置
datepicker
的代码放入现在创建的getDateRanges
函数的回调中。 This causes the daterangepicker
to wait until the AJAX call is finished and has a value. 这将导致
daterangepicker
等待直到AJAX调用完成并具有一个值。
See code below: 参见下面的代码:
// Get the dates from the server.
// Fire the callback function when the AJAX call has returned a value.
// And use it as the dates variable.
getDateRanges(function(dates) {
$('input[name="start_date"]').daterangepicker({
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
},
isInvalidDate: function(date) {
// Here use your dates that you've got from the server.
var dateRanges = dates;
return dateRanges.reduce(function(bool, range) {
return bool || (date >= moment(range.start) && date <= moment(range.end));
}, false);
}
});
$('input[name="start_date"]').on('apply.daterangepicker', function(ev, picker) {
document.getElementById("start_date").value = picker.startDate.format('MM/DD/YYYY');
document.getElementById("end_date").value = picker.endDate.format('MM/DD/YYYY');
});
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
});
More on how to use the ajax function of jQuery, check out these docs . 有关如何使用jQuery的ajax函数的更多信息,请查看这些文档 。
Now the start
and end
values are still strings. 现在
start
和end
值仍然是字符串。 I did see you were using moment
in your PHP, but since we removed that from the PHP you'll have to call them in your JS. 我确实看到过您在PHP中使用了
moment
,但是由于我们从PHP中删除了一下,因此您必须在JS中调用它们。
You could do that in your reduce function: 您可以在reduce函数中做到这一点:
return bool || (date >= moment(range.start) && date <= moment(range.end));
I hope this is of any help! 希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.