This is the first time I do the ajax and I must confess that I am confused. What I want to do is to take the value of 3 Select html to make a request to my database that'll get me a score according to the desired choice. The purpose of using ajax is that I do not want the submit button and I want that when the value of one of my select changes only choose my result in my database changes according to the new value. So the hen I change a value in my select I call a javascript that takes values from my select and pass ajax to my function.php which then makes a request with the values of my Selects function and then returns the result of my request.
I have my html in archive page, my .js in external file and my php function is in function.php.
My problem is that dont working and i dont know why, i follow 5 tuto and all are different and confuse me.
Sorry for my English, this language is not my first language.
Now my code look like that:
javascript:
function showWidth($) {
// get the value of my 3 html select
var width1 = document.getElementById('width1').value;
var width2 = document.getElementById('width2').value;
var width3 = document.getElementById('width3').value;
if (width1!="aucun" && width2!="aucun" && width3!="aucun") {
$.ajax({
ObjectName.ajaxurl,
data: {
action:'script_handle',
width01 : width1,
width02 : width2,
width03 : width3
},
success:function(data) {
// This outputs the result of the ajax request
document.getElementById("result").innerHTML=console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
}
PHP (in function.php):
function widthcalculate(){
if( isset($_REQUEST) ) {
$width1 = $_REQUEST['width01'];
$width2 = $_REQUEST['width02'];
$width3 = $_REQUEST['width03'];
// Let's take the data that was sent and do something with it
global $wpdb;
$where = "'".$width1."' AND camber = '".$width2."' AND handrim = '".$width3."'";
$sql = $wpdb->get_results(
"SELECT result FROM mc_widthCalculatorResult WHERE wheel = ".$where.""
);
foreach ($sql as $element) {
echo $element->result;
}
echo $result;
//print_r($_REQUEST);
}
die();
}
add_action( 'wp_ajax_script_handle', 'widthcalculate' ); // Hook for the WordPress Dashboard.
add_action( 'wp_ajax_script_handle_nopriv', 'widthcalculate' ); // Hook for the user facing side of the site.
function register_scripts() {
wp_register_script( 'script-handle', $path_to_javascript_file, $dependencies, 'version', $in_footer = true );
wp_enqueue_script( 'script-handle' );
wp_localize_script( 'script-handle', 'ObjectName', array( 'ajaxurl' => admin_url( '/wp-admin/admin-ajax.php' ), 'parameter' => $whatever_you_want_to_pass ) );
}
add_action( 'enqueue_scripts', 'register_scripts' );