简体   繁体   中英

How to insert data of fields generated dynamically into database wordpress plugin

I am running a form which is posting data to database in such a way that every question field is having many options that are generated dynamically, the question query is working good but the option that are created dynamically(that query runs to 500) is not working.

front end:

<input name="text" placeholder="Question text" type="text" id="text"></br>
    <input type=\"text\" placeholder=\"text\" name=\"option_text[]\" class=\"fieldname\" />
    <input type=\"number\" placeholder=\"0\" name=\"option_score[]\" class=\"fieldtype\" />

jquery: which is functioning correctly

function abc(){

var fName = new Array();

jQuery('.fieldname').each(function(index, value){
       fName.push(jQuery(this).val());
})

var fType = new Array();

jQuery('.fieldtype').each(function(index, value){
       fType.push(jQuery(this).val());
})

jQuery.ajax({
        type: 'POST',
        url: "<?php echo admin_url('admin-ajax.php'); ?>",
        data: { action: 'savedataques', text: document.getElementById('text').value, textopt: fName, score: fType},              
        success: function(data){
            alert('success');
alert('data');
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });
}

The Php code: the data query is good but the dataop query runs int the error of blank page.

    function savedataques(){
    global $wpdb;

            $data = ($wpdb->insert('wp_dbquestions', array(

                        'text'        => $_POST['text'],
                    )
            ));


 $lastid = $wpdb->insert_id;
            echo $lastid;

this is where the problem is:

$dataop = ($wpdb->insert('wp_questoptions', array(
                'question_id'        => $lastid
                'text'        => $_POST['textopt'],
                'score'        => $_POST['score'],
            )
    ));

        }

    exit;

die();
return true;
}
//
add_action('wp_ajax_savedataques', 'savedataques'); 
//add_action('wp_ajax_nopriv_savedataques', 'savedataques');

this is the solution: just need to apply a foreach on all the dynamically generated options

    $i=0;
    $optiontext = $_POST['textopt'];
    foreach($optiontext as $key => $val ){

        $score = $_POST['score'][$i];
        $textopt = $_POST['textopt'][$i];
        $i++;

then the query:

        $data = ($wpdb->insert('wp_questoptions', array(
                    'question_id' =>  $lastid,
                    'text'        => $textopt,
                    'score'        => $score,
                )
        ));

done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM