shubham sharma
shubham sharma

Reputation: 301

Passing a php variable to another php file using ajax

I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.

When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.

 <script type="text/javascript">

  $(document).ready(function() {

    $(".content-short").click(function() {                //

      $.ajax({   
        type: "GET",
        url: "content.php",               //
        dataType: "text",                  
        success: function(response){                    
            $(".content-full").html(response); 
        }

      });
    });
  });
</script>

content.php

 <?php
     include "mysql.php";
     $query= "SELECT Content FROM blog limit 1";
     $result=mysql_query($query,$db);
     while($row=mysql_fetch_array($result))
       {
           echo $row['Content'];          
       }
     mysql_close($db);  

    ?> 

Is there an alternate way to do this or something that I need to correct for it to work?

Thanks

Upvotes: 0

Views: 2239

Answers (2)

somethinghere
somethinghere

Reputation: 17340

First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:

$(".content-short").click(function() {
  // get the ID
    var id = $(this).attr('data-id');
    $.ajax({   
        type: "post",
        url: "content.php",
        data: 'id=' + id
        dataType: "text",                  
        success: function(response){                    
            $(".content-full").html(response); 
        }
    });
});

Next up is reading the value you passed in using the script:

<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id     = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id     = intval($id);
$query  = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
    echo $row['Content'];          
}
mysql_close($db);
?>

There you go, I have modified your query to allow fetching by id. There are two major caveats:

First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.

The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:

 echo $row['Content'];

with this:

 echo json_encode(array('success' => $row['Content']));

Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:

success: function(response){                    
    $(".content-full").html(response); 
}

into this:

success: function(response){
    if(response.success) $(".content-full").html(response);
    else alert('No results');
}

Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php

Upvotes: 1

Frank Adrian
Frank Adrian

Reputation: 1234

You can look at passing a parameter to your script, generally like an id by which you can search in the db.

The easiest way to achieve this is by get parameters on the url url: "content.php?param=2",

Then in php: <?php $param = $_GET['param']; ...

Upvotes: 0

Related Questions