I want to reload page using with jQuery Ajax. I have the code below, however, it's not working and is returning error [object Object]
Is this just a simple syntax problem, or is my whole logic problematic? It is working perfectly without Javascript, but I'm thinking the UI is more intuitive with jQuery Ajax.
functions.php
//enqueue scripts
function my_theme_enqueue_scripts() {
wp_enqueue_script('jquery-ui', 'https://code.jquery.com/ui/1.12.1/jquery-ui.min.js', array('jquery'), '1.12.1');
wp_register_script( 'myjs', get_stylesheet_directory_uri() . '/my.js', array('jquery'),'1.0.0');
wp_enqueue_script('myjs');
wp_localize_script( 'ajax-script', 'admin-ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );
function load_projectmessages($projectid) {
global $wpdb;
$sql_displaymessages = $wpdb->prepare("some sql", $projectid );
$projectmessages = $wpdb->get_results($sql_displaymessages);
return $projectmessages;
wp_die();
}
add_action('wp_ajax_load_projectmessages', 'load_projectmessages');
Page Template PHP:
<form id="form-pm" method="post" enctype="multipart/form-data" action="">
<table>
<tr>
<td><textarea name="projectMessage" rows=3 id="project-message"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="send" value="send message"></td>
</tr>
</table>
</form>
my.js
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
if($.inArray(hash[0], vars)>-1)
{
vars[hash[0]]+=","+hash[1];
}
else
{
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
}
return vars;
}
$("#form-pm").submit(function(e) {
e.preventDefault();
var pID = getUrlVars()["id"];
$.ajax({
url: "admin-ajax.ajax_url",
type: "POST",
data: {
action: "load_projectmessages",
projectid: pID
},
success: function(data) { },
error: function(errorData) { alert(errorData); }
});
return false;
});
get_results
returns a php object,var_dump
the contents to see its structure.