Philipp Seven
Philipp Seven

Reputation: 3

Wordpress: run php script via jquery

I try run php script from external file on wordpress site.

Example:

jQuery:

jQuery('.button').click(function(){
  jQuery(this).parent('.entry_card').append('<div class="static"></div>');
  jQuery(this).parent('.entry_card').children('.static').load("insert.php");
});

insert.php:

<?php 
echo date("d.m.Y h:i:s"); //for testing

echo the_title(); //wordpress post title

if( get_field('xxx') ) { insert_cform('1'); } //some order form
else { insert_cform('2'); }
?>

Date is inserted correctly, but rest of the script don't working. I'm noob in coding, sorry if my question is stupid.

Upvotes: 0

Views: 748

Answers (2)

Adam
Adam

Reputation: 6783

As @vch said in a comment, if you have a simple php file that you call directly then the wordpress framework is not loaded and you cannot use wordpress functions in that file.

I think what you want to do is write a wordpress plugin which exposes an ajax action you can then call from your javascript to get the desired data. There is information in the codex about how to create ajax actions in plugins.

That said, if you call your ajax action you are not necessarily in the wordpress loop, so I'm not sure you can use the_title() anyway - the ajax call (as your .load() ajax call) is a new request so how does the server know which the current post is? You might need to get the post id in your main page and set it as data soemwhere and send it in the ajax call.

Upvotes: 0

Machavity
Machavity

Reputation: 31644

Wordpress AJAX isn't handled like that. There's nothing loading your WordPress environment so functions like the_title() don't exist (you're probably getting a fatal error there). Typically you create a plugin and set up your AJAX inside

jQuery(document).ready(function($) {

    var data = {
        'action': 'my_action',
        'whatever': 1234
    };

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    $.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

And then your plugin looks like this

<?php 

add_action( 'wp_ajax_my_action', 'my_action_callback' );

function my_action_callback() {
    echo the_title();
    die();
}

Upvotes: 1

Related Questions