• Resolved everyeurocounts

    (@everyeurocounts)


    Hi,

    I have the following code to pass a post_date to a php file to save it after a user selects a date. The problem is the event is not firing…i hard coded the values into the phpfile to check..Anyone any ideas?

    jQuery

    <script type="text/javascript">
    			var array = ["<?php
    echo $comma_seperated;
    ?>"];
    
    				jQuery(document).ready(function() {
    				jQuery('#MyDate').datepicker({
    				beforeShowDay: function(date){
    				var string = jQuery.datepicker.formatDate('yy/mm/dd', date);
    				return [ array.indexOf(string) == -1 ]
    				},
    				})
    
    				var bf = jQuery('#stotal').val();
    				var vf = parseInt(bf)*.21;
    
    				jQuery('#vat').val(vf);
    
    				vtf = (parseFloat(vf)+parseFloat(bf)).toFixed(2);
    
    				jQuery('#Total').val(vtf);
    			});
    
    				jQuery('#MyDate').change(function() {
    					$.post(
    					"https://xxxxxxx.com/www/wp-content/themes/gbs-prime-child-theme-merchant-dashboard/datesave.php",
    					{
    						MyDate: jQuery('#MyDate').val()
    
    					}
    					)});
    
    			</script>

    datesave.php

    <?php
    $posted_id = "408";
    //(isset($_POST['$posted_id'])) ? htmlspecialchars($_POST['posted_id') : 0;
    $temp_submitted_post_time = "12/13/2013"; 
    
    //(isset($_POST['MyDate'])) ? strtotime($_POST['MyDate']) : 0;
    
    $args = array(
        'ID' => $posted_id,
        'post_status' => 'temp',
        "edit_date" => true,
        'post_date' => date('Y-m-d H:i:s', $temp_submitted_post_time),
        'post_date_gmt' => gmdate('Y-m-d H:i:s', $temp_submitted_post_time)
    );
    wp_update_post($args);
    
    ?>

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    datesave.php cannot access WP functions because the WP environment is not loaded for that particular POST request. The best way to gain access to WP functions is to POST to wp-admin/admin-ajax.php, include data keyed ‘action’ with an arbitrary string value.

    Then from a plugin file or functions.php hook the action named ‘wp_ajax_’ plus your arbitrary string. Also hook ‘wp_ajax_nopriv_’ plus string for non-logged in users if need be. Your hook callback will then have access to all WP functionality.

    You’ve probably figured out this is a type of AJAX call. For more information see AJAX in Plugins.

    Thread Starter everyeurocounts

    (@everyeurocounts)

    Ok 1st clumsy attempt ??

    Two issues 1. The datepicker remains open after you select a date
    2. Its not working — do you need a wpdb call rather than update_post?

    jquery

    jQuery(document).ready(function() {
    				jQuery('#MyDate').datepicker({
    				minDate: '+2',
    				maxDate: new Date(2014, 1,28),
    				dateFormat: 'yy-mm-dd',
    				beforeShowDay: function(date){
    				var string = jQuery.datepicker.formatDate('dd/mm/yy', date);
    				return [ array.indexOf(string) == -1 ];
    				}
    				}).change(function($MyDate) {
    					var wdate = $('#MyDate').val();
    					$.post( ajaxurl ,
    					{
    						action: temp_save,
    						post_id: <?php echo $posted_id ?>,
    					  	post_date: wdate
                        });
    });
    
    				var bf = jQuery('#stotal').val();
    				var vf = parseInt(bf)*.21;
    
    				jQuery('#vat').val(vf);
    
    				vtf = (parseFloat(vf)+parseFloat(bf)).toFixed(2);
    
    				jQuery('#Total').val(vtf);
    				});
    add_action( 'wp_ajax_temp_save', 'temp_save' );
    function temp_save () {
    	$temp_submitted_post_time = $_POST['wdate'];
    	$posting = $_POST['post_id'];
    	global $wpdb;
    
    	$wpdb->query(
    	"
    	UPDATE $wpdb->posts
    	SET post_date = $temp_submitted_post_time
    	WHERE ID = $posting
    	"
    );
    
    }

    Moderator bcworkz

    (@bcworkz)

    I’ll wager a fair number of us had made the same clumsy error in the past!

    I’m not familiar with datepicker, perhaps it needs to be explicitly closed by script after selection?

    Either wp_update_post() or $wpdb should work in this context. I suspect your action hook is not even being called. You can test this by using error_log() to place a message in your error file. This is not a useful technique if your host does not give you immediate access to log files. You could simply echo a message and setup the jQuery .post() callback to place any server response in an alert box.

    In .post() your action value should probably be a quoted string: "temp_save" unless you’ve assigned the string to a variable of the same name somewhere. If not, your javascript error console should be showing an undefined variable error. It’s a good idea to check this when things don’t work. If this jQuery script is an external file, the <?php echo $posted_id ?> will not work. You need to pass values using wp_localize_script(). If this is part of a template file going between <script> tags you’re probably OK with this PHP segment.

    If this date picker could be used by non-logged in users, you also need to hook ‘wp_ajax_nopriv_temp_save’. These are the things I noticed, there could be more. Most likely the reason it’s not working is the string vs. variable issue.

    Once you get this working, you should also add in some security measures. Use and verify a nonce to ensure the request is from a legitimate calendar input. Sanitize the date input to foil any kind of SQL injection attack through the ‘wdate’ value.

    Thread Starter everyeurocounts

    (@everyeurocounts)

    thanks for this, it put me on the right track!

    The 1st issue was the datepicker wasn’t triggering a change event. There is a function within datepicker for this (onSelect) but i couldn’t get it to work with any functions including a simple alert(). In the end i found a post suggesting that you use onSelect to trigger a change event….

    Also i couldn’t get .post to work with the datepicker at all so i used .ajax.

    Ill add in the nounce after. Thanks for your help, brilliant as usual!

    page template:

    jQuery(document).ready(function () {
        jQuery('#MyDate').datepicker({
            minDate: '+2',
            maxDate: new Date(2014, 1, 28),
            dateFormat: 'yy-mm-dd',
            beforeShowDay: function (date) {
                var string =      jQuery.datepicker.formatDate('dd/mm/yy', date);
                return [array.indexOf(string) == -1];
            },
            onSelect: function (dateText) {//trigger the change event when value "selected"
                jQuery(this).change();
            }
        }).change(function () {
            var postid = '<?php echo esc_js($posted_id); ?>';
            var pdate = jQuery(this).val(); //select updated value
    
            jQuery.ajax({
                type: "POST",
                url: "/wp-admin/admin-ajax.php",
                data: {
                    action: 'tempsave',
                    postid: postid,
                    postdate: pdate,
                    status: 'waiting'
                },
                success: function (data) {//handle return
                    jQuery("#feedback").html(data);
                }
            });
    
        });
    });

    and in theme functions

    function tempsave(){
    	$postidcheck = strtotime($_POST['postdate']);
    
    	global $wpdb;
    
    	$postid = (int)$_POST['postid'];
    	$post_date = date('Y-m-d H:i:s',$postidcheck);
    	$status = $_POST['status'];
    	$time = date('y-m-d H:i:s');
    
    	if($wpdb->update('wp_posts',array(
    		'post_date'=>$post_date,
    		'post_date_gmt'=>$post_date,
    		'post_modified'=>$time,
    		'post_status'=>$status
    		),array ('ID'=>$postid
    		))===FALSE){
    
    		echo "Error";
    
    	}
    	else {
    			echo "Pending payment the date you selected has been reserved for 10 minutes";
    
    		}
    	die();
    }
    add_action('wp_ajax_addCustomer', 'addCustomer');
    add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');

    Thread Starter everyeurocounts

    (@everyeurocounts)

    small type in the above….

    should be

    add_action('wp_ajax_tempsave', 'tempsave');
    add_action('wp_ajax_nopriv_tempsave', 'tempsave');

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘jQuery .post save to database’ is closed to new replies.