Support

Account

Home Forums Backend Issues (wp-admin) CPT Select Field, AJAX Update Another and Show in Admin?

Solved

CPT Select Field, AJAX Update Another and Show in Admin?

  • Hello,

    I’ve been trying to solve this for a bit and can’t quite seem to get it working. I’m trying to make a CPT (Exams) where, after adding a new post, the Admin user selects a “Level” 1-5 (a ACF select field) and then some AJAX runs, collects some Questions (from a separate CPT) and then updates a “Questions” field on the Exam with the Post IDs of each Question.

    My problem seems to lie with programmatically assigning the Post IDs of the Questions to the Post Object field that is on the Exam.

    Here’s exactly what I’m doing: I’m going to “Add Exam”, selecting my “Level” (e.g. Level 1), clicking a button to run the AJAX, collecting the “Question” IDs, using update_field() to update the database value and then returning the IDs back to my new Exam post. I’ve checked the database after update_field is run in the AJAX and the Questions show up in the database, but if I Publish my Exam, the database questions get cleared out (because they don’t exist in the backend field).

    Here is my Javascript being run on the Exam CPT Admin:

    if( jQuery('body').hasClass('post-type-exams') ) {
    	//On Level Select, Run AJAX to Create Exam, store Question IDs (in Exam post) and then Generate the two PDFs
    	acf.addAction('ready', function(){ 
    		acf.unload.active = false;
    		var examID = acf.get('post_id'),
    			levelSelected = $('select#acf-field_5c9b8594fdf79').val();
    
    			$('div.acf-field-select.acf-field-5c9b8594fdf79').append('<div class="examOutput"><a href="#" class="button submitExam">Create Exam</a></div>');
    			$('a.button.submitExam').on('click', function(e) { //On Level Select Change
    				e.preventDefault();
    				//Loading Message
    				$('div.examOutput').html('<p class="examButtons">Creating Exam...
    ');
    				//Get Level Submitted
    				selectedExamLvl = $('select#acf-field_5c9b8594fdf79').val();
    				if( selectedExamLvl ) {
    					var examData = {
    						'action' : 'get_questions_for_exam', // the function name used in functions.php
    						'selectedExamLvl' : selectedExamLvl,
    						'examID' : examID
    					};
    					$.post(ajaxurl, examData, function(response) {
    						//$('#acf-field_5c9b994d45a1a-input').val(response).trigger('change');
    						var $question = $('select#acf-field_5c9b994d45a1a');
    							$question.focus();
    							$question.select2(response);
    
    						console.log(response);
    					}, "json"); 
    				}
    			});
    
    	});
    }

    Here’s the function it communicates with in functions.php:

    add_action( 'wp_ajax_get_questions_for_exam', 'get_questions_for_exam');
    add_action( 'wp_ajax_nopriv_get_questions_for_exam', 'get_questions_for_exam');
    function get_questions_for_exam() {
    	$examID = intval( $_POST['examID'] );
    	$examSelectedLevel = intval( $_POST['selectedExamLvl'] );
    
    	$modPrecent = array();
    	//Each Level has some Modules as well, this just collects them from an Options page
    	if(have_rows('level_' . $examSelectedLevel . '_modules', 'option')): //Repeater Name
    		while(have_rows('level_' . $examSelectedLevel . '_modules', 'option')): the_row();
    			$module = get_sub_field('module_number');
    			$percentage = get_sub_field('percentage_of_questions');
    			$modPrecent[$module] = $percentage;
    		endwhile; 
    	endif;
    
    	$questions = array();
    	//For Each Module in this Level, get the Requisite Number of Questions
    	foreach( $modPrecent as $mod => $percent ):
    		$questPerModule = get_random_questions($examSelectedLevel, $mod, $percent);
    		foreach( $questPerModule as $questID ) //Force Each Question into one big array (versus groups of arrays)
    			$questions[] = $questID;
    	endforeach;
    
    	//Update Questions Post Object field on Exam with Questions
    	update_field('field_5c9b994d45a1a', $questions, $examID);
    
    	echo json_encode($questions);
    
    	wp_die();
    }

    Anyone have any ideas?

  • I figured it out. Basically, in the AJAX response I iterated through each of the post ID’s of the Questions post type and added them to the select field of the post object ACF field as an <option>, which successfully populates the post object <ul> visible to admins after the Exam post is published (in theory, you could also add a <li> to the <ul> for each question if you needed to display it to the admin, but I didn’t).

    $.post(ajaxurl, examData, function(response) {
    	var questionSelect = $('select#acf-field_5c9b994d45a1a');
    	for(i=0; i<response.length; i++) {
    		var question_item = '<option value="'+response[i]+'" selected="selected" data-i="' + i + '">'+response[i]+'</option>';
    		questionSelect.append(question_item);
    	}
    	$('#publish').click(); //Save the Exam Post
    	console.log(response);
    }, "json");
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘CPT Select Field, AJAX Update Another and Show in Admin?’ is closed to new replies.