I am creating a custom wordpress plugin that it has a frontend form, and i want the data to be sent to the database with AJAX and also return a response to update the frontend table.
Everything looks good, till i click “submit” button
So my AJAX is :
$('#form').submit(function(event) {
var formData = {
'user' : $('input[name=userid]').val(),
'cardname' : $('input[name=card]').val(),
'setname' : $('input[name=setname]').val(),
'quantity' : $('input[name=quantity]').val(),
'multiverseid' : $('input[name=multiverseid]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : ''+base_url+'/website/wp-content/plugins/test/public/js/process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html', // what type of data do we expect back from the server
encode : true,
success : function(updatedTable) {
$('div#tableHolder').html(updatedTable);
}
})
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
The process.php file that will add the data is :
global $wpdb;
$wpdb->insert(
'wp_mycards',
array(
'user' => $_POST[userid],
'cardname' => $_POST[cardname],
'setname' => $_POST[setname],
'quantity' => $_POST[quantity],
'multiverseid' => $_POST[multiverseid]
)
);
$data="<table><tr><td>Image</td><td>Name</td><td>Set</td><td>Quantity</td></tr>";
$user_ID = get_current_user_id();
$cards = $wpdb->get_row( "SELECT * FROM $wpdb->wp_mycards WHERE user = ".$user_ID."" );
while ($row = mysql_fetch_assoc($cards)) {
$data.='<tr><td align="center"><img src="http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid='.$row[multiverseid].'&type=card" width="30" height="42" /></td><td align="left">'.$row[cardname].'</td><td align="center">'.$row[setname].'</td><td align="center">'.$row[quantity].'</td></tr>';
}
$data.="</table>";
echo $data;
-I run it at firefox and at firebug it gives me 500 internal server error-The post values are fine
AJAX is a bit different in WordPress. Like AJAX is used in the backend, WordPress is ready to use ajax and you only need to use the correct functions.
In WordPress, every AJAX request goes through the admin-ajax.php file in the wp-admin folder and you need some actions to hook into it. The AJAX request URL should point to this file. Read here a complete tutorial of how to do it: https://premium.wpmudev.org/blog/using-ajax-with-wordpress/
It can seems a bit complicated at first, buy once you get it is not so difficult. You are going to need this functions:
wp_ajax_my_action
wp_ajax_nopriv_my_action
wp_localize_script
AND in process.php