I want to make my Bootstrap Modal appear only when there is an AJAX response. Otherwise, I want this Bootstrap Modal to be hidden.
I have done the below. However, it does not work properly. The Modal keeps showing even if there is no response.
JavaScript:
<script>
//$(dialog).close();
$(".dialog").parent().hide();
// execute alerts ajax function every 1 second
setInterval(alerts, 10000);
function alerts(){// define alerts function
$.ajax({ //create an ajax request to alerts.php
type: "GET",
url: "alerts.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#myModal").modal();
$("#modalbodyscreen").html(response);
$.playSound('http://alixali.com/taxiapp/taxiappbeep');
}
});
}
// close and delete modals every 10 seconds
setTimeout(function(){
//$(dialog).close();
$(".dialog").parent().hide();
}, 10000);
</script>
alerts.php
<pre>
ini_set('display_errors', 'On');
session_start();
$driver_id = $_SESSION['userId'];
include "header.php";
$result = mysql_query("SELECT * FROM alerts WHERE driver_id = '$driver_id'");
$num = mysql_num_rows($result);
if ($num != 0) {
while($data = mysql_fetch_row($result))
{
echo "<h5>Contact No:</h5><br>";
echo $data[1]."<br>";
echo "<h5>Address:</h5><br>";
echo "https://www.google.com/maps/preview/#".$data[3].",".$data[2].",16z"."<br>";
echo "<h5>Distance (km):</h5><br>";
echo $data[5];
$_SESSION['distance'] = $data[5];
}
$delete_result = mysql_query("DELETE FROM alerts WHERE driver_id = '$driver_id'");
}
</pre>
Please advise and get me with your recommendations/solutions as soon as possible.
You can see this app on:
http://www.alixali.com/taxiapp/
Driver login:
username 1111
password 1111
Passenger login:
username ali
password 12345678
Regards,
Alixali
change $("#myModal").modal(); to $("#myModal").modal("show");
and to hide the modals use $(".myModals").modal("hide");
here's a link to the bootstrap API documentation on modals
try this
success: function(response){
if(response != '')
{
$("#myModal").modal('show');
$("#modalbodyscreen").html(response);
$.playSound('http://alixali.com/taxiapp/taxiappbeep');
}
}`
Related
I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps
I am trying to build an costum login to Wordpress in a AJAX call. I a remove the wp_signon() from the PHP function I do get the right echo. But then I add the wp_signon() it always return my whole login page in HTML. I can't see what I am doing wrong. And can't get the login to work.
Please help!
js
$.ajax({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
'action': 'getLoggedIn',
'user_name': user_name,
'user_password': user_password,
'user_remember': user_remember
},
success: function(response) {
if (response === 'ok') {
window.location = '/app/';
}
},
error: function(){}
});
PHP
function getLoggedIn() {
global $wpdb;
// Check if users is already logged in
if ( is_user_logged_in() ) {
echo 'You are already logged in';
die;
}
//We shall SQL escape all inputs
$username = $wpdb->escape($_REQUEST['user_name']);
$password = $wpdb->escape($_REQUEST['user_password']);
$remember = $wpdb->escape($_REQUEST['user_remember']);
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = $remember;
$user_signon = wp_signon( $creds, false );
// Check if error
if ( is_wp_error($user_signon)) {
echo $user_verify->get_error_code();
exit();
} else {
echo 'ok';
exit;
}
die();
}
add_action('wp_ajax_getLoggedIn', 'getLoggedIn');
add_action('wp_ajax_nopriv_getLoggedIn', 'getLoggedIn');
The problem was not the wp_signon() function. It was an other Wordpress action that redirects the page after user login has failed. This:
add_action( 'wp_login_failed', 'login_failed' );
I got caught up in the same situation. did you remove that wp_login_failed action or how did you work this out?
My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function () {
var k = document.getElementById("balanceNumber");
k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
}
}
);
}
and the handler.php
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
//$link = mysqli_connect("localhost","username","password", "users");
$bal = $userRow['userBalance']+$_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
Can anyone suggest me how to update this information without refreshing the page?
The issue is that you are trying to run php in the client side when you wrote k.innerHTML="string"+php code
You should instead produce an output in the php file you request to and retrieve that output and put it in here.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
The link explains how to send data to server through POST and get data from server through GET.
there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type:
$.ajax({
'url': 'getdata.php',
'type': 'GET',
'dataType': 'json',
'data': {'topUpBalance':d},
'success': function(data) {
// if the request calls properly
},
'error': function(data) {
// if the request fails.
}
});
The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-
if(isset($_POST['topUpBalance'])){
$res=mysqli_query($link, "SELECT * FROM users WHERE
userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
$bal = $userRow['userBalance'] + $_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
//Send output echo ...... ;
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
In jquery side :-
receive data using parameter
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function (data) {
// use sent data or unsent data for processing
}
}
);
}
I'm currently into developing simple 'one score' votting system and I'm facing the problem: though php script workd fine I cant get AJAX updating the answer div without reloading page. I've tried different methods, some do nothing, other reload page, for example, I've tried adding (return: false) after AJAX or PreventDefault in it. Here is html and php index page:
<body>
<div align="center">
<h3>Voting with jQuery, Ajax and PHP</h3>
<?php
include('config.php');
$sql=mysqli_query($bd, "SELECT * FROM messages LIMIT 9");
while($row=mysqli_fetch_array($sql))
{
$msg=$row['msg'];
$mes_id=$row['mes_id'];
$total_score=$row['total_score'];
?>
<div id="main">
<div class="box1">
<img class='image'src="img/thumbsup.png">
<span class='this'><?php echo $total_score; ?></span><div class='tr'></div>
<img class='image' src="img/icon-down.png"></div>
<div class='box2' ><?php echo $msg; ?></div>
</div>
<?php
}
?>
</div>
</body>
And here is my working up_vote.php (down_vote.php is almost same, so I wont add it)
<?php
include("config.php");
$ip=$_SERVER['REMOTE_ADDR'];
if($_POST['id'])
{
$id=$_POST['id'];
$ip_sql=mysqli_query($bd,"select ip_add from Voting_IP where mes_id_fk='$id' and ip_add='$ip'");
$count=mysqli_num_rows($ip_sql);
$sql = "update Messages set total_score=total_score+1 where mes_id='$id'";
mysqli_query($bd, $sql);
$sql_in = "insert into Messages (mes_id_fk,ip_add) values ('$id','$ip')";
mysqli_query($bd, $sql_in);
$count=mysqli_num_rows($ip_sql);
}
?>
And finally, the complete JQUERY - AJAX script (this's my problem - need to show the results in (div class = 'this') without refreshing the page):
$(function() {
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success:function(data){
$(".this").append(data);
},
complete: function() {alert('complete');};
});} else
{
$(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle" style="height: 10px;width:10px;">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false
}).done(function ( data ) {
$('.this').append(data);
});
}
return false;
});
});
I have spent whole my day and I know the solution is obvious, Im just really new in this all and so I would appreciate any helpful response. Thanks in advance.
I have added this code to up_vote.php at the buttom:
$result=mysqli_query($bd, "select total_score from Messages where mes_id='$id'");
$row=mysqli_fetch_array($result);
$up_value=$row['total_score'];
echo $up_value;
Thanks to all of you guyz!!! It works now! The problem was that php script didnt return anything!!! As I though - obviouse))) THANKS!
HAve NEW PROBLEM NOW - WHEN I CLICK ON ICONS IT UPDATES ALL OF THEM!! IN EVERY DIV! I VOTE FOR ONE THING - AND IT ADDS VOTES FOR EACH ONE!! whats wrong with that?
I have tried to get this to work for a while now.
When I load new Ajax content into my accordion, then the new content won't work. The preloaded content works just fine, both before and after.
I have added my code here
I know you can't run the script with ajax, since my config and mysql runs local.
Here is my "update-data.php":
<?php
include('../../includes/config.inc.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
$query = "INSERT INTO messages(msg,name) VALUES ('$content','$name')";
mysqli_query($sqlCon, $query);
//mysqli_query("insert into messages(msg) values ('$content')");
$sql_in= mysqli_query($sqlCon, "SELECT msg,msg_id,name FROM messages order by msg_id desc");
$r=mysqli_fetch_array($sql_in);
$msg=$r['msg'];
$name=$r['name'];
$msg_id=$r['msg_id'];
}
?>
<div class="accordionButton"><?php echo $msg_id; ?>:<?php echo $name; ?></div>
<div class="accordionContent" style="display: block;"><?php echo $msg; ?></div>
Thanks for your help
Here are the ajax call:
<script type="text/javascript">
$(function() {
$(".comment_button").click(function()
{
var element = $(this);
var boxval = $("#content").val();
var bval = $("#name").val();
var dataString = {content:boxval,name:bval};
if(boxval=='')
{
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "<?php echo $total_path.'/update_data.php'; ?>",
data: dataString,
cache: false,
success: function(html){
$("div#wrapper_ac").prepend(html);
$("div#wrapper_ac .accordionButton:first").slideDown("slow");
document.getElementById('content').value='';
document.getElementById('name').value='';
$("#flash").hide();
}
});
}
return false;
});
</script>
You php is fine, just clean your inputs please and look into PDO
You can read about cleaning inputs here and PDO here
In your js I think your problem is your on statement
$('.accordionButton').on('click', function() {
// DO stuff
});
I think it's just not bubbling up the DOM far enough to capture new data, it's adding he click event onto all accordion buttons and listening for them.
Change it to this
$('#wrapper_ac').on('click', '.accordionButton', function() {
// DO stuff
});
This places the listener on #wrapper_ac so any click events that happen underneath will be caught.
Hope this helps
Edit: For more info on PDO check this site http://www.phptherightway.com/#databases