I am using AJAX to receive data from my database on to my main PHP page.
I have a piece of code that worked, but on with PHP.
When I have just tried to put it in to AJAX (receiving format), the code that I return is not being shown.
I know my AJAX method works as I'm using it to get some other database values.
It's just the Get online users individually won't work.
When I load the page, the code shows what's inside my div id - Loading Info... and then goes blank, so I know it's trying to update it but it's not getting it correctly.
Picture showing that nothing is displayed
My PHP request code is :
//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$last_online = strtotime($users_['lastonline']);
if(time() - $last_online < 30) {
$client_is_online = '
<div class="chat-list-item -available" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Online</div>
</div>
';
} else {
$client_is_online = '
<div class="chat-list-item -offline" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Offline</div>
</div>
';
}
}
//I then echo it back to my home PHP page so it can read the values
//Ignore my other code definitions below as I know they work
//$client_is_online is the only one which doesn't
echo $totalUsers.",".$totalOnline.",".$freemode.",".$bypasses.",".$client_is_online;
My AJAX recieve code is :
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
success: function(value){
var data = value.split(",");
$('#totalUsers').html(data[0]);
$('#totalOnline').html(data[1]);
$('#freeModeStatus').html(data[2]);
$('#bypassesStatus').html(data[3]);
$('#isOnline').html(data[4]);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
I then try storing the returned data in-side my div id :
<div class="sidebar-tab-content" id="staff">
<div class="chat-list sidebar-content-section" id="isOnline">
Loading Info...
</div>
</div>
Return the json data like this
1st : your overwriting the variable . you need to concatenate all user like this
$client_is_online=""; //declare empty string before while loop start
//while loop start here
$client_is_online .= 'html here';
// while end here
2nd : Return the json data like this
$response = array ('totalUsers'=> $totalUsers, 'totalOnline'=> $totalOnline,'freemode'=>$freemode,'bypasses'=>$bypasses,'client_is_online'=>$client_is_online);
header('Content-Type: application/json');
echo json_encode($response);
3rd : Don't forgot to add dataType in ajax
dataType: "json",
4rd : success function should be changed like this
ajax :
success: function(value){
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},
Related
I was trying to parse data to my controller so I can insert it into the database using JQuery and it was returning null. It's for a review star system so doesn't use conventional form fields however the network tab in inspect elements shows that data is actually posted to the controller just, not able to read it for some weird reason.
Update: The data is being inserted fine on desktop however the confirmation (flashdata) message is shown correctly not sure why. Additionally on mobile view no data or message is shown. Does anyone know why? I have updated the code below..
Here's the code from my view:
<?php if($this->session->flashdata('review_submitted')){ ?>
<div class="alert alert-success alert-dismissible container show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Thank you!</strong> Your review has been submitted.
</div>
<?php } ?>
<form id="myForm" name="myForm">
<br>
<div class="form-group text-left div-style">
<h3 style="font-family: MontserratLight;letter-spacing: 2px; line-height: 32px;">Full Name <b>*</b></h3>
<input name="name" class="form-control" style="background: #f7f7f7; border: 1px solid #801424;" required />
</div>
<div class="rate">
<div id="1" class="btn-1 rate-btn"></div>
<div id="2" class="btn-2 rate-btn"></div>
<div id="3" class="btn-3 rate-btn"></div>
<div id="4" class="btn-4 rate-btn"></div>
<div id="5" class="btn-5 rate-btn"></div>
</div>
<script>
$(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var therate = $(this).attr('id');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
var dataRate = 'rate='+therate; //
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-active');
};
$('#myForm').on('submit', function(e){
var url = "<?php echo base_url(); ?>index.php/reviews/add_review";
// $('#myForm').append(therate);
var dataPost = $('#myForm').serialize() + "&rate=" + therate;
$.ajax({
type : "POST",
url : url,
data: dataPost,
success:function(){
}
});
});
});
});
</script>
and using the controller I simply use the following to get the data and add it to the database:
public function add_review(){
$name = $this->input->post('name');
$rating = $this->input->post('rate');
$dataDB = array(
'full_name' => $name,
'rating' => $rating
);
if($this->functions->submit($dataDB)){
$this->session->set_flashdata('review_submitted', true);
redirect(base_url() . 'reviews/index', 'refresh');
}
}
Here's some CSS that I used, perhaps the problem is to do with the mobile browser not having a cursor?
.rate{
width:245px; height: 40px;
margin-bottom:0px;
}
.rate .rate-btn{
width: 45px; height:40px;
float: left;
background: url(rate-btn.png) no-repeat;
cursor: pointer;
cursor:hand;
pointer-events: auto;
}
.rate .rate-btn:hover, .rate .rate-btn-hover, .rate .rate-btn-active{
background: url(rate-btn-hover.png) no-repeat;
}
When passing data through ajax, I think it is better to use JSON dataType. Reform the data type (string -> data object). Besides, I don't think it is really necessary to concat the 'to-be-sent' data into a string.
If you want dynamic data to be sent, you can push elements by condition
$.ajax({
type : "POST",
dataType: 'text' //it is not necessary if you are not returning any data (if you return json, put 'JSON'),
url : "<?php echo base_url(); ?>index.php/reviews/add_review",
data: dataRate, //change to {key:value,key:value}
success:function(data){
}
});
This is just to address your issue with your AJAX Posted Values not appearing where you are expecting them ONLY.
There are a zillion ways you can code this but here is just one which I have changed about to perform debugging. Even I learned a new trick doing this.
Just Nit Picking but what stuck out when reading your code is your use of therate when everywhere else in your JS you use camel case so it should be theRate.It's a good idea to choose a standard and stick to it.
Plus you had what appeared to be nested events in your JS. Some attempt at getting theRate to work correctly? Anyway...
First things. Get back to something basic and work your way back up. (Although in this case I didn't strip your view back to bare bones, but I did with your controller.
Your View.
I had to change this up a bit and hopefully the comments explain things.
I called it rating_view.php
<form name="my-form" id="my-form">
<div class="rate">
<div id="1" class="btn-1 rate-btn">1</div>
<div id="2" class="btn-2 rate-btn">2</div>
<div id="3" class="btn-3 rate-btn">3</div>
<div id="4" class="btn-4 rate-btn">4</div>
<div id="5" class="btn-5 rate-btn">5</div>
</div>
<input type="submit">
</form>
<!-- Added for viewing debug response -->
<div id="json-debug-output"></div>
<!-- Some styles added as non were provided -->
<style>
.rate-btn-hover {
background: blue;
}
.rate-btn-active {
background: yellow;
}
</style>
<script src= <?= base_url('assets/js/jquery_v3.4.1.js'); ?>></script>
<script>
$(document).ready(function () {
// Define your Dom Elements ONCE for efficiency etc
let domRateButton = $('.rate-btn');
let domMyForm = $('#my-form');
let theRate = 0; // Declares this as a Global Var.
let domJsonDebugOutput = $('#json-debug-output');
// Hover
domRateButton.hover(function () {
domRateButton.removeClass('rate-btn-hover');
let theRate = $(this).attr('id');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-hover');
}
});
// Click
domRateButton.click(function () {
console.log('Rating Button Clicked');
theRate = $(this).attr('id');
domRateButton.removeClass('rate-btn-active');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-active');
}
});
// Submit
domMyForm.on('submit', function (e) {
e.preventDefault(); // This was missing
console.log('Posting Rate = ' + theRate);
$.ajax({
type: "POST",
// dataType: 'text',
dataType: "json",
url: "<?php echo base_url(); ?>reviews/add_review",
data: {'act': 'rate', 'post_id':<?= $post_id; ?>, 'rate': theRate},
success: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
},
error: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
}
});
});
});
</script>
Note in the AJAX the changes to dataType from text to json. Also note that data is an array.
I also changed the scope of theRate from local to a global so it was "findable" amongst the functions.
NOT SURE how your form was setup but I added e.preventDefault(); to prevent the form submitting for testing.
Personally I cringe at having PHP vars embedded in any JS code and I usually have my JS as external files and pass in the values from PHP by reading them using JS but that's got it's Pros and Cons as well. So I left that alone for the sake of not going too far with this.
For your Controller - Called Reviews.php
public function show() {
$data['post_id'] = 1; // This comes from somewhere
$content = $this->load->view('rating_view', $data, TRUE);
echo $content;
}
/**
* Called by AJAX
* Do we need to test this is only called by AJAX?
*/
public function add_review() {
// Return everything that was sent for debugging
echo json_encode($this->input->post());
// var_dump($this->input->post());
exit();
}
So here I just had a method show() show the form and the add_review to simply bounce back what was sent. You can do all sorts of things with this. One nice aspect in this case is you do not need to use console.log) as you can view it all on the page (BUT ONLY FOR DEBUGGING). It's another option.
So have a play with that and start making changes to your code and see what works. Remember - get back to basics and pick on the bit that isn't working.
Next you will find you might be getting tripped up on your redirect. But that's for another post.
I am trying to create an input that queries the database and returns whether or not a result exists in the database. I have it partially working, but my box is glowing green whenever I only type in one letter. It would be better if it stayed red until it actually found a exact match and then turned green. Edit: I just realized there is also something wrong with my query. It is correctly querying the database now. The original issue is my main problem.
$(document).ready(function(){
$("#load").keyup(function (e){
e.preventDefault();
;
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
},
error: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
});
});
});
Below is my php
<?php include('../model/conn.php'); ?>
<?php include('../model/conn2.php') ?>
<?php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 = '{$_POST['load']}'";
$query = (odbc_exec($conn,$sql));
$row = (odbc_fetch_row($query));
if($row['cmt_2']){
echo 'yeah';
}
HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<span class="error" style="display: none;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I'm not finding anything</span>
<span class="success" style="display: none;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>
Your error handler will not be called even if "yeah" is not echoed out by PHP script, as the server response would still be HTTP 200. For this reason, your success handler will always trigger (unless of course there is an actual problem with your server/application).
If you want to trigger the error handler, you would have to have the server send a 400 or 500 series HTTP response code (likely 404 in this case) for the case when no match is found.
Alternately, you could just put all your logic in the success handler and not change your server-side code at all. You would just have to test for the value of "yeah" being present or not.
You should also consider adding/removing CSS classes on your DOM elements rather than specifically specifying the CSS in your function. This would allow you to later change the CSS if needed, without having to alter this function.
success: function (data) {
if(data==="yeah")
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
}
else
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
}
check if response is what you need and only then add .success class
Decided to output the error/success message using php instead of changing css
$("#load").keyup(function (e){
e.preventDefault();
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
console.log(data);
if(data==="yeah")
{
$(".validate").html(data);
}
else
{
$(".validate").html(data);
}
}
});
});
My php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 LIKE '{$_POST['load']}'";
$query = odbc_exec($conn,$sql);
$row = (odbc_fetch_row($query));
if($row){
echo '<span class="success" style="display: block;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span>';
}else{
echo'<span class="error" style="display: block;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I\'m not finding anything</span>';
}
My HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<div class="validate"></div><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>
Please have a look at the below CakePHP code
Flip2.php (Model)
<?php
class Flip2 extends AppModel {
var $name = 'Flip2';
public $useTable = false;
//Increment the correct_answer field of the specific user
public function correctAnswer($userID=89, $word)
{
$setQuery = "UPDATE `users_words` SET `correctanswer` = `correctanswer`+1 WHERE `userid`=$userID && `wordid`='$word' ";
query($setQuery);
}
}
Flip2Controller.php (Controller)
<?php
class Flip2Controller extends AppController {
public function index()
{
}
}
?>
index.ctp (View)
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
});
</script>
Now, what I need to do is, this. When the user click on the Acertei button, I need to execute the function correctAnswer. I am very new to PHP and CakePHP so I am really confused about how to do this when a button is clicked. Any advice please?
You have
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
You should use different IDs for each button.
You can call the correctAnswer function with ajax:
Change the button to something like
<button type="button" id="2" data-word="<?php $worcard['unique_wordsforcards']['en_word'] ?>" class="a btn btn-success mr5 btn-lg">Acertei</button>
And then add the following code in $(document).ready()
$(document).ready(function(){
$(".btn-success").click(function(){
var word = $(this).data('word');
$.post('/flip2/correct.json', { word: word })
.done(function(data) {
alert('Saved');
});
I am not sure how the user part works. You should probably have that in the session, and not sent to the function. I hardcoded user 89 and added a way for you to send the word.
Use an appropriate model method
The function correctAnswer in the model would better be written using updateAll:
public function correctAnswer($userId, $word) {
return $this->updateAll(
array('correctanswer' => 'correctanswer + 1'),
array(
'userid' => $userId,
'wordid' => $word
)
);
}
Written in this way the inputs ($userId and $word) will be escaped appropriately and not susceptible to sql injection.
Create a controller action
The doorway to the web for an application is a controller action, create a simple function, calling the model method, and write it to output json:
public function correct() {
$postData = $this->request->data;
$word = $this->request->data['word'];
$userId = $this->Auth->user('id');
$result = false;
if ($userId && $word) {
$result = $this->Flip2->correctAnswer($userId, $word);
}
$this->set('_serialize', array('result'));
$this->set('result', $result);
}
Note that
It'll only work via a post request.
The Auth component (the session) is used to get the current user id, it's not a user-defined input.
This function is defined such that it'll work as a json response.
There's no need to create a view file with the above code.
Be sure to setup your app to handle json requests:
After adding Router::parseExtensions('json'); to your routes file, CakePHP will automatically switch view classes when a request is done with the .json extension, or the Accept header is application/json.
Call the controller action
The required js would be of the form:
$(".btn-success").click(function(){
var word = ...;
$.post(
'/flip2/correct.json',
{word: word},
function (data) {
console.log(data);
// {result: bool}
}
);
});
Note that:
The url ends in .json which is a simple and robust way to provoke CakePHP to respond as json.
It is a post request.
The response will be of the form defined by _serializein the controller action.
I would like to achieve such an effect, except that when you click on the picture (link) jquery script sends a GET to the same file from the fact that with another ID. I mean the dynamic reload the page without refreshing the addition of a nice effect in the attached link.
my code :
<script>
$('a.menu').click(function(){
$('.content').html('');
})
</script>
<div class="content" id="page_effect" style="padding:0px; display:none;">
<div class="separator" style="margin: -17px auto;"></div>
<span class="choose-product"> Wybierz Produkt</span>
<p>
<?php
$kat=$_GET['kat'];
$co_ile_strona=9;
//----------------
$dopisz="";
if (is_numeric($kat)) {
$dopisz=" WHERE kat_id='".$kat."'";
$wyk=mysql_query("SELECT * FROM kategorie WHERE kat='".$kat."'");
while($ww=mysql_fetch_array($wyk)) {
$dopisz.=" OR kat_id='".$ww['id']."'";
}
}
$sile=false;
$wyk=mysql_query("SELECT * FROM produkty ".$dopisz."");
if ($ile=mysql_num_rows($wyk)) {
if (!$sile) {
$nazwa = mysql_fetch_assoc(mysql_query("SELECT * FROM kategorie WHERE id='".$_GET['kat']."'"));
if(strlen($nazwa['nazwa']) > 0)
$nazwa = $nazwa['nazwa'];
?>
<div style="text-align: center; width: 80%;margin: 0 auto;margin-top: 39px;">
<a href="produkt.html"><div class="product-box">
<img src="images/picasso0.png" alt="Product"/>
<span class="product-title"><?=$nazwa?></span>
</div>
</a>
<?
$sile=true;
}
if (!$_GET['strona']) $strona=1; else $strona=$_GET['strona'];
$start=($strona*$co_ile_strona)-$co_ile_strona;
mysql_data_seek($wyk,$start);
$licz=0;
while(($ww=mysql_fetch_object($wyk)) && $licz<$co_ile_strona) { $licz++;
?>
<a href="<?=strtolower(seo($ww->nazwa))?>-<?=$ww->id?>p.html"><div class="product-box">
<img src="produkty/front/<?=$ww->front?>" alt="<?=$ww->nazwa?>"/>
<div class="name2"><span><?=$ww->nazwa?> </span></div>
</div>
</a>
<?
}
} else echo "<span style='color: #ff0000; font-size: 12pt; font-weight: bold;'>Przepraszamy, ale nie znaleziono produktów pasujących do tego zapytania</span>";
?>
</div>
<div class="menu-bottom" style="text-align:center;">
<span style="position: relative;top: 25px;display: inline-flex;margin-bottom: 20px;">Wybierz serię:
<ul>
<?php
$zapas=$_GET['kat'];
$wyk=mysql_query("SELECT * FROM kategorie WHERE kat='0' and wid='1' ORDER BY poz ASC");
while($ww=mysql_fetch_object($wyk)) {
?> <!--<?/*=$ww->nazwa?>-<?=$ww->id*/?>k.html*/-->
<li> <? if($_GET['kat']==$ww->id) echo "<span style='color: #000;'>".$ww->nazwa.""; else echo $ww->nazwa?></li>
<? } ?>
</ul>
</span>
</div>
<!-- end .content --></div>
link : Click here
As mentioned in the comment, you should send an AJAX request to the page that is responsible for handling the database tasks. You can use get() or post() function which is a shorthand of AJAX function as stated in jQuery documentation.
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
I've prepared a simple jsFiddle demonstrating how the task can be achieved (please note the event.preventDefault() call):
$(document).ready(function(){
$("button").click(function(e){
var URL = '';
$.get(URL,function(data){
console.log("Status: " + status);
e.preventDefault();
});
});
});
Hope that helps.
function showComments(wallID){
$.ajax({
url: "misc/showComments.php",
type: "POST",
data: { mode: 'ajax', wallID: wallID },
success: function(msg){
var $msg = $('#showWallCommentsFor'+wallID).find('.userWallComment');
// if it already has a comment, fade it out, add the text, then toggle it back in
if ( $msg.text().length ) {
$msg.fadeOut('fast', function(){
$msg.text( msg ).slideToggle(300);
});
} else {
// otherwise just hide it, add the text, and then toggle it in
$msg.hide().text( msg ).slideToggle(300);
}
}
});
}
msg, the response i get: ( firebug )
<span class='userWallComment'>
<span style='float: left;'>
<img style='border: 1px solid #ccc; width: 44px; height: 48px; margin-right: 8px;' src='images/profilePhoto/thumbs/noPhoto_thumb.jpg'>
</span></span>
<span style='font-size: 10px; margin-bottom: 2px;'>
<a href='profil.php?id=1'>Navn navn</a> - igår kl. 01:55
</span>
<br>
DETTE ER EN TEST
<br>
<div class="clearfloat"></div>
</span>
It sends and execute the ajax call properly, and it have something in response, but it doesnt toggle it?
This is the div:
<div id="showWallCommentsFor<?php echo $displayWall["id"]; ?>" style="display: none;">
</div>
The Problem
Your if - else statement has a flaw:
if ( $msg.text().length ) {
// ...
} else {
// $msg has a length of ZERO by definition here!!!
$msg.hide().text( msg ).slideToggle(300);
}
The very first time the AJAX call is fired #showWallCommentsFor is empty, so it doesn't have .userWallComment inside it so, $msg will not be defined.
The Solution
You should add text directly to the original div in your else, using:
if ( $msg.text().length ) {
// ...
} else {
// otherwise just hide it, add the text, and then toggle it in
// You cannot use $msg here, since it has a length of 0.
// Add text directly to the original div instead.
// You do not need to hide the DIV first since it is already
// invisible.
$('#showWallCommentsFor'+wallID).text( msg ).slideToggle(300);
}
Finally, in your else, there's no need to .hide() the #showWall... div, since the div is orginally invisible due to style="display: none;".