Javascript And PHP Ajax

Berk

berkibap#4233
Developer
Oct 17, 2015
863
190
hello

so what i'm trying here is, when i click <a href="" id="admin">e<?php echo $array['username']; ?></a> I want it to pop a modal (custom css, not bootstrap) with including some information about the $array['username'];
I tried AJAX but it didn't send any response. Either success or error.
My code:
Code:
<script>
$("#admin").click(function() {
    function toggleProfile(id) {
        $.ajax ({
            url: "getProfile.php",
            method: "POST",
            data:id,
            success: function(data) {
                $("#profile").html(data);
                },
            error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        console.log(msg);
            }
            });
        }   
    });
    </script>
PHP:
<?php
$id = $_POST['id'];
$q = $db->assoc($db->query("SELECT * FROM users WHERE id = '{$id}'"));
?>
 <div id="openModal" class="modalDialog">
    <div>
        <a href="#close" title="Close" class="close">X</a>
        <div style="padding-top:20px;">
        <h4>Profile</h4><hr><img src="http://domain.com/pictures/<?php echo $r['username']; ?>.png" style="border-radius: 5000px; float:right; width:300px; height:300px;"/></div>
        <h2><?php echo $q['username']; ?> </h2> <div style="padding:10px;"><?php if($q['is_away'] == 1) { ?><div style="border:5px solid rgb(115,56,128);border-radius:3px; height:25px;width:125px; background: rgb(0,0,0); font-weight:bold;color:white;padding:10px;"><center>This user is away</center></div></div><?php } ?>
        <p><B>Region</b>: <?php echo $q['region']; ?></p>
       <p><b>Rank</b>: <?php echo $q['rank']; ?></p>
<?php
    if($user->hasGroup('4') || $user->hasGroup('5')){
        ?>
        Admin actions<br>
            <form method="post" action="" >
            <input type="submit" class="mws-button red" value="Log out this user." name="logout">
            </form><br>
            <form method="post" action="" >
            <input type="submit" class="mws-button red" value="Alert this user." name="alert">
            </form><br>
            <form method="post" action="" >
            <input type="submit" class="mws-button red" value="Suspend this user." name="suspend">
            </form>
            <?php
          
  
        if($_POST['logout']) {
            $user->logoutUser($uid['id']);
        }
      
    }
        ?>
  

</div>
</div>
</div>
</div>

It doesn't return anything. Maybe i'm missing something?

Any help appreciated.

Thanks
 
Last edited:

Markshall

Русский Стандарт
Contributor
Dec 18, 2010
2,637
2,389
You're defining a function called toggleProfile but not actually invoking it. And even then, where is the id parameter coming from?

Also, in your JavaScript, all you appear to be sending is an ID number, no parameter names.

It should be something like this (also change your method to GET rather than POST. You're not posting anything, you're trying to get information. This will also need updating in your PHP):
This code refers to a variable called id, but you'll need to figure out how to grab it from your link.
Code:
<script>
    $("#admin").click(function() {
        $.ajax({
            url: "getProfile.php",
            method: "GET",
            data: 'id=' + id,
            success: function(data) {
                $("#profile").html(data);
            },
            error: function() {
                console.log('Error occurred');
            }
        });
    });
</script>

After that, you're filling the #profile element, but where is it opening? There's no code in there which looks like it is opening the modal dialog.
 

Berk

berkibap#4233
Developer
Oct 17, 2015
863
190
You're defining a function called toggleProfile but not actually invoking it. And even then, where is the id parameter coming from?

Also, in your JavaScript, all you appear to be sending is an ID number, no parameter names.

It should be something like this (also change your method to GET rather than POST. You're not posting anything, you're trying to get information. This will also need updating in your PHP):
This code refers to a variable called id, but you'll need to figure out how to grab it from your link.
Code:
<script>
    $("#admin").click(function() {
        $.ajax({
            url: "getProfile.php",
            method: "GET",
            data: 'id=' + id,
            success: function(data) {
                $("#profile").html(data);
            },
            error: function() {
                console.log('Error occurred');
            }
        });
    });
</script>

After that, you're filling the #profile element, but where is it opening? There's no code in there which looks like it is opening the modal dialog.

ID meant to be onclick="toggleProfile(<?php $array['id']; ?>)". I messed it up.

Modal only uses CSS. Here is it's CSS:
Code:
<style>.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    z-index: 99999;
    opacity:0;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    pointer-events: none;
}
.modalDialog:target {
    opacity:1;
    pointer-events: auto;
}

.modalDialog > div {
    width: 700px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: white;
    height:500px;
}.close {
    background: #606061;
    color: #FFFFFF;
    line-height: 25px;
    position: absolute;
    right: -12px;
    text-align: center;
    top: -10px;
    width: 24px;
    text-decoration: none;
    font-weight: bold;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    -moz-box-shadow: 1px 1px 3px #000;
    -webkit-box-shadow: 1px 1px 3px #000;
    box-shadow: 1px 1px 3px #000;
}

.close:hover { background: #00d9ff; }</style>
And to open, i do <a href="#openModal" >Modal</a> and for modal <div id="openModal">
So if you have any better code, please share with me.
 

CosmoPeak

PeakRP.com
May 15, 2016
271
268
ID meant to be onclick="toggleProfile(<?php $array['id']; ?>)". I messed it up.
[/CODE]
And to open, i do <a href="#openModal" >Modal</a> and for modal <div id="openModal">
So if you have any better code, please share with me.
You're combining JavaScript events and jQuery, you need to use one or the other.

$("#admin").click(function() {}); is called when a div with ID 'admin' is clicked. There's no need to define a function within your handler (as in Mark's snippet). Just remove the onclick="" from your html.

A way to pass the ID to JavaScript would be to add a data attribute to your html. For example:

Code:
<a id="#admin" data-id="<?php $array['id']; ?>">Username</a>

And updating Mark's code to get the id from the element:

Code:
<script>
    $("#admin").click(function() {
        var id = $(this).data('id');

        $.ajax({
            url: "getProfile.php",
            method: "GET",
            data: 'id=' + id,
            success: function(data) {
                $("#profile").html(data);
            },
            error: function() {
                console.log('Error occurred');
            }
        });
    });
</script>

Again, you would also need to add the code which opens the modal on success as well.
 

Berk

berkibap#4233
Developer
Oct 17, 2015
863
190
You're combining JavaScript events and jQuery, you need to use one or the other.

$("#admin").click(function() {}); is called when a div with ID 'admin' is clicked. There's no need to define a function within your handler (as in Mark's snippet). Just remove the onclick="" from your html.

A way to pass the ID to JavaScript would be to add a data attribute to your html. For example:

Code:
<a id="#admin" data-id="<?php $array['id']; ?>">Username</a>

And updating Mark's code to get the id from the element:

Code:
<script>
    $("#admin").click(function() {
        var id = $(this).data('id');

        $.ajax({
            url: "getProfile.php",
            method: "GET",
            data: 'id=' + id,
            success: function(data) {
                $("#profile").html(data);
            },
            error: function() {
                console.log('Error occurred');
            }
        });
    });
</script>

Again, you would also need to add the code which opens the modal on success as well.
Thanks. How can I open it? As I stated, it uses CSS, nothing else.
And, how do I write everything in getProfile.php? I mean, the data. I have queries and things and want to write modal to main page. Should I use json_encode or something?
Thanks
 

CosmoPeak

PeakRP.com
May 15, 2016
271
268
Thanks. How can I open it? As I stated, it uses CSS, nothing else.
And, how do I write everything in getProfile.php? I mean, the data. I have queries and things and want to write modal to main page. Should I use json_encode or something?
Thanks
If it were me, I'd format the data as JSON on the server and parse it using JS when it's received (look up JSON.parse). Then populate the elements on the page with the relevant data. To show the modal (if it's not bootstrap/anything and just CSS) you can just do something like $('#myModal').show() or $('#myModal').fadeIn();
 

Berk

berkibap#4233
Developer
Oct 17, 2015
863
190
If it were me, I'd format the data as JSON on the server and parse it using JS when it's received (look up JSON.parse). Then populate the elements on the page with the relevant data. To show the modal (if it's not bootstrap/anything and just CSS) you can just do something like $('#myModal').show() or $('#myModal').fadeIn();
Okay, I'm confused now. So can you show me an example of getProfile.php? I can't quite understand :/
 

MayoMayn

BestDev
Oct 18, 2016
1,423
683
Thanks. How can I open it? As I stated, it uses CSS, nothing else.
And, how do I write everything in getProfile.php? I mean, the data. I have queries and things and want to write modal to main page. Should I use json_encode or something?
Thanks
Also the Ajax example has been deprecated.
Code:
<script type="text/javascript">
$('#admin').on('click', function () {
   var id = $(this).data('id');

   $.ajax({
      url: 'getProfile.php',
      method: 'GET',
      data: { id: id }
   }).done(function (data) {
      $('#profile').html(data);
   }).fail(function (err) {
      console.log('An error occurred: ' + err);
   });
});
</script>
 

CosmoPeak

PeakRP.com
May 15, 2016
271
268
Okay, I'm confused now. So can you show me an example of getProfile.php? I can't quite understand :/
If you don't understand it, stick with what you have for now until you have time to learn about JSON, it should work fine. If you're going to use this for production, make sure you use prepared statements or at least filter the input properly.

Code:
$q = $db->assoc($db->query("SELECT * FROM users WHERE id = '{$id}'"));

This is subject to SQL injection.
 

Users who are viewing this thread

Top