I have a problem in showing the alert box. This code for the rating star.
rating.js
$(document).ready(function(){
$('.post li').mouseout(function(){
$(this).siblings().andSelf().removeClass('selected highlight')
}).mouseover(function(){
$(this).siblings().andSelf().removeClass('selected');
$(this).prevAll().andSelf().addClass('highlight');
})
$('.post li').click(function(){
$(this).prevAll().andSelf().addClass('selected');
var parent = $(this).parent();
var oldrate = $('li.selected:last', parent).index();
parent.data('rating',(oldrate+1))
data = new Object();
data.id = parent.data('id');
data.rating = parent.data('rating')
$.ajax({
url: "add_rating.php",// path of the file
data: data,
type: "POST",
success: function(data) {
}
});
})
/* reset rating */
jQuery('.post ul').mouseout(function(){
var rating = $(this).data('rating');
if( rating > 0) {
$('li:lt('+rating+')',this).addClass('selected');
}
})
})
add_rating.php
<?php
include("dbconnection.php");
session_start();
$myid = $_SESSION['id'];
// echo "".$myid;
$sql_notification ="SELECT * FROM table_user_skills where user_id='$myid' and rating=5";
$result = $conn->query($sql_notification);
$count = 0;
while ($row=$result->fetch_assoc()) {
if ($row['rating']==5) {
$count = $count +1;
}
}
// echo "Count: ".$count;
if(!empty($_POST["rating"]) && !empty($_POST["id"])) {
$myrate=$_POST["rating"];
if($count<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Less than 5");';
print '</script>';
} else if($myrate<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Rate Less than 5");';
print '</script>';
}else if($count>5){
print '<script type="text/javascript">';
print 'alert("Lpas 5 stars");';
print '</script>';
}
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE skills_id='" . $_POST["skills_id"] . "'";
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE user_id='" . $_POST["userid"] . "' and skills_id='" . $_POST["id"] . "' and category_id='" . $_POST["category"] . "'";
}
?>
My problem is that the alert box is not showing. I have to limit the number of 5 stars being updated. If anyone could help me figure out what's wrong with my code, I would appreciate it.
Look at the success callback function for your AJAX call - it's empty. You're having PHP print out the alert box code in the ajax call and then never doing anything with that output.
To make the alert show up, you would have to append the code your AJAX call returns to the DOM. However, it would probably be better to just return just the message and let the JavaScript code take care of raising the alert box. Just a simple alert(data) should do the trick.
Related
I'm having a hard time getting the value of a specific variable in php to use in js. This is my code in php:
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
}
?>
I want to get the value of this ($result['status']) and pass it on the variable pos in js. This is my js code:
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
var pos = $('PHP VARIABLE HERE').val();
alert(pos);
}
Thanks for your help.
The easiest way is to output it to javascript directly:
?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...
window.MY_PHP_VAR now contains your php variable
if your javascript code is on same page where the result is comming then you can use this
var pos = `<?php echo $result['status'] ?>`;
var pos = `<?= $result['status'] ?>`;
===============
// refresh.php
===============
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
echo "<script> alert('". $result['status'] ."'); </script>";
/* If the $result['status'] is 'success' the above line will be converted to:
echo "<script> alert('success'); </script>";
*/
}
?>
so, every time the refresh.php loads, the script is going to get executed.
However, I suggest you to assign a id or class attribute to your h4 where you are echoing your status and access the value using the selectors in the javascript.
you could try giving an id or class to the status.
then in JavaScript you could then get the value of the id or class.
PHP
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}
?>
JavaScript
var oldStatus = '';
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
// note that since we used a class, you will get the value of the first element only.
var pos = $('.status').text(); // use .text() instead of .val()
if (pos.toLowerCase() == 'out' && pos != oldStatus){
oldStatus = pos;
alert(pos);
}
}
I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.
I am very new to using AJAX and passing data with json_encode. I have this "aht" button when clicked it will send an AJAX request to my show_aht.php script, which will run a query. I want to save the results and display it to my map.php.
Problem:
In my map.php I have a while loop that outputs square(desk) DIVs with another DIV(station) when clicked that displays content inside of it. Here is the fiddle so you may understand. I want the results of show_aht.php "TIME" to be displayed in the DIVs being produced by my WHILE LOOP in map.php.
How is it possible to do this? I know that AJAX and PHP cannot interact with eachother and thats why I need help. If this can't be done, how else can I display the TIME from show_aht.php to their corresponding usernames on each DIV being output? I have around 200 of them being displayed.
Thanks in advance.
map.php (only showing the last line of the while loop, outputs all DIVs)
//desk DIV
while(somequery){
....
echo '<div class="' . $class . '" data-rel="' . $id . '" style="left:' . $x_pos . 'px;top:' . $y_pos.'px;">' . $sta_num . '</div>' . "\n";
}//end while
//station DIV
while(some query){
.....
echo '<div class="station_info_" id="station_info_' . $id . '" style="left:' . $x_pos . 'px;top:' .$y_pos . 'px;"><p class="numb">User:' . $user .'<br>Station:' . $hostname . '<br>Pod:' . $sta_num . '<br>Section:' . $sec_name . '<br>State:' . $state .'<br></p></div>' . "\n";
}//end while
map.php (AJAX part)
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht.php (showing the loop and part I where I want the data to be returned)
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo "User: " . $m . " Time: N/A <br>";
}
}
}
Don't output anything except one valid json string. In your case you do that by replacing the echo's with building an array (or object...) and output that at the very end:
For example:
$data = array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$data[] = " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
$data[] = "User: " . $m . " Time: N/A <br>";
}
}
}
// Output your json string
echo json_encode($data);
Note that I have simply replaced your echos with an assignment but you could also add arrays in your array to return just the data parts and process that afterwards in javascript.
For example (this would depend a bit on your exact data structure...):
...
$data[] = array($m, $v['avg_handle_time']);
...
change show_aht.php to
$res=array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$res[]= " User: " .$m. " Time: " . $v['avg_handle_time'];
}
elseif( $v['memo_code'] != $m){
$res[]= "User: " . $m . " Time: N/A <br>";
}
}
}
echo json_encode($res);
and map.php ajax to
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
for(i=0;i<data.length;i++){
//append data[i] to div
}
}//end success
});//end ajax
});//end click
});//end rdy
I currently have this function exactly how I want it except for the jQuery at the bottom in which I am only alerting and not creating a real variable. It all works but I am stuck on how I can take all of the data from the jQuery script and then make it into a variable so that I can bring it to another page? Any ideas, NEED HELP!
function getGrade($id, $grades_array) {
$counter = 0;
$sql = "Select grade FROM grades";
$result = mysql_query($sql) or die (mysql_error());
echo '<select name="grades_selected" multiple="multiple" id="grades_selected">';
while ($row = mysql_fetch_array($result)) {
if ($row['grade'] != $grades_array[$counter]) {
echo "<option>" . $row['grade'] . "</option>";
} else {
echo "<option selected=" . $row['grade'] . ">" . $row['grade'] . "</option>";
$counter = $counter + 1;
}
}
mysql_free_result($result);
echo '</select>';
$_SESSION['test'] = $grades_array;
?>
<script>
$(document).ready(function() {
$('#grades_selected').change(function() {
alert($(this).val());
});
});
</script>
<?
}
You need to use ajax within on change function:
$(document).ready(function() {
$('#grades_selected').change(function() {
var variable = $(this).val();
$.ajax({
type: 'post',
url: 'target_page.php',
data: {variable : variable},
success: function (res) {
alert(res);
}
});
});
});
On target_page.php:
echo $_POST['variable'];
I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket