Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

INSERT fails when done with Ajax WordPress

  • SOLVED

I'm building a simple email subscription form and using ajax to call the function that stores the email in the database.

If I do it without ajax, everything works perfect, but the moment I try and use ajax to process the request, I get this error:
Fatal error: Call to a member function query() on a non-object

I have looked every where and cannot find a solution.

This is the function that stores the address:

function pn_store_address()
{
global $wpdb;
// Check for an email address in the query string
error_reporting (E_ALL ^ E_NOTICE);

$post = (!empty($_POST)) ? true : false;
if($post)
{
$address = trim($_POST['address']);

// Check address
if(!$address)
{
$error .= 'Please enter your email.';
}
if($address && !ValidateEmail($address))
{
$error .= "<strong>Error</strong>: An invalid email address was provided.";
}
if(!$error) // everything ok
{
$insert_address = $wpdb->query("INSERT INTO pn_mailinglist SET email='" . $address . "'"); // this is the line that sends the fatal error
if ($insert_address)
{
echo 'OK';
}
}
else
{
echo '<div class="notification_error">'.$error.'</div>'; // set up error div for jQuery/Ajax
}
}
}


Notice the line:


$insert_address = $wpdb->query("INSERT INTO pn_mailinglist SET email='" . $address . "'"); // this is the line that sends the fatal error


And this is the ajax function:

function pn_header_jquery()
{
$script_file_dir= WP_PLUGIN_URL.'/'.str_replace(basename( __FILE__),'',plugin_basename(__FILE__));
$submit = $script_file_dir . 'pn-ajax-request.php';
?>
<script type="text/javascript">
//<![CDATA[
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#pn_address_form").submit(function()
{
var str = $j(this).serialize();
$j.ajax(
{
type: "POST",
url: '<?php echo $submit; ?>',
data: str,
success: function(msg)
{
$j("#note").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK') // Message Sent? Show the 'Thank You' message and hide the form
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$j("#pn_address_fields").hide();
}
else
{
result = msg;
}

$j(this).html(result);
});
}
});
return false;
});
});
//]]>
</script>
<?php
}
add_action('wp_head', 'pn_header_jquery');

As I said before, everything works perfect if I don't use ajax, but with ajax, the Fatal Error pops up.

Ideas, please?

Answers (4)

2010-10-30

Oleg Butuzov answers:

global $wpdb;


Oleg Butuzov comments:

hm. no ... can you show whant wpdb contain there?

var_dump($wpdb); // null?


Pippin Williamson comments:

I've already done that. It's NULL.


Oleg Butuzov comments:

Can you tell me how do you run it? look like wpdb not initiated or unseted before your query runs....

take look to 'wp_ajax_'.$_POST['action']
hook to runn wp-admin ajax actions


Pippin Williamson comments:

How I run what? The sql query?

It definitely looks as though $wpdb is not getting initiated, though I have no idea why.


Oleg Butuzov comments:

nono.. i mean where this method/function located. hot do you iniate running of theiis insertion. is it plugin? is it functiosn.php? is it template file? where this code located?


Oleg Butuzov comments:

no no.. i mean where this method/function located. how do you initate running of this insert. is it plugin? is it functions.php? is it template file? where this code located?

of its in index.php in some if-else condition..,. sorry for mistakes. i didn't sleep well few days =)


Pippin Williamson comments:

It's all part of a plugin.


Oleg Butuzov comments:

understand...

$submit = $script_file_dir . 'pn-ajax-request.php';
// as far as i see there no wpdb variable in this file. it dosn't include wp-config.php so it jsut dosn't have the requeired object to work.

function pn_store_address()
{


inset in this code

something

function pn_store_address()
{
gloabl $wpdb;
if (is_null($wpdb)){
include PATH_TO_THE_DIR.'/wp-config.php';
}
// and cmmon! we got our rock wave.
// cheers


Oleg Butuzov comments:

gloabl $wpdb;
should be... of course
global $wpdb;

sorry

2010-10-30

Utkarsh Kukreti answers:

AJAX calls should be handled using wp_ajax action. http://www.wphardcore.com/2010/5-tips-for-using-ajax-in-wordpress/


Pippin Williamson comments:

I've tried doing that as well. Still no result.


Pippin Williamson comments:

I've looked at that page probably 10 times now, though I'm not really sure how to adapt my code to the techniques described there.

Can you help me out?

2010-10-30

Nilesh shiragave answers:

the global $wpdb must be added in the pn_header_jquery() function


function pn_header_jquery()
{
global $wpdb;
.
.
..


Pippin Williamson comments:

Nope, makes no difference. Remember, it works perfect without ajax, so the $wpdb global shouldn't be a problem.


Nilesh shiragave comments:

may be the wordpress functions are not loaded. as you are calling using ajax

try this i am assuming that your pn-ajax-request.php is inside a your plugin folder in plugins directory

like

/wp-content/plugins/your-plugin/pn-ajax-request.php

add following line inside the pn-ajax-request.php file

require_once( dirname(__FILE__) . '../../../../wp-load.php');


Nilesh shiragave comments:

if your file is located inside one more folder then you have to add one more ../ to that path.. and have to remove ../ if file is one folder up

2010-10-30

Maor Barazany answers:

In addition to what others said above, try also to add a ; add the end of the mySQL INSERT statement -




$insert_address = $wpdb->query("INSERT INTO pn_mailinglist SET email='" . $address . "';");


Pippin Williamson comments:

Nope, no change.