0

Ok guys/Gals. I need some help. Or a better way to do this. I need to be make it when someone clicks div id O+$row['Id'] will load the function displayops and some how pass the arguments. I can deal with the $row['name'] not being passed, and $pastOp will always = TRUE in this case. And I need to do it without reloading the page if at all possible.

The reason I need this is because running it for ALL of them at the same time takes almost 5-10 min for it to load completely, and there is no need to load all of them. Just the ones that people need to click on as they go. Any help is truly appreciated.

while($row = $result->fetch_assoc()){
    echo "<div style=\"clear: both;\"></div>\n";
    echo "<div class=\"operation\">\n";
    echo "<h2 class=\"opsList\" style=\"cursor:pointer;\"><img src=\"/js/assets/".$row['icon']."\"/><div id=\"O".$row['Id']."\">Past Operations for " .$row['Name'] ."</div></h2>\n";
    echo "<div class=\"initiallyHidden\" id=\"P".$row['Id']."\">";
//      displayops($row['Id'], $row['Name'], $pastOp);
    echo "</div>";
    echo "</div>\n";
}

Using a modified version of Adams code and some research online I got it to work. (THANK YOU ADAM!!!) Below is the modified Jquery

Ok, I was able to takes Some of Adams code and make it work. Thank you very much Adam. Below is what worked.

$(document).ready(function(){
$(function(){
    $('.operation').click(function(){
        var container = $(this);
            var params = {
                id: $(this).data('id'),
                name: $(this).data('name')
            };
            $

            $.ajax({
                url: '/opserv/ajaxExPrintOps.php',
                data: params,
                type: 'POST',
                dataType: 'html',
                success: function(data){
                    $('.initiallyHidden', container).html(data);
                },
                error: function(){
                    alert('An error occurred'); //Or something mroe useful?
                }
            });
    });
});
});
6
  • You can use jquery for that Commented Apr 14, 2014 at 17:32
  • I'm certain I can use jquery to do that.. But how.. What. I've searched everywhere how to load a php function but they all want it to reload the page. I need it to NOT reload the page. Commented Apr 14, 2014 at 17:36
  • Ah, my apologies. I took off my answer then since it doesn't help you in this case. I'll try to come up with something that does help you. Commented Apr 14, 2014 at 17:37
  • ChaseC I appreciate it.. I've been searching google for ways to do this and got frustrated, and came here. I'm still searching even now. Commented Apr 14, 2014 at 17:42
  • I would strongly suggest using a data binding library (knockout) to display JSON from the PHP output, rather then using PHP to render the output. This is proper separation of concerns and cleaner. see fiddle Commented Apr 14, 2014 at 21:31

2 Answers 2

1

You need an ajax action which takes the row id (possible name, etc) as paramters and returns the contents just for that row. I.e. which runs your displayops command.

Then you use as your main php:

while($row = $result->fetch_assoc()){
    echo "<div style='clear: both;'></div>\n";
    printf( '<div class="operation" data-id="%2$s" data-name="%3$s">
               <h2 class="opsList" style="cursor:pointer;">
                 <img src="/js/assets/%1$s"/>
                 <div id="O%2$s">Past Operations for %3$s</div>
               </h2>
               <div class="initiallyHidden" id="P%2$s"></div>
             </div>',
             $row['icon'],
             $row['Id'],
             $row['Name'] );
    echo "</div>\n";
}

Then add an action at, for example, /get_past_ops.php:

<?php
// You should maybe add some data validation here?
displayops($_POST['id'], $_POST['name'], TRUE);

Then in your page add the following javascript:

$(function(){
   $('.operation').click(function(){
     var container = $(this);
     if( !$('.initiallyHidden', container).is(':visible') ){
       var params = {
          id: $(this).data('id'),
          name: $(this).data('name')
       };
       $.ajax({
         url: '/get_past-ops.php',
         data: params
         type: 'POST',
         dataType: 'html',
         success: function(data){
                     $('.initiallyHidden', container).html(data).show();
                  },
         error: function(){
                  alert('An error occurred'); //Or something mroe useful?
                }
       });
     }
   });
});

All untested but hopefully you get the idea.

Sign up to request clarification or add additional context in comments.

7 Comments

Adam, I've tried this example and played around with it some, but seems somethings wrong with the click option? The Div section was a little off but I fixed that fairly quickly.. But my Jquery is VERY limited and while I understand what it does.. I couldn't tell you if there was a syntax error. I did add the document.ready What about the id: $(this).data('id'), should it be data['Id'] and 'Name' or is it the id: needs to be Id:?
Nevermind after doing some more research I see what the id and such means. But I still can't get this to work.
Ok, I've managed to figure out that after the Params there should be a , but This function still is not working.. The only think I know for sure is when I change the . on the second instance of initiallyHidden I get the error.. Otherwise nothing is happening.
Alright I've narrowed it down to either the div its printing in is wrong, or the ajax call is not calling the php file. Still looking into this
I figured it out.. All is good now Adam. With a lot of research I was able to modify your code to get it to work. I posted the results in my question. Hopfully this can help someone in the future. The php section in the while llop just needed some Div help. But all was good.
|
0

Here is the source code pertaining to the information give below, except I haven't implemented any JSON stuff yet, but I will be :)

Here is how I get some PHP data from database and store in readable forms, then it is easy to get it to JSON to be passed to the View. Where knockout can take the rest of it:

public function getAll() {
    try {       
        $stmt = $this->database->queryUnprepared('SELECT * FROM products');

        $_products = $stmt->fetchAll(PDO::FETCH_CLASS, "Product");

        $stmt->closeCursor();

        $this->error = FALSE;

        return $_products;
    }catch (PDOException $e){
        $this->error = TRUE;
        $this->message = $e->getMessage();
    }
}

$this->database is just a class variable holding a PDO wrapper class, all queryUnprepared wraps is, $pdoConnection->query(). PDO is the best possible database php class available. The fact you can connect to just about any database server using it. Plus I think it has better functions to use than mysqli. For instance, the fact you can pull all the rows out of a database and have PDO automatically fill a model is perfect.

class Product {
    public $id;
 // etc model data
}

that is the product class.

This will then give you a long array of all the products in their respective models. After that just wrap it in a simple json_encode(), or better yet, extend the Product class functionality:

class Product {
     public $id;
     // etc model data

    public function toJson() {
        return json_encode(array('id' => $this->id)); // etc for all things
    }
}

For your OPS list do:

class OpsModel {
    public $Id;
    public $name;
    public $icon;
    // etc extend etc
}

I'd assume to get it to the JSON state, simply do something like:

foreach($_products as $product) {
    array_push($jsonArray, $product->toJson());
}
$productJsonArray = json_encode($jsonArray);

Then it is a simple case of assigning it to a javascript variable:

<script> var jsonArray = <?php echo $productJsonArray; ?> </script>

Then just follow this link for the knockout stuff

This way, we leave server side scripting to do server side stuff, and client side scripting for view processing. Much cleaner and easier to maintain server side.

Comments

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.