• Resolved Phi

    (@ppdoan)


    I would like to have JavaScript call a PHP function defined in a snippet but what would be the url for ajax?

    $(‘.button’).click(function() {
    $.ajax({
    type: “POST”,
    url: “some.php”,
    data: { name: “John” }
    }).done(function( msg ) {
    alert( “Data Saved: ” + msg );
    });
    });

    <?php
    function abc($name){
    //your code here
    }
    ?>

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter Phi

    (@ppdoan)

    This is one of my favorite plugins. No ideas from the author?

    Plugin Author Shea Bunge

    (@bungeshea)

    Hello,

    Sorry for not responding to you sooner.

    Here’s a basic example of how that might work:

    <?php
    
    add_action( 'wp_footer', function () { ?>
    
    	<script>
    
    	(function ($) {
    
    		$('.button').click(function() {
    			$.ajax({
    				type: 'POST',
    				url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
    				data: {
    					action: 'save_abc_data',
    					_ajax_nonce: '<?php echo wp_create_nonce( 'save_abc_data' ); ?>',
    					name: 'John'
    				}
    			}).done(function (msg) {
    				alert('Data Saved: ' + msg);
    			});
    		});
    
    	})(jQuery);
    
    	</script>
    
    <?php } );
    
    add_action( 'wp_ajax_save_abc_data', function () {
    
    	check_ajax_referer( 'save_abc_data' );
    
    	$name = $_POST['name'];
    
    	// do something with $name here
    
    } );

    There are a bunch of changes that should be made for this depending on where you will be using it (in the admin area, for logged-out users, etc), but it’s a good foundation to build from. I would recommend taking a look at the AJAX in Plugins Codex page for more information.

    Thread Starter Phi

    (@ppdoan)

    Thank you very much!!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Call code snippet from javascript’ is closed to new replies.