Spikeedoo G
Spikeedoo G

Reputation: 31

How to GET javascript data in PHP file without page reload

I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).

In script.js, I check for a click and try to change the url.

$('body').on("click", ".chirp", function(){
 var uid = $_GET['id'];
 var pid = $(this).attr("id");
 var pidSplit = pid.split("chirp");
 var messageID = pidSplit[1];
 var obj = {foo: "status"};
 $('.chirpOverlay').addClass("active");
 window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});

The javascript works as intended...but as I will soon find out, the victory is short-lived.

In profile.php, I attempt to GET the status id from the URL parameter.

<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
  $c = $sql->fetch_object();
}
?>

This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).

PS: I tried to do an XMLHttpRequest as well- to no avail. :(

Thanks in advance!

Upvotes: 1

Views: 624

Answers (3)

Spikeedoo G
Spikeedoo G

Reputation: 31

I have finally found a AJAX-based solution to my problem.

I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:

var datastring = 'status=' + messageID;
$.ajax({
    url: "chirp_open_ref.php",
    type: "POST",
    data: datastring,
    cache: false,
    dataType: "text",
    success: function(data){
        $('.chirp-container').html(data);
    }
});

Inside of 'chirp_open_ref.php':

<?php
require 'core.inc.php';

if (isset($_POST['status']) && isset($_SESSION['user_id'])){
  $chirp_id = $_POST['status'];
  $c = "";
  $sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
  if (mysqli_num_rows($sql) > 0){
    $c = $sql->fetch_object();
  }
  include'chirp.inc.php';
}
?>

'chirp.inc.php' is simply a template for the layout/structure of each post. This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!

Upvotes: 0

Joseph_J
Joseph_J

Reputation: 3669

You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.

Here are your two files. Make sure they are both in the same directory.

You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

script.js

$(document).ready(function(){

  $('body').click(function(){

    var id; //define your id.
    var pid;  //define your pid.

    var datastring = 'id=' + uid + '&status=' + pid;
    console.log(datastring);
      $.ajax({

        url: 'profile.php',
        type: 'POST',
        cache: false,
        data: datastring,
        dataType: 'json',
        success: function(data){
          console.log('Made it to the success function: ' + data);
          if (data) {
            //It works, do something.
            console.log(data);

          } else{
            //It does not work, do something.
            console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');

            }

        }

      });    

  });

});

profile.php

<?php

/*
$status_id = $_POST['status'];  //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/

echo 'You made it to your php page.';

?>

A few things:

  • You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
  • Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
  • Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices

Upvotes: 1

Vijay Makwana
Vijay Makwana

Reputation: 921

$('body').on("click", ".chirp", function(){
    var uid = $_GET['id'];
    var pid = $(this).attr("id");
    var pidSplit = pid.split("chirp");
    var messageID = pidSplit[1];
    var obj = {foo: "status"};

    $('.chirpOverlay').addClass("active");

    $.ajax({
        url: "profile.php?id="+uid+"&status="+pid,
        type: "GET",
        data: obj,
        dataType: "html",
        success: function(data){
            console.log(data);
        }
    });
 });

Upvotes: 1

Related Questions