WordPress.org

Ready to get started?Download WordPress

Forums

Ajax function not returning any results (2 posts)

  1. iamjonas
    Member
    Posted 2 years ago #

    Hello everyone!

    Im trying to create an ajax call when I click a link, the link is the post thumbnail, and the result should show the post content.

    When I use admin-ajax.php it works fine, but the problem then is that the URL doesnt become accessable.

    This is my ajaxcall

    $.ajax({
    			//url: admin_url +  '/wp-admin/admin-ajax.php',
    			url: href + '?action=ajax',
    			dataType: 'json',
    			data: {
    				//action: 'ajax',
    				post_id: post_id
    			},
    
    			success: function(data) {
    				console.log("Succes");
    				row.before('<div id="case" class="twelve columns omega alpha"></div>');
    				$("#case").slideUp(1);
    				$("#case").html(data).slideDown(speed);
    
    				$("#header, #featured, .row").animate({'opacity': halfOpacity}, speed);
    				return false;
    			},
    			error: function() {
    				console.log("Error");
    				window.location = href;
    			}
    		});

    And this is the php in the functions.php

    function ajax() {
    
    		global $wpdb;
    		global $post;
    		$id = $_GET['post_id'];
    
    		$querystr = "
    		    SELECT $wpdb->posts.*
    		    FROM $wpdb->posts
    		    WHERE $wpdb->posts.ID = $id
    		";
    
    		$post = $wpdb->get_results($querystr);
    
    		$response = $post[0]->post_content;
    		$response = json_encode($response);
    
    		header( "Content-Type: application/json" );
    		echo $response;
    		exit;
    	}
  2. Hax
    Member
    Posted 2 years ago #

    you need to rename your php function to something like
    wp_ajax_ajax(); the function needs to be prefix with "wp_ajax". Make sure you un-comment and change the action name on the javascript also.

    One more thing you need "?action=ajax" in the javascript url
    for more information http://codex.wordpress.org/AJAX_in_Plugins

Topic Closed

This topic has been closed to new replies.

About this Topic