admin管理员组

文章数量:1406063

Hi i am a beginner i am working on software site. i have built all the pages and layout for the site that was the easy part done using HTML CSS AND JAVASCRIPT alone, only thing left is to make main categories pages for different software which is tough for me.

i want to to add sorting option on category pages like this (See Here) where user shall be able to sort software according to date, name, date added etc. and also be able to control max number of software to display like 20, 30, 100 etc.

On my HTML Page i have these div's in which i want to display data (different softwares) from MySQL database "security_software" (it is a testing database) from table "internet_security" (it is a testing table)

HTML Div's

  <div class="category-container">
    <div class="category-image"></div>
    <div class="category-desc"><a href="#">#</a><p>text</p></div>
    <div class="rating5" >Editors' rating: </div>
    <div class="category-download-btn"><a href="#">Download</a></div>
    <div class="category-buy-btn"><a href="#">Buy</a></div>
  </div>

After Some research i have got a solution to use JSON AJAX PHP &MySQL

JAVASCRIPT Code i have

<head>    
<script src=".js"></script>
<script type="text/javascript">
$.ajax({
    url: 'ajax.php',
    dataType: 'json',
    success: function(response){
        data = '';
        $.each(response,function(i,val){
          data = '<div class="category-image">'+val.image+'</div>'+
        '<div class="category-link"><a href="#">'+val.id+'</a></div>'+
        '<div class="category-desc"><p>'+val.description+'</p> </div>'+
        '<div class="rating5" >'+val.rating+'</div>'+ 
        '<div class="category-download-btn"><a href="'+val.download+'">Download</a></div>'+ 
        '<div class="category-buy-btn"><a href="'+val.buy+'">Buy</a></div>';
        $('<div>').attr('id',i).html(data).appendTo('#response');
    });

    }
 });
</script>
</head>
 <body>
<div id='response'></div>   
 </body>

PHP Code i have

<?php
$q=$_GET["q"]; 

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("security_software", $con);

$sql="SELECT * FROM internet_security ORDER by `".$q."` DESC" ;


$result = mysql_query($sql);
$response = array();
$i=0;
while($row = mysql_fetch_array($result))
  {
  $response[$i]['id']           =$row['id'];
  $response[$i]['title']        = $row['title'];
  $response[$i]['image']        = $row['image'];
  $response[$i]['description']  = $row['description'];
  $response[$i]['rating']       = $row['rating'];
  $response[$i]['download']     = $row['download'];  
  $response[$i]['buy']          = $row['buy'];
  $i++;
  }
mysql_close($con); 

echo json_encode($response);
?>

Now it is not working at all as i dont have any place to attach these codes for (categories drop down) in javascript i have.

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="id">id</option>
<option value="title">title</option>
<option value="image">image</option>
<option value="description">description</option>
<option value="description">rating</option>
<option value="download">download</option>
<option value="buy">buy</option>
</select>
</form>

Please help me guys where can i attach these code and how to get it working, i am totally confused.

Hi i am a beginner i am working on software site. i have built all the pages and layout for the site that was the easy part done using HTML CSS AND JAVASCRIPT alone, only thing left is to make main categories pages for different software which is tough for me.

i want to to add sorting option on category pages like this (See Here) where user shall be able to sort software according to date, name, date added etc. and also be able to control max number of software to display like 20, 30, 100 etc.

On my HTML Page i have these div's in which i want to display data (different softwares) from MySQL database "security_software" (it is a testing database) from table "internet_security" (it is a testing table)

HTML Div's

  <div class="category-container">
    <div class="category-image"></div>
    <div class="category-desc"><a href="#">#</a><p>text</p></div>
    <div class="rating5" >Editors' rating: </div>
    <div class="category-download-btn"><a href="#">Download</a></div>
    <div class="category-buy-btn"><a href="#">Buy</a></div>
  </div>

After Some research i have got a solution to use JSON AJAX PHP &MySQL

JAVASCRIPT Code i have

<head>    
<script src="http://code.jquery./jquery-latest.js"></script>
<script type="text/javascript">
$.ajax({
    url: 'ajax.php',
    dataType: 'json',
    success: function(response){
        data = '';
        $.each(response,function(i,val){
          data = '<div class="category-image">'+val.image+'</div>'+
        '<div class="category-link"><a href="#">'+val.id+'</a></div>'+
        '<div class="category-desc"><p>'+val.description+'</p> </div>'+
        '<div class="rating5" >'+val.rating+'</div>'+ 
        '<div class="category-download-btn"><a href="'+val.download+'">Download</a></div>'+ 
        '<div class="category-buy-btn"><a href="'+val.buy+'">Buy</a></div>';
        $('<div>').attr('id',i).html(data).appendTo('#response');
    });

    }
 });
</script>
</head>
 <body>
<div id='response'></div>   
 </body>

PHP Code i have

<?php
$q=$_GET["q"]; 

$con = mysql_connect('localhost', 'root', '');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("security_software", $con);

$sql="SELECT * FROM internet_security ORDER by `".$q."` DESC" ;


$result = mysql_query($sql);
$response = array();
$i=0;
while($row = mysql_fetch_array($result))
  {
  $response[$i]['id']           =$row['id'];
  $response[$i]['title']        = $row['title'];
  $response[$i]['image']        = $row['image'];
  $response[$i]['description']  = $row['description'];
  $response[$i]['rating']       = $row['rating'];
  $response[$i]['download']     = $row['download'];  
  $response[$i]['buy']          = $row['buy'];
  $i++;
  }
mysql_close($con); 

echo json_encode($response);
?>

Now it is not working at all as i dont have any place to attach these codes for (categories drop down) in javascript i have.

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="id">id</option>
<option value="title">title</option>
<option value="image">image</option>
<option value="description">description</option>
<option value="description">rating</option>
<option value="download">download</option>
<option value="buy">buy</option>
</select>
</form>

Please help me guys where can i attach these code and how to get it working, i am totally confused.

Share Improve this question edited May 18, 2012 at 11:16 asked May 18, 2012 at 10:59 user1275456user1275456 7
  • 1 First rule of ajax is to make the server side script (ie PHP) work and fully test it before moving on to consume it with Javascript. Your PHP won't work because you're ordering by a string not a field. Replace the single quotes with backticks and add a check so that it will only accept a predefined list of field names to prevent SQL injection. When you have that working you can rule out the PHP and debug the Javascript. – MrCode Commented May 18, 2012 at 11:10
  • I was about to write a long response, but MrCode is correct. You should ensure your viewers do not have Javascript enabled first and then once it's working, use Javascript to improve it. – Gavin Commented May 18, 2012 at 11:17
  • i forget to add backticks thanks for reminding, but it is not working. – user1275456 Commented May 18, 2012 at 11:19
  • @Gavin if you can provide me your response it will be great help. as i am new i understant a little late, you guys just tell in a way that goes off my head – user1275456 Commented May 18, 2012 at 11:21
  • What happens when you navigate to ajax.php?q=title? – MrCode Commented May 18, 2012 at 11:23
 |  Show 2 more ments

1 Answer 1

Reset to default 2

First thing worth noting is, if you are going to display tabular data... Use a table! It will make things a lot easier for you.

Secondly. Build your code and table as if Ajax did not exist. Initially populate the data using PHP on the page your displaying the data. Then, hook up the column header's so they link to your page, but passing which column you want to sort by and also which direction.

i.e.

<?
    $column = (isset($_GET["column"]) ? $_GET["column"] : 'id'); 
    $direction = (isset($_GET['direction']) ? $_GET['direction'] : 'asc');
    $con = mysql_connect('localhost', 'root', '');
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("security_software", $con);
    $sql="SELECT * FROM internet_security ORDER by '".$column."' " . $direction;


    $result = mysql_query($sql);
    $response = array();
    $i=0;
    while($row = mysql_fetch_array($result))
    {
        $response[$i]['id']           =$row['id'];
        $response[$i]['title']        = $row['title'];
        $response[$i]['image']        = $row['image'];
        $response[$i]['description']  = $row['description'];
        $response[$i]['rating']       = $row['rating'];
        $response[$i]['download']     = $row['download'];  
        $response[$i]['buy']          = $row['buy'];
        $i++;
    }
    mysql_close($con); 
?>

<div id="content">
    <table>
        <thead>
            <tr>
                <td><a href="table.php?column=id<?= (isset($_GET['column']) && $_GET['column'] == 'id' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">ID</a></td>
                <td><a href="table.php?column=title<?= (isset($_GET['column']) && $_GET['column'] == 'title' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">Title</a></td>
                <td><a href="table.php?column=rating<?= (isset($_GET['column']) && $_GET['column'] == 'rating' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">Rating</a></td>
                <td><a href="table.php?column=download<?= (isset($_GET['column']) && $_GET['column'] == 'download' && !isset($_GET['direction']) ? '&direction=desc' : ''); ?>">Download</a></td>
            </tr>
        </thead>
        <tbody>
            <? foreach($response as $i => $row) : ?>
            <tr>
                <td><?= $row['id']; ?></td>
                <td><?= $row['title']; ?></td>
                <td><?= $row['rating']; ?></td>
                <td><?= $row['download']; ?></td>
            </tr>
            <? endforeach; ?>
        </tbody>
    </table>
</div>

The above code would go inside a single PHP file, without any other HTML etc. Then, on the page you want to display this table, you simply <? include('path-to-file.php'); ?> include it.

Finally... At the top of the page you are displaying the table on, you would put:

<?
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
    {
        include('path-to-file.php');
        die();
    }
?>

The above code would then detect an Ajax request and serve only the table with the data in the new order.

You would then need to use Javascript to replace the table with the new HTML via

$('#content table thead a').live('click', function(e)
{
    e.preventDefault();
    $.ajax(
    {
        url : $(this).attr('href'),
        success : function(resp)
        {
            $('#content').html($(resp).html());
        },
        error : function()
        {
            alert('There was a problem sorting your table...');
        }
    });
});

where resp is the variable that contains your Ajax response.

Note: This is just a very simple and crude (oh, and untested) way to handle the situation. You would need to improve it your self to prevent any security related issues such as SQL Injection.

本文标签: javascriptHow to apply sorting and filtering using Ajax Json PHP amp MySQLStack Overflow