3

I used this existing question to help me out: HTML - Change\Update page contents without refreshing\reloading the page

The template-comparison.php file fetches the code from the header.php code but the actual "fetch code" isn't shown. Otherwise, the template page would have no header. The templatecode.php file is the code used to fetch and display the database data.

My code:

template-comparison.php

    <a href="#" onClick="prescand('1')" >link text</a>
    <a href="#" onClick="prescand('2')" >link text 2</a>
    <div id='myStyle'>
    </div>

templatecode.php

    <?php
    $servername = "localhost";
    $username = "hidden for security purposes";
    $password = "hidden for security purposes";
    $dbname = "hidden for security purposes";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

      $ID = $_GET['ID'];
      $results = mysql_query("SELECT * FROM PresidentialCandidate WHERE  ID='$ID'");   
      if( mysql_num_rows($results) > 0 )
      {
       $row = mysql_fetch_array( $results );
       echo $row['ID'];
      }
    ?>

header.php

   <script type="text/javascript">
    function prescand(ID) {
      $('#myStyle').load('templatecode.php?id=' + ID);
    }
    </script>

What happens:

I click the link. Nothing happens. It just acts like an anchor that pushes me to the top of the page.

Any ideas? What I want is to have ALL of the data for the link clicked (eg: ID 1...link text) to be displayed in the div. If I click, ID 2 (link text 2), the data for that ID is shown.

Community
  • 1
  • 1
thomas
  • 163
  • 2
  • 13

4 Answers4

2

I have a longer answer below but one thing you can do to prevent it from acting like an anchor tag is to just call event.preventDefault(); on the onclick() before your function:

template-comparison.php

<a href="#" onClick="event.preventDefault();prescand('1');" >link text</a>
<a href="#" onClick="event.preventDefault();prescand('2')" >link text 2</a>
<div id="myStyle">
</div>

Use AJAX like this:

template-comparison.php

<a href="#" class="query-link" data-id="1">link text</a>
<a href="#" class="query-link" data-id="2">link text 2</a>
<div id="myStyle">
</div>

header.php

jQuery(document).ready(function(){
    jQuery('a.query-link').on('click', function(e){    
        //Prevent the link from working as an anchor tag
        e.preventDefault();

        //Make AJAX call to the PHP file/database query
        jQuery.ajax({
            url:'{PATH TO FILE}/templatecode.php',
            type:'POST',
            data:{id:jQuery(this).data('id')},
            success:function(data){
                jQuery('#myStyle').append(data);
            }
        });
    });
});

templatecode.php

<?php
$servername = "localhost";
$username = "hidden for security purposes";
$password = "hidden for security purposes";
$dbname = "hidden for security purposes";

// Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
} 

  $ID = $_POST['ID'];
  $results = $mysqli->query("SELECT * FROM PresidentialCandidate WHERE  ID='$ID'");   
  if( $results->num_rows > 0 )
  {
   $row = mysqli_fetch_array($results,MYSQLI_ASSOC);

    //Instead of just echoing out the ID, you need to build the result/data that you want in the div right here. The success function of the AJAX call will append whatever you echo out here
    echo $row['ID'];
  }
?>

BTW, I updated your PHP code to use MySQLI properly instead mixing MySQL with MySQLi.

After seeing your site (WordPress), you're not going to want to load this in the header.php directly. One of the issues is that jQuery is being loaded AFTER this script so it doesn't have the jQuery variable to use yet when it loads. You can try by putting it in the footer.php file but the 'right' way to do it is to put it in an external script and then load it using wp_enqueue_script in your functions.php file.

MillerMedia
  • 3,651
  • 17
  • 71
  • 150
  • the `templatecode.php` still has major issues of `mysqli` vs `mysql`. Also, that `$.ajax` code is overkill compared to OP's ` $('#myStyle').load('templatecode.php?id=' + ID);`. – Sean Dec 15 '15 at 06:35
  • @Sean, yeah that's definitely true. I don't think it's a bad thing to have it a bit more verbose if it exposes the process a bit better (I know; I'm going to get bashed by other programmers here...but on something simple like this it can't hurt to be clearer). I'll put his option fixed up here as well. – MillerMedia Dec 15 '15 at 06:40
  • 1
    @MillerMedia, Thank god you did not approach `new XMLHttpRequest();` to expose the process..If OP is certain that response will be `html` then `load()` seems appropriate to me.. – Rayon Dec 15 '15 at 06:44
  • @MillerMedia - not working. check my site http://dirtypoliticsph.com/presidential-candidate-comparison – thomas Dec 15 '15 at 09:09
  • A couple things are happening here. First off, the Javascript isn't running because I think with the way you have it set up in your template, it's loading before the jQuery is being loaded on the page (you're getting a 'jQuery is not defined' error in the console). When I run the code after page load, the jQuery runs fine but then I'm getting a 500 error on the PHP page. Are you using the exact code from above? I wasn't obviously able to test it on your server but it looks like there's slight issues in that as well. I've also updated my answer now that I see your site...see above.. – MillerMedia Dec 15 '15 at 09:39
  • if I put the jquery in the footer, won't it run AFTER all of the code is executed? I have it in the footer now but it still don't work. – thomas Dec 15 '15 at 09:47
  • I tried using the wp_enqueue_script function in my functions.php file but it crashed my site: ` function comparison-js() { wp_enqueue_script( 'custom-script', get_template_directory_uri() . '/js/comparison-js.js', array( 'jquery' ) ); } add_action( 'wp_enqueue_scripts', 'comparison-js' );` – thomas Dec 15 '15 at 09:57
  • When you say it 'crashed' your site do you mean you got the white screen with the error message or did it do something else? – MillerMedia Dec 15 '15 at 17:54
  • I got a blank white screen. This was when I attempted to use the wp_enqueue_script script. – thomas Dec 15 '15 at 23:56
  • @MillerMedia - fixed the error. you can check the site now. now I get this error: Empty string passed to getElementById(). – thomas Dec 16 '15 at 15:33
  • Problem is, if I look at NetworkActivity, it doesn't show the javascript file bring loaded. – thomas Dec 16 '15 at 15:41
  • eh...posting too many comments. anyways, got the js loading through the wp_enqueue_script. had to add the theme name to the function name. but even still, the code isn't working. – thomas Dec 16 '15 at 17:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/98161/discussion-between-millermedia-and-thomas). – MillerMedia Dec 16 '15 at 19:28
1
$results = mysql_query("SELECT * FROM PresidentialCandidate WHERE  ID='$ID'");   
if( mysql_num_rows($results) > 0 )
{
   $row = mysql_fetch_array( $results );
   echo $row['ID'];
}

Replace with:

$sql = "SELECT * FROM PresidentialCandidate WHERE  ID='$ID'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
  $row = $result->fetch_assoc();
  echo $row['ID'];
}

Please don't mix both mysql_* & mysqli_* functions.

Shailesh Katarmal
  • 2,757
  • 1
  • 12
  • 15
1

just remove href from anchor link and it'll just call the function and will not redirect to #

<a onClick="prescand('1')" >link text</a>
0

If you are using jQuery you can avoid DOM onClick triggers and use the jQuery events instead. Also when you have a hashtag as href in your anchors it puts the hashtag in the URL when clicked because it assumes it is an element ID. You can change that as show below, or even ommit it:

<a href="javascript:;" class="foo" data-target="1" >link text</a>

Now you can bind the events using jQuery:

$(document).ready(function(){
    $('.foo').on('click', function(e){
        e.preventDefault();
        prescand($(this).data("target"));
    });
});

You might also use the $('a') jQuery selector, but usually you want to be a bit more specific and target only certain anchors by grouping them together with a certain class.

The loading function is OK as is.

Dropout
  • 13,653
  • 10
  • 56
  • 109