Search code examples
ajaxwordpressvariablestextsend

Wordpress ajax not passing text variable


I use ajax code from the wordpress official site. Everything works fine if I send numbers, if I send a text variable it doesn't send?

If I change the text with numbers everything works and stores in the database, if I type the text then it sends 0.

index.php

<?php
add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here

function my_action_javascript() { ?>
    <script type="text/javascript" >
    jQuery(document).ready(function($) {

        var data = {
            'action': 'my_action',
            'whatever': 12345, 
            'notes': sometext, / Text is not sent???
            'courseid': 666555444
        };

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

function.php


<?php 

add_action( 'wp_ajax_my_action', 'my_action' );

function my_action() {
    global $wpdb; // this is how you get access to the database

    $whatever = intval( $_POST['whatever'] );
    $notes = intval( $_POST['notes'] );
    $course_id = intval( $_POST['courseid'] );

    $whatever += 10;

        echo $whatever;
        global $wpdb;
        $wpdb->insert(
            $wpdb->prefix. 'lms_enroll',
            [
                 'course' => $notes,
                 'student' => $whatever,
                 'course_ID' => $course_id,
            ]
         );

    wp_die(); // this is required to terminate immediately and return a proper response
}


Solution

  • The problem with your code is that you're converting the string in $_POST['notes'] into an integer:

    $notes = intval( $_POST['notes'] );
    

    Just remove the call to intval to get the string as expected:

    $notes = $_POST['notes'];