Web Analytics Made Easy -
StatCounter Same page AJAX post to php variable - CodingForum

Announcement

Collapse
No announcement yet.

Same page AJAX post to php variable

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Same page AJAX post to php variable

    I'm trying to do an ajax post on the same page to basically create a dynamic div based on which a tag is clicked.

    Code:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    
    <script type="text/javascript">
    	$(function() {	
    		$(".clicker").click(function(){
    			var data = $(this).attr('id');
    			$.ajax({
    				type: "POST",
    				data: "db_data=" + data
    			});
    		});
    	});
    </script>	
    
    <a class="clicker" id="<?php echo "test1"; ?>" href="#">Click Here</a><br>
    <a class="clicker" id="<?php echo "test2"; ?>" href="#">Click Here</a><br>
    <a class="clicker" id="<?php echo "test3"; ?>" href="#">Click Here</a><br>
    <br>
    
    <?php
    	$variable = $_POST['db_data'];
    	echo "<p>Posted Data: '" . $variable . "'</p>";
    	//query mysql database using posted data as a where clause
    ?>

    I know I can do this by specifying an external ajax url, but I'm trying to do this on page if possible. Any help will be appreciated.
    Time after Time

  • #2
    Well the PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response. So you could basically accomplish that by this:
    Code:
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    
    <script type="text/javascript">
    	$(function() {	
    		$(".clicker").click(function(){
    			var data = $(this).attr('id');
    			$.ajax({
    				type: "POST",
    				data: "db_data=" + data,
    				success: function(){
    					//alert(data);
    					$('.responseDiv span').text(data);
    				}
    			});
    		});
    	});
    </script>	
    
    <a class="clicker" id="<?php echo "test1"; ?>" href="#x">Click Here</a><br>
    <a class="clicker" id="<?php echo "test2"; ?>" href="#y">Click Here</a><br>
    <a class="clicker" id="<?php echo "test3"; ?>" href="#z">Click Here</a><br>
    <br>
    
    <div class="responseDiv">Posted Data: <span></span></div>
    Stop making things so hard on yourself.
    i is tugbucket :: help raise tugburg :: Whitehaven Kiwanis

    Comment

    Working...
    X