Вопрос

Wordpress way to make an Ajax call in a custom page template is unbelievable complicated. I cant get it to run at all without crashing my whole site. Why I need to do it that way? My other Ajax calls are not needing this complicated and complex way too.

So what I am trying to do:

I want to add a feature to the Shop that Resellers can enter there ID and reorder new bags for there Shops. So long so good.

I got my landing page:

    <?php
    /*
    Template Name: 
    */
    ?>
    <?php
        get_header();
    ?>
    <section id="main" class="reseller-page">

    <form action="<?php echo get_stylesheet_directory_uri(); ?>/reseller.php" method="GET" id="resellerform">
        Reseller ID: <br><input type="text" name="rid" id="rid">
        <button id="resellercheck">SUCHEN</button>
    </form> 
    <div id="resellerwrapper" style="display: none;">
        <div id="resellerinfo"></div>

        <div id="resellerorder" style="display: none;">
            <h2>Bestellformular:</h2>
            <?php
            $args = array('post_type' => 'product', 'posts_per_page' => -1, 'product_cat' => 'tabak-taschen');
            query_posts($args);
            if (have_posts()):
                echo '<div id="reseller-select-wrapper"><select id="artikelselector">';
                while (have_posts()) : the_post();
                    echo '<option value="' . $product->get_sku() . ': ' . $product->get_title() . '" data-type-href="' . get_permalink() . '">' . $product->get_sku() . ': ' . $product->get_title() . '</option>';
                endwhile;
                echo '</select>Menge: <input id="reseller-menge" type="text" class="input-text"><button value="hinzufügen" id="reseller-add-to-form">+</button></div>';
            endif;
            ?>
            <form action="" method="POST" id="reseller-bestell-liste">
                <ul>

                </ul>
                <textarea name="nachricht" id="reseller-msg"></textarea>
                <input type="submit" id="reseller-send-order" value="bestellen" title="verbindliche Bestellung" />
            </form> 

        </div>
    </div>
</section>
<?php
get_footer();
?>

then the checkresellerid.php that checks the database if the RiD(ResellerID) is in the DB:

<?php
//header('Content-Type: text/html; charset=utf-8');
include 'db_connect.php';

// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

if (isset($_GET['rid'])) {
//  $rid = "R10369";
$rid = $_GET['rid'];


$result = mysqli_query($con, "SELECT rid FROM reseller WHERE rid = '" . $rid . "'");

$ergebnis = mysqli_num_rows($result);

if ($ergebnis == 1) {
    $RJSON = [];
    $RQUERY = mysqli_query($con, "SELECT * FROM reseller WHERE rid = '" . $rid . "'");
    while ($row = mysqli_fetch_array($RQUERY, MYSQL_ASSOC)) {

        $RJSON[] = array(
//          'rid' => $row['rid'],
            'name' => $row['name'],
            'adresse' => $row['adresse'],
            'email' => $row['email'],
            'phone' => $row['phone']

        );
    }


    echo json_encode($RJSON);

} else {
    echo 'false';
}

mysqli_close($con);
}
?>

When I enter something in the Input Field(no matter if its in the DB or not) I get a 500 Internal Server Error. But why my other Ajax calls on the Site like my "Love a product" feature in the woocommerce shop loop are working but not this little fella? on my localhost is everything runnning correctly. Did it has anything to do because its a custom php file(template page file)?

Check the Example Page >>> Here <<<

I tried registering a function in functions.php but that crashed the whole site. How can I pack my php script in this functions.php and call it correctly? Why is it even neccesary to make it that complicated? I am googling this for hours and tryied many ways, nothing works...

Thanks for any help and sorry for my bad englisch.

EDIT:

my functions.php looks like this:

<?php

/****************************************
Theme Setup
*****************************************/

require_once( get_template_directory() . '/lib/init.php' );
require_once( get_template_directory() . '/lib/theme-helpers.php' );
require_once( get_template_directory() . '/lib/theme-functions.php' );
require_once( get_template_directory() . '/lib/theme-comments.php' );


/****************************************
Require Plugins
*****************************************/

require_once( get_template_directory() . '/lib/class-tgm-plugin-activation.php' );
require_once( get_template_directory() . '/lib/theme-require-plugins.php' );

add_action( 'tgmpa_register', 'mb_register_required_plugins' );
add_theme_support( 'woocommerce' );


/****************************************
Misc Theme Functions
*****************************************/

/**
 * Define custom post type capabilities for use with Members
 */
function mb_add_post_type_caps() {
    // mb_add_capabilities( 'portfolio' );
}

/**
 * Filter Yoast SEO Metabox Priority
 */
add_filter( 'wpseo_metabox_prio', 'mb_filter_yoast_seo_metabox' );
function mb_filter_yoast_seo_metabox() {
    return 'low';
}


function checkResellerId(){
    include 'db_connect.php';
    wp_localize_script( 'function', 'checkResellerId', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

    // Check connection
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    if (isset($_GET['rid'])) {
    //  $rid = "R10369";
        $rid = $_GET['rid'];


        $result = mysqli_query($con, "SELECT rid FROM reseller WHERE rid = '" . $rid . "'");

        $ergebnis = mysqli_num_rows($result);

        if ($ergebnis == 1) {
            $RJSON = [];
            $RQUERY = mysqli_query($con, "SELECT * FROM reseller WHERE rid = '" . $rid . "'");
            while ($row = mysqli_fetch_array($RQUERY, MYSQL_ASSOC)) {

                $RJSON[] = array(
    //              'rid' => $row['rid'],
                    'name' => $row['name'],
                    'adresse' => $row['adresse'],
                    'email' => $row['email'],
                    'phone' => $row['phone']

                );
            }


            echo json_encode($RJSON);

        } else {
            echo 'false';
        }

        mysqli_close($con);
    }
}

add_action( 'wp_ajax_nopriv_product_s', 'checkResellerId' );
add_action( 'wp_ajax_product_s', 'checkResellerId' );

function resellerMail(){
    wp_localize_script( 'function', 'resellerMail', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
    $zieladresse = 'xxx';

    $absenderadresse = 'xxxReseller';

    $absendername = 'xxxReseller';

    $betreff = 'Reseller-Bestellung';

    $trenner = ":\t";

    if ($_SERVER['REQUEST_METHOD'] === "POST") {

            $header = array();
            $header[] = "From: ".mb_encode_mimeheader($absendername, "ISO-8859-15", "Q")." <".$absenderadresse.">";
            $header[] = "MIME-Version: 1.0";
            $header[] = "Content-type: text/plain; charset=ISO-8859-15";
            $header[] = "Content-transfer-encoding: 8bit";

        $mailtext = "";

        foreach ($_POST as $name => $wert) {
            if (is_array($wert)) {
                        foreach ($wert as $einzelwert) {
                                $mailtext .= $name.$trenner.$einzelwert."\n";
                }
            } else {
                $mailtext .= $name.$trenner.$wert."\n";
            }
        }

        mail(
            $zieladresse, 
            mb_encode_mimeheader($betreff, "ISO-8859-15", "Q"), 
            $mailtext,
            implode("\n", $header)
        ) or die("Die Mail konnte nicht versendet werden.");
        echo $mailtext; // nur check für ajax response, später wieder entfernen!!!!
        echo 'Ihre Bestellung wurde an uns versandt.<br>Sie werden telefonisch von uns kontaktiert um die Bestellung zu bestätigen.';
        exit;
    }

//header("Content-type: text/html; charset=utf-8");
}

add_action( 'wp_ajax_nopriv_product_s', 'resellerMail' );
add_action( 'wp_ajax_product_s', 'resellerMail' );

Screen of the 500 Error: ![Screenshot 500 Internal error][2]

Это было полезно?

Решение

Ok so there's lots of separate problems with this

The add_action() blocks look correct so that's good!

However:

How have you included the javascript which runs the ajax action? To use wp_localize_script() the script must be loaded using wp_enqueue_script() or wp_register_script().

wp_localize_script() should be called just after the script is registered, normally just after wp_enqueue_script(). At the moment you are not posting to admin-ajax.php, but to a file in your theme directory.

If you want you can print a <script> in the head with an ajaxurl var and use that instead, but this isn't best practise.

Once we've called checkResellerId(), there's no need for opening your own database connection if you are storing this data in the wordpress database, you can use $wpdb for your SQL queries.

You are looking for $_GET but if your javascript matches you form it will be in $_POST. Use $_REQUEST instead.

MAJOR PROBLEM: You are passing $_GET data straight into your sql query, this leaves you wide open to sql injection! Bad.

Depending on your php version you might not be able to call $RJSON = []; use array() instead.

Before echo json_encode you should send json headers using header( "Content-Type: application/json" );

I haven't looking into the other function.


I suggest making a very simple ajax action and getting this working first before trying to run your more complicated logic, see this tutorial.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top