0

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 ) {
      alert(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.

1 Answer 1

1

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

<script>
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                 
jQuery.ajax({
  type: "POST",
  url: ajaxurl,
  dataType: "json",
  data: data,
  success: function(response) {
    console.log(response);
    ///response will return that you echo in function insert_data_customtable

  },
  error: function(response){
    alert(response);
  }
});

</script>

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
    $insertid=mysql_insert_id();

    echo json_encode($insertid);
    die();
}
3
  • 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, 2015 at 14:19
  • nevermind I didn't notice the 'action:method_name' part. Thanks man that was very helpful!
    – ccot
    Mar 18, 2015 at 14:36
  • Great ! As you find it useful Mar 19, 2015 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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