I'm using JQVMaps to create a world map on a WordPress site. I need to generate the page's content based on the region the user clicked. Here is what I have so far for a proof of concept:
<div id="post"></div>
<script>
jQuery('#vmap').vectorMap({
map: 'world_en',
backgroundColor: '#fff',
borderColor: '#bbb',
borderOpacity: 1,
borderWidth: .2,
color: '#bbb',
onRegionOver : function (element, code, region)
{
highlightRegionOfCountry(code);
},
onRegionOut : function (element, code, region)
{
unhighlightRegionOfCountry(code);
},
onRegionClick: function(element, code, region)
{
highlightRegionOfCountry(code);
$.ajax('/get_chart_data.php', {
dataType: 'json',
success: function(response) {
var jspost = "<?php echo $post; ?>";
var el = document.getElementById("post");
el.html = jspost;
}
});
}
});
</script>
And here's what I have in get_chart_data.php:
<?php
// Switch based on region
switch($_REQUEST['region']) {
case China:
$post = 'You clicked China';
break;
case Canada:
$post = 'You clicked Canada';
break;
case Brazil:
$post = 'You clicked Brazil';
break;
}
echo json_encode($post);
?>
I'm getting no response from the map. I'm very new to AJAX, so I would appreciate any and all help I can get with this. I may be missing a very crucial piece.
When you say "no response from the map," do you mean that your highlightRegionOfCountry and unhighlightRegionOfCountry are working, and it's just that your ajax call is not working? And what you want is for the value of the $post variable in your php script to end up inside your element?
If that's the case, I think there's a little confusion about how you receive data in your jQuery ajax call. You wouldn't receive it by putting php code inside the javascript code, you would receive it in the data passed to your success callback function, in the variable "response" as you have it. Also, you have to pass the clicked code as data in the ajax call. Also, you can't use just a plain "html" property on a dom element, so I'll change that. So your ajax call should be changed to something like:
$.ajax({
url: "/get_chart_data.php",
data: {
region: region
},
success: function(response) {
$("#post").html(response);
}
});
Also it's a better practice to quote your strings in php, so instead of e.g. case China:, use case 'China': and so on.