I’ve encountered a problem with a custom shortcode i created, which just outputs a table via PHP-Echo.
This shortcode just serves as a search form and posts the data to another site.
Everytime i insert the shortcode in a wp-site and update it, i get "Invalid JSON-Response".
I’ve tried some troubleshooting and found out that:
The problem just persists with that one shortcode, another custom created shortcode does not error at all. So i guess the problem really "just" lies within the shortcodes-function.
<?php
function function_name() {
require( WP_PLUGIN_DIR.'/<dir>/assets/runtime/shortcode/function_name/form.php' );
global $wpdb;
$filter = $_POST['filter'];
$job_table_name = '<tableName>';
// Check if the Job-Table has Entries
if ( $wpdb->get_var( 'SELECT * FROM '.$job_table_name ) == null OR $filter == null ) {
exit;
}
// Run The Query With Selected Filter
$query = 'SELECT id, column1, column2, column3 FROM '.$job_table_name." WHERE column1 LIKE '%$filter%' OR id LIKE '$filter'";
// echo $query;
$results = $wpdb->get_results( $query, ARRAY_A );
//echo var_dump( $results );
// Display The Jobs From The Result Set
echo '<table>';
echo '<tr>';
echo '<th> column1</th>';
echo '<th> column2</th>';
echo '<th> column3</th>';
foreach ( $results as $result ) {
echo '<tr>';
// echo "<td><a href=.site_url().'/displayjobs?id=".$result['column1'].'>'.$result['column2'].'</a></td>';
?>
<td>
<a href = '<?php echo site_url()?>/displayjobs?id=<?php echo $result["id"]?>'><?php echo $result['column1']?></a></td>
<?php
echo '<td>'.$result['column2'].'</td>';
echo '<td>'.$result['column3'].'</td>';
}
echo '</table>';
}
?>
Here’s the form i’m rendering:
<form method='POST'>
<input type='text' name='filter' placeholder='someval ...'/>
<input type='submit' value='someval ...'/>
</form>
Any ideas on why it fails?
2
Answers
I think i've solved the problem myself:
Since I've done that, there are no errors anymore and the plugin can be displayed just fine.
Looking good!
So it no longer returns the "invalid JSON response"?
You should consider using $wpdb->prepare and sprintf variables for security. Illustrated below. (I’m not sure on the SQL LIKE wildcards. Codex says "All % characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as %%." … you’ll have to experiment.)
Also, when using output buffer, you can simplify and eliminate some of the ‘echo’ commands, as illustrated below.
Other updates below:
(Aside from the updates – this is basically your script.)