dimanche 28 juin 2015

Returning arrays from php with ajax and json

-I have an array that contains more arrays in my php file. I am sending a integer variable (Possibly something else for sometime later that isn't the problem)

-I want php file to return array according to the incoming variable (in this example just 1 and 2.)

-I tried somethings from other posts but they were too complicated and I couldn't understand any of them. And I want to be able to change it whenever I want.

This is what I have done so far..

index.php

<script src="http://ift.tt/1APuVEV"></script>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script type="text/javascript">   
        var sayac = 1;
        $(document).ready(function() {

                $(document).delegate("#klikme", "click", function() {
                        $.post('sayac.php',{"komut": sayac }, function(data){
                                
                                var res = $.parseJSON(data);
                                $('#output').html(res.result[0]);
                                $('#output2').html(res.result[1]);
                        });
                        sayac = sayac + 1;
                        if(sayac > 2)
                                sayac = 1;
                });
        });

</script>
<div id = "klikme">
        KLİK ME!
</div>

<div id = "output">
<?php include 'sayac.php'?>

</div>

<div id = "output2">

</div>

sayac.php

<?php 

        $returnThis = array( array("One" => "Sample Stuff Bla Bla this is one!","Two" => "Sample Text One"), 
                                                array("One" => "Sample Stuff Bla Bla this is one!", "Two"=> "Sample Text Two"));

        if(isset($_POST["komut"]))
        {
                switch($_POST["komut"])
                {
                        case 1:
                                json_encode($returnThis[0]) ;
                                break;
                        case 2:
                                json_encode($returnThis[1]); 
                                break;
                        default:
                                echo "Something is wrong";
                                break;
                }
        }
        
?>

Aucun commentaire:

Enregistrer un commentaire