Yet another WordPress Ajax 400 Bad Request problem - wordpress

I am certain I am making a basic mistake here. I am getting the lovely 400 Bad Request response from WordPress when I try to make an Ajax call. I have one Ajax call that works, and this one that does not. I have looked at several posts both here and elsewhere, but remain stumped as to where I have erred.
Okay, the relevant code. First, here is how I do the add_action and script registration:
if ($_GET["page"] == "krudkat_data_structures") {
add_action("wp_ajax_krud_save_new_connection", "krud_save_new_connection");
}
// Other Stuff, for the Ajax call that works.
if ($_GET["page"] == "krudkat_data_structures") {
wp_register_script("krud_data_structures", plugin_dir_url( __DIR__ ) . "/js/dataStructures.js", array("jquery"));
wp_localize_script("krud_data_structures", "krudAjax", array( "ajaxurl" => admin_url("admin-ajax.php")));
wp_enqueue_script("krud_data_structures");
}
This sits in a function outside of a class. My JS call is like this:
var krudNewConnect = { action:"krud_save_new_connection",
dbname:$("#krud_new_dbname").val().trim(),
dbhost:$("#krud_new_dbhost").val().trim(),
dbconnect:$("#krud_new_dbconnect").val().trim(),
dbusername:$("#krud_new_dbusername").val().trim(),
dbpassword:$("#krud_new_dbpassword").val() };
$.post(krudAjax.ajaxurl, krudNewConnect, function(newConnectData) {
console.log(newConnectData);
});
Finally, my PHP method is, thus far, very simple:
function krud_save_new_connection() {
$dbname = $_POST["dbname"];
$dbhost = $_POST["dbhost"];
$dbconnect = $_POST["dbconnect"];
$dbusername = $_POST["dbusername"];
$dbpassword = $_POST["dbpassword"];
$dbport = 0;
$dbsocket = '';
if (!empty($dbconnect)) {
if (is_numeric($dbconnect)) {
$dbport = $dbconnect * 1;
} else {
$dbsocket = $dbconnect;
}
}
echo "Port: " . $dbport . "\nSocket: " . $dbsocket;
wp_die();
}
This is not expected to work when somebody is not logged in as an admin, so I omitted the no_priv add_action. I am certain this is not the problem; I did add that into my code and it had no impact.
What newbie mistake have I made? :)

First, enqueue the script and then localize the script for ajax. It will fix the issue. Check the codex: https://codex.wordpress.org/AJAX_in_Plugins

Related

How to trash a post if it contains specific explicit words?

I am trying to write a wordpress filter that would change the post status to trash if it contains explicit words, but I can't manage to get it to work. Could you please help me?
This is what I got so far:
add_filter('wp_insert_post_data', 'delete_invalid_posts', '99');
function delete_invalid_posts($data) {
$false_titles = array("*****", "******");
if (in_array($data['post_title'], $false_titles) {
// If post data is invalid then
$data['post_status'] = 'trash';
}
return $data;
}
If you want to search the title for Explicit Words, you may use this code:
add_filter('wp_insert_post_data', 'delete_invalid_posts', 99);
function delete_invalid_posts($data) {
$false_titles = array("*****", "******");
$title_arr = explode(' ', $data['post_title']);
$found = array_intersect($false_titles, $title_arr);
if (!empty($found)) {
$data['post_status'] = 'trash';
}
return $data;
}
I've not tested the code, So try it and if you have any question don't hesitate to ask.
I might be wrong, but I think you are missing a closing parentheses here...?
Are you getting an error message?
if (in_array($data['post_title'], $false_titles) // <--- HERE should be a ")"
Like I said, I could be mistaken or there may be other issues...

$_GET is empty after defining a rewrite rule

Hello Wordpress ninjas,
I am new to wordpress develpoment. I define a rewrite rule (with a tag), similar to what you can find in examples here and here.
$wp_rewrite->add_rewrite_tag('%filterx_location%', '([^&/]+)', 'filterx_location=');
$wp_rewrite->add_rule('property-location/(.+)$','index.php?post_type=property&filterx_location=$matches[1]', 'top');
Now, the problem is, that when the query is completed (the page is shown), the filterx_location paramater is not set. In fact, var_dump($_GET) gives me an array(0) { }.
I have a black out or something, seems like something simple I miss here, just cannot figure it out :-/
Any help is much appreciated!
UPDATE
what is even stranger is that when I generate rewrite rules with:
$wp_rewrite->add_rewrite_tag('%filterx_location%', '([^/]+)', 'filterx_location=');
$permalink_prefix = 'property-location';
$permalink_structure = '%filterx_location%/';
$rewrite_rules = $wp_rewrite->generate_rewrite_rules($permalink_prefix.'/'.$permalink_structure, EP_ALL, true, true, true, true, true);
I see a bunch of generated urls matches and redirects, if I print them. One of them is:
property-location/([^/]+)/page/?([0-9]{1,})/?$ => index.php?filterx_location=$matches[1]&paged=$matches[2]&post_type=property
I add all the generated urls with:
foreach($rewrite_rules as $regex => $redirect) {
if(strpos($redirect, 'attachment=') === false) {
//add the post_type to the rewrite rule
$redirect .= '&post_type=property';
}
//turn all of the $1, $2,... variables in the matching regex into $matches[] form
if(0 < preg_match_all('#\$([0-9])#', $redirect, $matches)) {
for($i = 0; $i < count($matches[0]); $i++) {
$redirect = str_replace($matches[0][$i], '$matches['.$matches[1][$i].']', $redirect);
}
}
//add the rewrite rule to wp_rewrite
$wp_rewrite->add_rule($regex, $redirect, 'top');
}
And If I go to the URL /property-location/madrid/page/2/ then the query_vars correctly do have ["paged"]=> int(2). But the filterx_location is totally ignored!
Ok, I got it working, in a strange turn of events. First I replaced
$wp_rewrite->add_rewrite_tag('%filterx_location%', '([^/]+)', 'filterx_location=');
with:
add_rewrite_tag('%filterx_location%', '([^/]+)', 'filterx_location=');
I noticed those are two different things. I took a look into the wordpress code of add_rewrite_tag:
function add_rewrite_tag($tagname, $regex) {
//validation
if ( strlen($tagname) < 3 || $tagname[0] != '%' || $tagname[strlen($tagname)-1] != '%' )
return;
$qv = trim($tagname, '%');
global $wp_rewrite, $wp;
$wp->add_query_var($qv);
$wp_rewrite->add_rewrite_tag($tagname, $regex, $qv . '=');
}
I thought the "add_query_var" part might be essential.
But it still did not work!
So what I did finally was add another call to add_query_var() after the add_rewrite_tag() call:
add_rewrite_tag('%filterx_location%', '([^/]+)', 'filterx_location=');
$wp->add_query_var('filterx_location');
and only then everything started to work. Initially I assumed that $_GET should be holding my variable, but then even calls to get_query_var('filterx_location') were empty. Now it get the right stuff.

Module field with feeds, module generating data

I have an issue with triming a field before it is saved. I wanted to use substr(), or regex() with preg_match(). I have built a Drupal 7 module, but it can't work at all. I have tried using the trim plugin in feeds tamper module, but it doesn't seem to work. The data I am using is from a feed from Google Alerts. I have posted this issue here.
This is what I have done so far, and I know my regular expression is wrong; I was trying to get it do anything, just to see if I could get it to work, but I am pretty lost on how to add this type of function to a Drupal module.
function sub_node_save() {
$url = $node->field_web_screenhot['und'][0]['url'];
$url = preg_match('~^(http|ftp)(s)?\:\/\/((([a-z0-9\-]*)(\.))+[a-z0-9]*)($|/.*$)~i',$url );
$node->field_web_screenhot['und'][0]['url'] =$url;
return ;
}
I used the Devel module to get the field.
If there's an easy way to use substr(), I would consider that or something else.
Basically, I just want to take the Google redirect off the URL, so it is just the basic URL to the web site.
Depending on your question and later comments, I'd suggesting using node_presave hook (http://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_presave/7) for this.
It's called before both insert (new) and update ops so you will need extra validations to prevent it from executing on node updates if you want.
<?php
function MYMODULE_node_presave($node) {
// check if nodetype is "mytype"
if ($node->type == 'mytype'){
// PHP's parse_url to get params set to an array.
$parts = parse_url($node->field_web_screenhot['und'][0]['url']);
// Now we explode the params by "&" to get the URL.
$queryParts = explode('&', $parts['query']);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
//valid_url validates the URL (duh!), urldecode() makes the URL an actual one with fixing "//" in http, q is from the URL you provided.
if (valid_url(urldecode($parms['q']))){
$node->field_web_screenhot['und'][0]['url'] = urldecode($parms['q']);
}
}
}

recursive function using joomla db object

I want to write a recursive function in joomla that get all the child level categories using a category id using joomla's jmodel's db object.Following is my code that I have written:
function getChildCategories($type){
$query = "SELECT id FROM #__cd_categories WHERE parent_id='$type'";
echo $query."<br/>";
$this->_db->setQuery($query);
$list = $this->_db->loadObjectList();
if ($this->_db->getErrorNum()) { echo $this->_db->stderr(); return false; }
foreach($list as $record){
$this->childCategories[]= $record->id;
echo $record->id."<br/>";
return $this->getChildCategories($record->id);
}
return true;
}
So now problem is that, in joomla we use $this->_db_setQuery method and $this->_db->loadObjectList method , so in recursive call the result set, I think it overwrite, I think because the object is same. So can any one tell the way that how to overcome this problem? If you can solve this by using loop even that would be also very helpful for me.
I also think that once values are assigned to $list variable then that over write shouldn't be problem.So seems strange.Please tell if some one can tell me the way to do it?
thanks in advance
I don't think the issue is with the database object getting overwritten. It has been a bit since I have been struggling with recursive functions but I think the issue is with assigning the $list variable.
Should you not be returning that variable instead of boolean true like this:
function getChildCategories($type) {
$query = "SELECT id FROM #__cd_categories WHERE parent_id='$type'";
$this->_db->setQuery($query);
$list = $this->_db->loadObjectList();
if ($this->_db->getErrorNum()) { echo $this->_db->stderr(); return false; }
if ($list) {
foreach($list as $record){
$list->childCategories = $this->getChildCategories($record->id);
}
return $list;
} else {
return;
}
}

$wpdb->posts not being accepted by Wordpress Pugin

Hope you all have been doing great...
I am here today to look for an answer to my issue...
I created a plugin and activated it, it does not create a table etc just simple php script.
<?php
/*
Plugin Name: F
Plugin URI: h
Description: T
Author: D
Author URI: h
*/
$server = "localhost";
$user = "admin";
$password = "";
$db = "wordpress";
$con = mysql_connect($server,$user,$password);
if (!$con) {
die("database connection error");
} else
{
mysql_select_db($db, $con);
$results = mysql_query("SELECT ID, post_title FROM wp_posts "
. "WHERE "
. "post_status = 'publish' "
);
while($row = mysql_fetch_array($results))
{
echo $row['post_title'];
}
}
the autocomplete code is as below
$("#imageSearch").autocomplete("<?php echo bloginfo('wpurl')."/wp-content/plugins/foxycomplete/"; ?>foxycomplete.php", {
dataType: "json",
parse: function(data) {
return $.map(data, function(row) {
return {
data: row,
value: row.title,
result: $("#imageSearch").val()
}
});
}
}).result(function(e, item) {
location.href = link(item);
});
});
this is working but I am pretty sure that this is not the right way. I am not able to use the wp functions is the plugin script and also this seems unsafe and prone to hacking...
could anyone please help how I can get a php file to feed the autocomplete that can access wop functions and is safe?
Thanks a lot!
There's no such thing as a Plugin Page. The code above should probably be wrapped in a function and called from somewhere in a WordPress context, or it should be used in an action or a filter.
If you are accessing the plugin page directly rather than from within Wordpress, the problem might be that the $wpdb is not being initialized. This is done in the WordPress header, which is normally included on the page if you are inside of a Wordpress template. Try including wp-blog-header.php in your script with something like this:
include_once(‘wp-blog-header.php’);

Resources