I created a custom php file, put it in my folder. The files does insert some data to the database to a custom table i created.

require wp_path() . "/wp-load.php";
global $wpdb;
$favorite_table = $wpdb->prefix . "fav";
$wpdb->insert( $favorite_table, array( 'link' => $_POST['fav_link'], 'title'=> $_POST['title']) );
$lastid = $wpdb->insert_id;

echo $lastid;
function wp_path() {
    if (strstr($_SERVER["SCRIPT_FILENAME"], "/wp-content/")) {
        return preg_replace("/\/wp-content\/.*/", "", $_SERVER["SCRIPT_FILENAME"]);
    return preg_replace("/\/[^\/]+?\/themes\/.*/", "", $_SERVER["SCRIPT_FILENAME"]);

what is calling this php file is a jquery ajax function from within my theme:

$.post(WPURLS.theme_directory_uri+'/favorite/fav.php', data).done(function(data ) {
 }).fail(function() {      

This insert into the database but doesn't return anything in the response, data is blank. while if i manually pasted the URL in browser (GET) i can see the $lastid displayed.

What am I doing wrong? I need to retrieve the response data $lastid.


You are going on the wrong way.This will create difficulties and is NOT WORDPRESS STANDARD.Wordpress has a ajax technique to implement this.

Call the ajax from your page

var data = {
    'action': 'insert_data_customtable',
    'first_name': firstname,
    'last_name': lastname

// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php                 
  type: "POST",
  url: ajaxurl,
  dataType: "json",
  data: data,
  success: function(response) {
    ///response will return that you echo in function insert_data_customtable

  error: function(response){


And write this in your functions.php

add_action("wp_ajax_nopriv_insert_data_customtable", "insert_data_customtable");
dd_action("wp_ajax_insert_data_customtable", "insert_data_customtable");

function insert_data_customtable(){
    //Here is your code for insert into table

    echo json_encode($insertid);
  • but url:ajaxurl alone will not point to the php function that is inserting to my table. My url is: WPURLS.theme_directory_uri+'/favorite/fav.php' , i need to reach fav.php – ccot Mar 18 '15 at 14:19
  • nevermind I didn't notice the 'action:method_name' part. Thanks man that was very helpful! – ccot Mar 18 '15 at 14:36
  • Great ! As you find it useful – Rocker Maruf Mar 19 '15 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.