How can i count video view in php without refreshing page - javascript

This is my code check and gives me any suggestions Thanks StackOverflow team
<video onclick="
<?php
$slectips = "SELECT * FROM unique_visitors WHERE ipaddress = '$uuser_id'";
$checkipNumber = mysqli_query($conn,$slectips);
$numbersofviews = mysqli_num_rows($checkipNumber);
if($numbersofviews==0)
{
$insertips = "INSERT INTO `unique_visitors`(`ipaddress`) VALUES ('$uuser_id')";
$Ipquery = mysqli_query($conn,$insertips);
if($Ipquery==true)
{
$insertview = "UPDATE `videos` SET `views`= views +1 WHERE id = '".$row['id']."'";
$Viewquery = mysqli_query($conn,$insertview);
if($Viewquery==true)
{
echo "<script>alert('Suceessfully Ips Adress And Views Inseted');</script>";
}
else
{
echo "<script>alert('ERROR UPDATING VIEW');</script>";
}
}
else
{
echo "<script>alert('ERROR INSERTING IPS YOUR IP MATCH');</script>";
}
}
else
{
echo "<script>alert('Your Ip AVAILABLE IN DATABASE');</script>";
}
?>
" id='my_video' src="<?php echo $images; ?>" controls></video>
please help me I don't know how can I count video view and insert into the database in PHP without refreshing page

As i say here a example on how to use AJAX with ONCLICK
//page one1
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<video onclick="sendcount('<?php echo $uuser_id;?>')" id='my_video' src="<?php echo $images; ?>" controls></video>
<script>
function sendcount(uuser_id)
{
$.ajax({
type: "POST",
url: "page2.php",
data: {"uuser_id":uuser_id},
async: true,
success: function(data){
var obj = JSON.parse(data);
alert(obj.msg);
}})
}
</script>
</body>
</html>
// page 2
<?php
$uuser_id=$_POST['uuser_id'];
$msg='';
$slectips = "SELECT * FROM unique_visitors WHERE ipaddress = '$uuser_id'";
$checkipNumber = mysqli_query($conn,$slectips);
$numbersofviews = mysqli_num_rows($checkipNumber);
if($numbersofviews==0)
{
$insertips = "INSERT INTO `unique_visitors`(`ipaddress`) VALUES ('$uuser_id')";
$Ipquery = mysqli_query($conn,$insertips);
if($Ipquery==true)
{
$insertview = "UPDATE `videos` SET `views`= views +1 WHERE id = '".$row['id']."'";
$Viewquery = mysqli_query($conn,$insertview);
if($Viewquery==true)
{
$msg="alert('Suceessfully Ips Adress And Views Inseted');";
// echo "<script>alert('Suceessfully Ips Adress And Views Inseted');</script>";
}
else
{$msg="ERROR UPDATING VIEW";
// echo "<script>alert('ERROR UPDATING VIEW');</script>";
}
}
else
{$msg="ERROR INSERTING IPS YOUR IP MATCH";
//echo "<script>alert('ERROR INSERTING IPS YOUR IP MATCH');</script>";
}
}
else
{$msg="Your Ip AVAILABLE IN DATABASE";
//echo "<script>alert('Your Ip AVAILABLE IN DATABASE');</script>";
}
$json_data = array(
"msg" => $msg,
);
echo json_encode($json_data); // send data as json format
die;
?>

Related

How to solve this "Uncaught ReferenceError: $ is not defined"

I have some code where I need to update a column of a table (MySQL) calling another php file without leaving the page where some tables might allow inline editing.
I have a point in the php echoing of the page, where an icon can be clicked to save input. The code at that point is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
// some tabled elements not relevant for the issue
echo "<input type='text' id='note_1' name='note_1' value=$note readonly>";
echo "<input type='text' id='new_note' name='new_note'>";
echo "<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
?>
<script type="text/javascript">
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = document.getElementById('note_1').value;
var code_val = '<?php echo "$code" ?>';
var note_new = document.getElementById('new_note').value;
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
document.getElementById('note_1').value = note_new;
}
});
}
});
});
The relevant code of update_notes.php is:
<?php
// connection
$unsafe_note = $_POST["note"];
$code = $_POST["code"];
require "safetize.php"; // the user input is made safe
$note = $safetized_note; // get the output of safetize.php
$sqlupdate = "UPDATE table SET note='$note' WHERE code='$code'";
if (mysqli_query($conn, $sqlupdate)) {
echo "Note updated";
} else {
echo "Problem in updating";
}
// close connection
?>
Now when I run the code and look at the tool, it gives me the error: Uncaught ReferenceError: $ is not defined, linking the error to this line of the previous js code:
$(document).ready(function() {
So, how can I fix that?
It means that you tried to use Jquery in your Javascript Code without calling Jquery Library or the code is called without the library was fully loaded.
I notice :
That you haven't closed your script tag
You use Jquery so you can use $('#id_name') to select element by Id instead of document.getElementById('note_1')
Get element value by using Element.val() instead of Element.value
Try to edit your code like this
<?php
$sql = "SELECT * FROM table WHERE a_column='certain_value'";
if (mysqli_query($conn, $sql)) {
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$note = $row["note"];
$code = $row["code"];
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Some title</title>
</head>
<body>
<form method="post" accept-charset="UTF-8">
<input type='text' id='note_1' name='note_1' value=<?= $code ?> readonly>";
<input type='text' id='new_note' name='new_note'>";
<img src='icon_to_click.png' id='icon_to_click' name='icon_to_click' >";
</form>
<script>
$(document).ready(function() {
$('#icon_to_click').click(function() {
var note_orig = $('#note_1').val();
var code_val = '<?= $code ?>';
var note_new = $('#new_note').val();
if (note_new != note_orig) {
$.ajax({
type: 'POST',
url: 'update_notes.php',
data: {'code': code_val, 'note': note_new},
success: function(response){
$('#note_1').val() = note_new;
}
});
}
});
});
</script>
</body>
</html>
Hey I have faced same error a day before,this is because you have missed using a jquery library script that is needed. please try using some Updated Jquery CDN . :) It will definitely help
OR
include the jquery.js file before any jquery plugin files.

How to display values in JS from a PHP array that was posted from jQuery

I have a button called rename that when pushed, executes in jQuery a rename.php file. Inside that php file the program selects data from a mysql, creates an array with that data, and processes an array in to json_encode($array);. How can I then get that json encoded array and echo it out into javascript?
I'm trying to echo the array out so that javascript displays my images src's.
This is my second line of ajax so I just wrote the javascript out as if it were php because I'm not sure of the commands or structure in js.
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
/*alert(result);*/
document.getElementById("images_to_rename").innerHTML = foreach(jArray as array_values)
{
"<img src=\""array_values['original_path']"/"array_values['media']"/>";
}
}
}
);
and my jQuery php file:
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if(empty($_GET['image_name']))
{
echo '<div class="refto" id="refto">image_name is empty</div>';
}
else
{
echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach($_GET['image_name'] as $rowid_rename)
{
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE ".$username." SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$arri[] = $row;
}
foreach($arri as $rows) //put them into workable variables
{
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
?>
<script type="text/javascript">
var jArray= <?php echo json_encode($arri); ?>;
</script>
<?php
}
echo "something2";
?>
My PHP file is a jQuery url:"test4.php", type: "GET", and is not the main file. The main file is called main.php and the test4.php is something that's called in jQuery when the user clicks on rename.
Somebody suggested console log so here's what chrome says:
<div class="refto" id="refto">image_name is not empty</div>[{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}] <script type="text/javascript">
var jArray= [{"original_path":"Downloads","media":"shorter.jpg"},{"original_path":"Album 2","media":"balls.jpg"}];
</script>
something2
Your ajax php file isn't render in browser, then the variable jArray is undefined. With your case, let return php file to json and you can get it as variable in result.
<?php
include 'db/mysqli_connect.php';
$username = "slick";
if (empty($_GET['image_name'])) {
//echo '<div class="refto" id="refto">image_name is empty</div>';
} else {
//echo '<div class="refto" id="refto">image_name is not empty</div>';
foreach ($_GET['image_name'] as $rowid_rename) {
//echo '<br><p class="colourful">rowid_refto: '.$rowid_refto.'</p><br>';
$active = 1;
$command = "Rename";
$stmt = $mysqli->prepare("UPDATE " . $username . " SET active=?, command=? WHERE rowid=?");
$stmt->bind_param("isi", $active, $command, $rowid_rename);
$stmt->execute();
$stmt->close();
}
//go to database, get parameters of sort
$command = "Rename";
$active = 1;
$stmt = $mysqli->prepare("SELECT original_path, media FROM " . $username . " WHERE active=? and command=?");
$stmt->bind_param("is", $active, $command);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$arri[] = $row;
}
foreach ($arri as $rows) { //put them into workable variables
$rowt = $rows['original_path'];
$rowy = $rows['media'];
//echo 'rows[\'original_path\'] = '.$rows['original_path'].''.$rows['media'].'';
}
$stmt->close();
echo json_encode($arri);
//stop render here
die();
}
?>
php file need return only json string. Then we'll get result as json variable in javascript.
And Js:
$.ajax
(
{
url:"test4.php",
type: "GET",
data: $('form').serialize(),
success:function(result)
{
var jArray = JSON.parse(result);
/*alert(result);*/
var txt = "";
jArray.forEach(function(array_values){
txt += `<img src=\""array_values.original_path."/"array_values.media"/>`;
})
document.getElementById("images_to_rename").innerHTML = txt;
}
}
);

Updating Edited Value Using Jquery/PHP/Mysql

can some one help me out in updating edited value in mysql db using jquery/php.
I have three buttons edit/save/cancel
when i click on edit button span data pushed into input text and edit button replaced with save button!!
when i click on edit button i'll get span data in my text box with save and cancel button but when i try to update using save button its not updating in my db and in UI
Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function showdata()
{
$.ajax({
url:"pages/feeds.php",
type:'post',
async:false,
data:{
showtable:1
},
success:function(re){
$('#showdata').html(re);
}
});
}
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault(e);
var $li = $(this).closest('li'); $li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault(e);
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
//UPdate Ends
</script>
<style type="text/css">
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
</style>
</head>
<body>
<ul id="orders">
<?php
$sql = "select * from demo";
$result = mysql_query($sql);
while($row = mysql_fetch_object($result))
{
?>
<li>
<span class="noedit name" value='<?php echo $row->id;?>'><?php echo $row->url;?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php } ?>
</ul>
</body>
</html>
<?php
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
?>
Alright. I was still missing the following code from you, so you'll have to add these yourself:
The HTML element with parameter id="id" needed for $('#id').val(text.id);
The HTML element with parameter id="url1" needed for $('#url1').val(text.url);
The PHP response code for JS function showdata(); inside feeds.php
Since I don't have your database here, I was unable to test the code. It should work fine, but if anything is wrong, just let me know:
PHP file: index.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- CSS resources -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Javascript resources -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="main.js"></script>
<title>Update Script</title>
</head>
<body>
<ul id="orders">
<?php
// Instantiate database
$db = new Database;
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM demo");
// Get results
$data = $db->resultset();
// Echo reults
foreach($data as $row){ ?>
<li>
<span class="noedit name" value="<?php echo $row['id']; ?>"><?php echo $row['url']; ?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row['id']; ?>" />
<a data-ide="<?php echo $row['id']; ?>" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a data-idu="<?php echo $row['id']; ?>" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a data-idd="<?php echo $row['id']; ?>" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a data-idc="<?php echo $row['id']; ?>" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php }
//Catch any database errors
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
?>
</ul>
</body>
</html>
Javascript file: main.js
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault();
var $li = $(this).closest('li');
$li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault();
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('data-ide');
$.ajax({
url: "pages/feeds.php",
type: "POST",
data: 'editvalue=1&id='+IdEdit,
success: function(text){
$('#id').val(text.id);
$('#url1').val(text.url);
}
});
});
//Update Code
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'update=1&id='+id+'&upurls='+urls,
success: function(text){
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('Error in updating');
}
});
});
function showdata(){
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'showtable=1',
success:function(text){
$('#showdata').html(text);
}
});
}
CSS file: style.css
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
PHP file: feeds.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
// Instantiate database
$db = new Database;
// Edit
if(isset($_POST['editvalue']) && $_POST['editvalue'] == 1){
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM deccan WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":id", $_POST['id']);
// Get result
$data = $db->single();
// Set header JSON
header("Content-type:text/x-json");
// Return result
echo json_encode($rows);
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['update']) && $_POST['update'] == 1){
// Try updating data in database
Try {
// Query
$db->query("UPDATE deccan SET url = :url WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":url", $_POST['upurls']);
$db->bind(":id", $_POST['id']);
// Execute Query
$db->execute();
// Return succes
echo 'updated successfully';
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['showtable']) && $_POST['showtable'] == 1){
/*
This part was not included in your code, so write it
yourself using above data as examples
*/
}
?>
PHP file: pdo.class.php
<?php
Class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
return $this->error;
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function column(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_COLUMN);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
?>
I would normally have two scripts (.php) files.
One to display the form and one to catch the submission (possibly via ajax)
You can have both in the same .php file but then you'd want to check before outputting any text whether you have any POST data to process.
If you go with two files
view file:
<html>
<body>
<form method="POST" action="path/to/formname_submit.php">
your form fields go here
<input name="somefield"/>
...
</form>
<script>
//your jquery code
....
</script>
<body>
</html>
submit file
<?php
if (empty($_POST['id'])){
die("no ID");
};
if (empty($_POST['editvalue'])){
die("no editvalue");
}
//get a database connection
$db = mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
$db->set_charset("utf8");
// read in the POST data
//should do some more validation / anti SQL injection
$editvalue = $db->escape_string($_POST['editvalue']);
$id = intval($_POST['id']);
$sql = "UPDATE sometable SET `field` = '$editvalue' WHERE id=$id";
if ($db->query($sql)){
echo 'Success';
}
else {
echo 'UPDATE ERROR:'.$db->errno.': '.$db->error;
}
your jquery can now send the data to the second script and see if the data coming back from the call is 'Success' and display an error if it's not.

How to hide the check box after the form submit

Hello friends this i am facing some problem...I have multiple check boxes and by selecting each check box i am inserting the users details to database by Ajax. the records records are inserting to database but my problem is that , suppose i have 5 users in the page, suppose i am selecting the 3 user check boxes and submit , and if the insertion succeed then i want that the 3 selected users will not shown on page. i use Google many tips but can't solve the problem.
//this is the menu.php
<li class="invitetab"><span>Invite</span></li>
$('.invitetab').one('click', function(){
var rp = '<?php echo $baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $_SESSION['db_user_info']['id'] ?>';
$( document ).ready(function() {
$.ajax({
url: ""+rp+"invite.php?pageid="+v+"&userid="+userid,
type: 'POST',
beforeSend: function()
{
$("#loading_img").show();
},
success: function(data)
{
$("#loading_img").hide();
$("#Invite").append(data);
}
});
});
});
//And this is the invite.php
$('.gr-post-btn-submit').click(function(){ // when a feature button is selected
var rp = '<?php echo $config->baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $user_id ?>';
var serialize = $('.abc').serialize(); // takes all the values of the filter
$.ajax({
type : 'POST',
url: ""+rp+"sendinv.php?pageid="+v+"&userid="+userid, // sends the values to ajax file
data : serialize,
beforeSend: function()
{
$("#loading_own").show();
$("#Invite").css({ opacity: 0.5 });
},
success: function(data)
{
$("#loading_own").hide();
$("#Invite").css({ opacity: 5.6 });
// $("#Invite").show();
//this is the portion where we have to do some thing to hide the inserting check boxes
}
});
});
<form method="post" class="abc" id="" name="inviteform"
enctype="multipart/form-data" action="#">
<?php
$sql = "select * from gr_user_friendships where toid=$user_id and status = 1";
$pagd = $_GET['pageid'];
$liked_users = $db->select($sql);
$count = 0;
for($i=0; $i<count($liked_users); $i++)
{
$extrct_fr = "select * from gr_page_likes where page_id=".$pagd." and receiver_id=".$liked_users[$i]['fromid'];
//echo $extrct_fr;
$frnd = $db->select($extrct_fr);
if(count($frnd)>0)
{
$invt = $db->select("select * from gr_user_friendships where toid=$user_id and fromid!=$frnd[0]['receiver_id']");
$invt_id = $invt[0]['fromid'];
}
else
{
$invt_id = $liked_users[$i]['fromid'];
}
if(!empty($invt_id))
$count = 1;
$user = "Select * from gr_users where id = $invt_id";
//echo $user;
$table = mysql_query($user);
$dbc = mysql_fetch_array($table);
$usid= $dbc['id'];
$bab = $dbc['name'];
$imgs = $dbc['avatar'];
$image_of_fr = $_SERVER['DOCUMENT_ROOT']."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
$image_location_f = $config->baseUrl."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
if(file_exists($image_of_fr))
{
$imgp = $image_location_f;
}
else
{
$imgp = $config->baseUrl."/themes/gr-mist/includes/images.jpg";
}
if(!empty($invt_id)){
?>
<style type="text/css">
#users_<?php echo $invt_id ?>
{
width:147px;
height:54px;
display:inline-block;
}
</style>
<input type="checkbox" class="checkbox1" id="gcc_<?php echo $invt_id ?>" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
<?php
}
}//end of for
?>
<br>
<?php if($count){ ?>
<span style="color:blue; font-weight:bold;" >
<input type="checkbox" id="selecctall"/> Select All</span>
<input type="button" name="gr_submits" class="gr-post-btn-submit" value="invite" id="submits"/>
<?php } ?>
</form>
and this is the sendinv.php
global $db;
$myliker = $_POST['pgliker'];
$pageid = $_GET['pageid'];
$userid = $_GET['userid'];
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
}
/**In you invite.php put the element which you want to hide after success
form submission into one div*//
//replace your one with this one.
<div id="gcc_<?php echo $invt_id ?>">
<input type="checkbox" class="checkbox1" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
</div>
/**Now make an array in your sendinv.php and encode it with json incode***/
//replace your sendinv.php with this one.
$arr = array();
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
$arr[] = $tps;
}
echo json_encode($arr);
exit;
/**After in your invite.php in the success block run
jquery foreach with the data and hide the checked boxes with the ids associted after submission. */
$.each( data, function( key, value ) {
// alert( key + ": " + value );
$("#gcc_"+value).hide();//the div for each checked user
});

PHP variable not being passed to AJAX call?

Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>

Categories