php – using AJAX [object Object]
Question
I am new to working with AJAX. For whatever reason, every time I refresh the page, there doesn’t seem to be any error, just an alert box with [object Object]. I do not understand why this occurs.
<script>
jQuery(document).ready(function($) {
// This is the variable we are passing via AJAX
var fruit="Banana";
// This does the ajax request (The Call).
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'example_ajax_request', // This is our PHP function below
'fruit' : fruit // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
window.alert(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
});
</script>
<?php
function example_ajax_request() {
// The $_REQUEST contains all the data sent via AJAX from the Javascript call
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Processes the fruit variable into an Apple
if ( $fruit == 'Banana' ) {
$fruit="Apple";
}
// Returns the result to the Javascript function (The Callback)
echo $fruit;
}
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
Edit: I tried console.log(data) and errorThrown and got an error message with: Failed to load resource: the server responded with a status of 400 ()
0
1 month
2023-04-28T13:35:00-05:00
2023-04-28T13:35:00-05:00 0 Answers
0 views
0
Leave an answer