0

This is a bit complex for me, im still a newbie lol. Consider the the following blocks of code. Jquery's Ajax which loops a php block and appends new feed to some div. PHP returns more than one result in this case as an example it returns "Name" and "Slogan". After ajax recieved results, i want to appended the following as a template, but where there's php to be a variable since this will change every time this template is appended. Here's the html template.

<div id="BuzFeedResult1">
<?php 
require_once 'php/db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated DESC LIMIT 1") or  die (mysql_error());
while($row = mysql_fetch_array($Result))
{ ?>
          <div id="ProfileDiv">
            <div>
            <span class="flat-menu-button"><?php echo $row['name'];?></span>
            <span class="flat-menu-button"><?php echo $row['slogan'];?>
            </span>

<?php 
}?>
            </span>
            </div>
            </div>
    </div>

Question. How do i go about getting the above template into ajax inside this div.

var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>");

and then append it accordingly like the following does append "div".

var get_fb = (function() {
    var counter = 0;

    var $buzfeed = $('#BuzFeed');

    return function(){
        $.ajax({

        type: "POST",

        url: "../php/TopBusinesses_Algorythm.php"

     }).done(function(feedback) {

          counter += 1;

          //Divs being appended.

          var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>");

          $buzfeedresults.text(feedback);

          $buzfeed.append($buzfeedresults);

          var $buzfeedDivs = $buzfeed.children('div');

          if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }

          setTimeout(get_fb, 4000);

    }).fail(function(jqXhr, textStatus, errorThrown) {

         var $buzfeedresults = $("<div id='BuzFeedError'></div>");

         $buzfeedresults.text('Error: ' + textStatus);

         if (typeof console !== 'undefined') {

         console.error(jqXhr, textStatus, errorThrown);
       }

   });

   };

   })();

   get_fb()

This question may sound unclear please ask for clarity where needed. If Json can be more neater and short please suggest a structure i can use.

1
  • Didn't get you..Be more specific. Commented Oct 24, 2013 at 6:23

2 Answers 2

1

You can do it by split() function with response.

var response = "yes|||insert a title...and something more!"
var splitResult=response.split("|||");  
var yesNo=splitResult[0];  
var article=splitResult[1];
alert(yesNo+article);
Sign up to request clarification or add additional context in comments.

Comments

1

The better solution, as spliting your result, is to json_encode your result data in ../php/TopBusinesses_Algorythm.php and then you can decode result in done(function(feedback) { ... }) function, and update HTML content separately for each DIV.

Example of your JS code:

function holdSession() {
  $.ajax({
    type: 'POST',
    url: '../php/TopBusinesses_Algorythm.php',
    success: function(data) {
      var ajax_data = jQuery.parseJSON(data);

      $('#total_count').html(ajax_data.total_count);
      $('#online_count').html(ajax_data.online_count);
      $('#online_users_count').html(ajax_data.online_users_count);
    }
  });

  setTimeout("holdSession()", 30000);
}

And example of TopBusinesses_Algorythm.php code:

// here get your data and store it in a array, f.e.:
$result = array();

$result['total_count']        = 1000;
$result['online_count']       = 10;
$result['online_users_count'] = 5;

// finally output result using `json_encode` - {"total_count":1000,"online_count":10,"online_users_count":5}
echo json_encode($result);

Second solution:

Your JS code:

var counter = 0;

var get_fb = (function() {
  var $buzfeed = $('#BuzFeed');

  return function() {
    $.ajax({
      url: "../php/TopBusinesses_Algorythm.php"
    }).done(function(feedback) {
      counter += 1;

      //Divs being appended.

      var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>");

      $buzfeedresults.html(feedback);

      $buzfeed.append($buzfeedresults);

      var $buzfeedDivs = $buzfeed.children('div');

      if ($buzfeedDivs.length > 10) {
        $buzfeedDivs.last().remove();
      }

      setTimeout(get_fb, 4000);
    }).fail(function(jqXhr, textStatus, errorThrown) {
      var $buzfeedresults = $("<div id='BuzFeedError'></div>");

      $buzfeedresults.text('Error: ' + textStatus);

      if (typeof console !== 'undefined') {
        console.error(jqXhr, textStatus, errorThrown);
      }
    });
  };
})();

get_fb();

TopBusinesses_Algorythm.php:

<?php 
require_once 'php/db_conx.php';

$result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated DESC LIMIT 1") or die (mysql_error());

while ($row = mysql_fetch_array($result)) {
  echo '<div id="ProfileDiv">';
    echo '<div>';
      echo '<span class="flat-menu-button">'.$row['name'].'</span>';
      echo '<span class="flat-menu-button">'.$row['slogan'].'</span>';
    echo '</div>';
  echo '</div>';
}
?>

7 Comments

i included the php file on top inside the html. please provide the relevant example of encoding those results in php.
Check example I have added in my answer, hope its clear enough, if not, just ask.
nice, you forgot the dollar sign on the php code inside echo json_encode(result);
not fully, php is outputting json data when run alone, nice, but your ajax outputs nothing, please check it.
My code was just example, you should modify it, as you want, also I think, you dont need to call ajax as POST request. Also, is it ok, to reset var counter = 0; each time, get_fb is called? And why you just dont implement your whole template to ajax file, and return its HTML with name and slogan as one result, and then just append this result to your div?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.