Question

I am learning php and Ajax while creating a plugin for wordpress, managed to finish it up. It counts number of clicks and impressions that all banner on sites gets. U place banners through that plugin etc...anyway I just finished adding number of impressions that each banner gets. It works without any problems. But as I did this on my own and not some tutorial I am wondering is this the right way to do it:

$(window).load(function() {

    $("a[count]").each(function(){
        var id = $(this).attr("count");
        var data = {
            action: 'impressions_count',
            postid: id
        };
        $.post(MyAjax.ajaxurl, 
            data,
            function(response) {
                console.log( response);
        });
    })
});

and here is one part of code that updates DB

function impressions_count_callback() {
        global $wpdb;
        $post_id = $_POST['postid'];
        //print_r($post_id);
        $post_id = mysql_real_escape_string($post_id);
        $wpdb->query("UPDATE ". $wpdb->prefix ."cb_ads_manager SET impressions = impressions+1 WHERE ID = '$post_id'");
    }

as u can see I am sending ajax request for each baner on site, so if i have 5 baners thats 5 requests. Would it make any difference if i sent it all in one request, as even then i would have to do foreach loop in db query so i would again do 5 db queries unless its possible to do it in one go.

P.S. Even if i am working within WP, I believe this is more of php/ajax question thats why I asked here.

Was it helpful?

Solution

You could actually make only one ajax request and only one query to the DB with something like this :

$(window).load(function() {
    var ids = new Array();
    $("a[count]").each(function(){
        ids.push($(this).attr("count"));
    };
    if(ids.length > 0) {
       var data = {
          action: 'impressions_count',
          postids: JSON.stringify(ids);
       };
       $.post(MyAjax.ajaxurl, data,
           function(response) {
             console.log( response);
       });
    }

 }); 

and in PHP

function impressions_count_callback() {
        global $wpdb;
        $post_id = json_decode($_POST['postid']);
        //print_r($post_id);
        $post_id = implode(',', $post_id);
        $post_id = mysql_real_escape_string($post_id);
        $wpdb->query("UPDATE ". $wpdb->prefix ."cb_ads_manager SET impressions = impressions+1 WHERE ID IN ($post_id)");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top