I'm trying to use AJAX to pass a querystring within wordpress, I've tried various code on the net using get and post. However I'm unable to get the parameter within my PHP.
Using javascript within my page works, however it posts back the page which I want to avoid. Any suggestions?
working code with postback:
self.location = "?q=" + postcode;
or
jQuery.param.querystring(location.href= "?q=" + postcode);
ajax query using $_POST['q'] in php doesn't get the parameter
jQuery.ajax({
type: 'POST',
url: 'wp-admin/admin-ajax.php' ,
data: {"q": postcode},
success: function(data){jQuery('#results').val(postcode);}
});
Thanks
Gemma
Still having issues with this, can't get my querystring into my php:
class PostcodeChecker extends WP_Widget {
function PostcodeChecker() {
$widget_ops = array(
'classname' => 'PostcodeChecker',
'description' => 'Checks if valid postcode in database before request button enable'
);
$this->WP_Widget(
'PostcodeChecker',
'Postcode Checker',
$widget_ops
);
}
function widget($args, $instance) { // widget sidebar output
extract($args, EXTR_SKIP);
echo $before_widget; // pre-widget code from theme
print ('<h2 class="blocktitle">Postcode Checker</h2> ');
print ('<input type="text" id="txtPostcode"/> <input id="btnRegister" type="button" disabled="disabled" value="request application form" />');
print ('<br/><input type="text" id="results"></div><br/>');
$postcode = $_GET['q'];
print $postcode;
$mysqli= mysqli_connect('localhost','root', 'My5ql5s5s');
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
// A QUICK QUERY ON A FAKE USER TABLE
$query = "SELECT * FROM db_wp_webteam1.wp_bduk_towns where town_postcode='BT11ER'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
// GOING THROUGH THE DATA
if($result->num_rows > 0) {
//while($row = $result->fetch_assoc()) {
// echo stripslashes($row['town_postcode']);
//}
echo 'Results found';
}
else {
echo 'NO RESULTS';
}
// CLOSE CONNECTION
mysqli_close($mysqli);
echo $after_widget; // post-widget code from theme
}
}
function add_js_to_wp_footer(){ ?>
<script type="text/javascript">
jQuery('#txtPostcode').keyup(function(){
var postcode = jQuery(this).val();
postcode = postcode.replace(/\s+/g, '');
if (postcode.length >= 5)
{
//self.location = "?q=" + postcode;
jQuery('#txtPostcode').keyup(function(){
var postcode = jQuery(this).val();
postcode = postcode.replace(/\s+/g, '');
if (postcode.length >= 5)
{
jQuery.ajax({
type: 'POST',
url: 'wp-admin/admin-ajax.php' ,
data: {"q": postcode},
success: function(data){jQuery('#results').val(data);}
});
}
return false;
});
}
return false;
});
</script>