Я пытаюсь создать небольшой плагин для сайта WordPress, который манипулирует данными из полей, чтобы дать индивидуальные результаты на странице. Я невероятно хорошо разбираюсь в JS, PHP и веб-разработчике в целом, поэтому извините за любые большие ошибки.
Прямо сейчас я застрял при попытке передать данные JS в PHP с помощью Ajax, где у меня возникает проблема Uncaught RangeError. Я просто пытаюсь передать одну переменную (адрес), но зацикливаюсь. Функция для обработки onchange для поля также вызывается неоднократно (как я обнаружил при ведении журнала), поэтому сам вызов функции прерывает прослушиватель событий.
Я пытался получить значение поля непосредственно в функции AJAX, поскольку я думал, что, возможно, это проблема с передачей значения, но, похоже, это ничего не дало. Я также перемещал переменную catch для PHP, так как думал, что это может быть проблемой.
Я также подумал, что, возможно, перехватчик PHP находится в той же функции события, что и вызов AJAX, но еще не пытался переместить его.
Основной файл:
<?php
add_filter( 'gform_pre_render', 'populate_choices' );
//Note: when changing choice values, we also need to use the gform_pre_validation so that the new values are available when validating the field.
add_filter( 'gform_pre_validation', 'populate_choices' );
//Note: when changing choice values, we also need to use the gform_admin_pre_render so that the right values are displayed when editing the entry.
add_filter( 'gform_admin_pre_render', 'populate_choices' );
//Note: this will allow for the labels to be used during the submission process in case values are enabled
add_filter( 'gform_pre_submission_filter', 'populate_choices' );
function populate_choices( $form ) {
//only populating drop down for form id 5
if ( $form['id'] != 22 ) {
return $form;
}
//Adding post titles to the items array
global $wpdb;
$result = $wpdb->get_results ( "SELECT DISTINCT date FROM leadSchedule " );
$choices = array();
foreach($result as &$values){
$choices[] = $values->date;
}
//Adding items to field id 8. Replace 8 with your actual field id. You can get the field id by looking at the input name in the markup.
foreach ( $form['fields'] as &$field ) {
if ( $field->id == 4 ) {
foreach ($result as &$values){
$field->choices[]['text'] = $values->date;
}
}
}
return $form;
}
function my_enqueue() {
wp_enqueue_script( 'lead-scheduler', plugins_url( '/lead_ajax.js', __FILE__ ), array('jquery') );
wp_localize_script( 'lead-scheduler', 'leadajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function functionCaller() {
if (is_page ('')) {
?>
<script type="text/javascript" src="/wp-content/plugins/lead-scheduler/lead_ajax.js"></script>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(function(){
var addressField = document.getElementById('input_22_2');
var lastName = document.getElementById('input_22_3_4');
var bookDate = document.getElementById('input_22_4');
var bookTime = document.getElementById('input_22_5');
addressField.onchange = addressCheck;
function addressCheck(){
addressCheck();
<?php
if(isset ($_POST['address'])){
$address = $_POST['address'];
?>
alert("WE DID IT "<?php echo $address ?>)
<?php
}
?>
}
});
});
</script>
<?php
}
}
add_action('wp_head', 'functionCaller');
?>
Функция AJAX:
//AJAX
function addressCheck(){
jQuery(document).ready(function ($) {
$(function(){
var adr = document.getElementById('input_22_2').value;
alert(adr);
$.ajax({
type: "POST",
url: leadajax.ajax_url,
data: {address : adr},
success: function(){
alert("works");
},error: function(){
alert("broken");
}
});
});
});
}