Having issue while counting clicks of view number using php and javascript - javascript

Am having a issue while counting clicks for viewed numbers. Its working but when i refresh the page then also its updating the database and on click its not updating or inserting.
What i want is that when a user clicks on button, it shows the phone numbers and insert the database in increment.
Code below:
<script type='text/javascript'>
$(document).ready(function(e) {
$('#viewNumber').click(function(showNumber){
document.getElementById('showNumber').style.display = 'block';
document.getElementById('viewNumber').style.display = 'none';
<?php
$countcheck=0;
$checkcounter="SELECT * FROM seo_viewnumber_count WHERE seo_user_id='".$user_id."'";
$resultcheckcounter= mysql_query($checkcounter);
while($rowcheckcounter= mysql_fetch_array($resultcheckcounter))
{
$clickcount= $rowcheckcounter['seo_viewmob_count'] + 1;
$updatecounter="UPDATE viewnumber_count SET seo_viewmob_count='".$clickcount."' WHERE seo_user_id='".$user_id."'";
$resultupdatecounter= mysql_query($updatecounter);
$countcheck++;
}
if($countcheck==0)
{
$insertcounter="INSERT INTO viewnumber_count (seo_user_id, seo_viewmob_count) VALUES ('".$user_id."', '1')";
$resultinsertcounter= mysql_query($insertcounter);
}
?>
});
});
</script>
<button name="viewnumber" id="viewNumber" onclick="showNumber()" class="btn">View Number</button>
<ul id="showNumber" style="display:none;">
<li> 123456</li>
<li> 88888</li>
</ul>

Create a different PHP file for your following code:
<?php
$countcheck=0;
$checkcounter="SELECT * FROM seo_viewnumber_count WHERE seo_user_id='".$user_id."'";
$resultcheckcounter= mysql_query($checkcounter);
while($rowcheckcounter= mysql_fetch_array($resultcheckcounter))
{
$clickcount= $rowcheckcounter['seo_viewmob_count'] + 1;
$updatecounter="UPDATE viewnumber_count SET seo_viewmob_count='".$clickcount."' WHERE seo_user_id='".$user_id."'";
$resultupdatecounter= mysql_query($updatecounter);
$countcheck++;
}
if($countcheck==0)
{
$insertcounter="INSERT INTO viewnumber_count (seo_user_id, seo_viewmob_count) VALUES ('".$user_id."', '1')";
$resultinsertcounter= mysql_query($insertcounter);
}
Then, call that PHP file by AJAX from your client side code when any click will happen by user on button.
Sample jQuery code for making AJAX call:
$.ajax({
method: "GET",
url: "server.php",
})
.done(function( msg ) {
alert( "Counter incremented: ");
});

Related

Display data based on user input

I have a page with 2 columns (Side and Middle)
on the side column, I have a form with a date and a button (View Summary Report).
When the user selects the date and clicks the button, it must fetch the data from the MySQL DB and display the results in the middle column.
When I do a call action to the get_summary_sheet, it displays the info on a new page. This confirms that it is working fine. BUT, I don't want to display it on a new page. I want to display it in the middle column once the user clicks the button.
I was doing research and exploring options to use the onclick function.
Here is my side column:
<div class="column side">
Select Date:
<br>
<input type="date" id="select_summarydate" name="select_summarydate" required><br>
<button onclick="myFunction()">Display Report</button>
</div>
Below is a sample of the code in the PHP file:
$yourDate = $_GET['select_summarydate'];
$sqlpole="select count(*) as totalpole from user where MeterType = 'Pole Mounted' AND Category = 'Inspection' AND Date = '".$yourDate."%'";
$resultpole=mysqli_query($con,$sqlpole);
$datapole=mysqli_fetch_assoc($resultpole);
I need to call the results to the middle column and display it in the table:
<div class="column middle">
* display results of function in php file
</div>
Below is a snippet of the JS code:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script language="javascript">
function myFunction() {
// function below will run get_summary_sheet and should display in middle column
$.ajax({
type: "GET",
url: "get_summary_sheet.php" ,
???????,
???????
});
</script>
What code must go into the Javascript function?
function myFunction() {
var select_summarydate = $('#select_summarydate').val()
$.ajax({
type: "GET",
url: "get_summary_sheet.php" ,
data: {
select_summarydate : select_summarydate
},
success: function(resp){
$('.middle').html(resp)
}
});
}
this is a complete ajax function with sending data and displaying the fetched data in html
your php code will look like below
$yourDate = $_GET['select_summarydate'];
$sqlpole="select count(*) as totalpole from user where MeterType = 'Pole Mounted' AND Category = 'Inspection' AND Date = '".$yourDate."%'";
$resultpole=mysqli_query($con,$sqlpole);
while ($single = $resultpole->fetch_assoc()) {
echo $single['firstcolumn'].' '.$single['secondcolumn']
.'<br>';
}

How can I use jquery events to pass variables to php?

I have a form with a drop-down to select a time for scheduling
I didn't use a selector input, instead I used the following html to make the menu for styling reasons.
<div class="tabs">
<div class="apt-time">
<h3>#Time</h3>
<ul class="time-list">
<li class="available">8:00am</li>
<li class="available">9:00am</li>
<li class="available">10:00am</li>
<li class="available">11:00am</li>
<li class="available">12:00am</li>
<li class="available">1:00pm</li>
<li class="available">2:00pm</li>
<li class="available">3:00pm</li>
<li class="available">4:00pm</li>
<li class="available">5:00pm</li>
</ul>
</div>
</div>
Because of this I can't use the POST method to get the data the user clicked on in the menu. So I tried to come up with a solution that could pass a string variable with events to my php page with the GET method in the code below. The if statements are going to be used so the client can't submit the form without clicking on an option in the menu. Is there a way around this without using a selector input?
$('.available').click(function() {
return clockTime = $(event.target).text()
})
$('.btn').click(function() {
if ($('.available').click) {
window.location.href = "textsms.php?"+clockTime
} else {
// warn client that they need to chose a time
}
})
Added AJAX functionality below. The script passes POST values to PHP script named textsms.php without refreshing browser.
Updated Code:
<script>
$('.available').click(function() {
var clockTime = $(this).text();
$.ajax({
url:"textsms.php",
method:"POST",
data:{'clockTime':clockTime,var2:'2',}, // modify fields
success: function(data){
alert(data); // Do something with data received
},
});
});</script>
For testing..
textsms.php:
<?php
print_r( $_POST );
?>
You're not defining the get variable in the redirection:
window.location.href = "textsms.php?"+clockTime
The following will store the "clockTime" in the $_GET['time']
window.location.href = "textsms.php?time="+clockTime
Edit: Anyway your JS is not correct.
var clockTime;
$('.available').click(function(e) {
clockTime = $(this).text();
})
$('.btn').click(function() {
if(typeof clockTime !== "undefined"){
window.location.href = "textsms.php?time="+clockTime
}else{
// warn client that they need to chose a time
}
});
You can use a control variable for this (also defining a css class that show the selected option):
var selectedTime = '';
$('.available').click(function() {
$('.available').removeClass('clicked');
$(this).addClass('clicked');
selectedTime = $(this).text();
})
$('.btn').click(function() {
if (selectedTime != '') {
window.location.href = "textsms.php?time="+selectedTime;
} else {
// warn client that they need to chose a time
}
})
You need to get the value and pass it to your location properly:
$("ul.time-list").on("click","li.available",function(){
var selectedTime = $(this).text();
window.location.href = "textsms.php?varname="+selectedTime;
});
I like using jquery's on event as it allows you to use load content dynamically so long as you target an external static element.
http://api.jquery.com/on/

aJax update a specific row in sqlite and php using a button

I've got a table that lists values inputted by a user, with 2 buttons on the side to remove or to mark completed. On the page the table is visable, there are 3 tabs, we will call these Tab1, Tab2, and Tab3
Each tab has a table (As described above) with information about a specific type of entry.
These buttons are simple <a href> links, so when clicked they reload the page. This is a problem because the users view is refreshed and it takes the tabs back to the default tab, and is also an inconvenience when trying to mark several entries.
I would like to make these buttons send Ajax requests to another page to process the data. The only problem is, I am not really sure how to make the ajax call.
This is what I have right now
My buttons
echo "<td class='td-actions'>";
echo " <a href='?complete=".$row['uniqueID']."' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'> </i>
</a>
<a href='?remove=".$row['uniqueID']."' class='btn btn-danger btn-small'>
<i class='btn-fa fa-only fa fa-remove'> </i>
</a>";
echo "</td>";
There is one called Complete, and one called Remove.
When either of these are pressed, it currently reloads the page which triggers a few php if statements.
if(isSet($_GET['remove'])) {
$sql = "DELETE from rl_logged where uniqueID='".$_GET['remove']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
if(isSet($_GET['complete'])) {
$sql = "UPDATE rl_logged set complete=1 where uniqueID='".$_GET['complete']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
These are relatively simple functions. My problem is that I do not know javascript very well.
Any help would be much appreciated.
the javascript that I have come up with is this
$(document).ready(function() {
$('#markComplete').click(function() {
var input = input = $(this).text()
$.ajax({ // create an AJAX call...
data: {
onionID: input,
},
type: 'POST', // GET or POST from the form
url: 'pages/ajax/markCompleteRL.php', // the file to call from the form
success: function(response) { // on success..
refreshAllTabsWithFade();
}
});
});
});
using this button
<div name='markComplete' id='markComplete' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'></i>".$row['uniqueID']."
</div>
But, while inspecting with firebug, this seemed to work ONCE, but now the button doesn't do anything.
I tried again this morning, the button presses and the first time it sends this post, then the button doesn't do it again - even on page reload.
I was able to get it to work with the following:
javascript:
$('.markComplete').submit( function( event ) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // serialize the form
type: "POST", // GET or POST from the form
url: "pages/ajax/repairlogMarks.php", // the file to call from the form
success: function(response) { // on success..
refreshAllTabs();
}
});
return false;
});
button:
<form class="markComplete">
<input type="text" style="display:none;" class="form-control" name="uniqueid" value='<?=$row['uniqueID'];?>'>
<input type="text" style="display:none;" class="form-control" name="markcomp" value='1'>
<button type="submit" class="btn btn-success">
<i class="btn-fa fa-only fa fa-check"></i>
</button>
</form>
Basically, I made the button into a form which I knew how to create an ajax request for.
--
Update to make it work for multiple buttons that do the same function for different unique ID's.
Well for since you're sending the ajax call using "POST", it seems to me that if(isSet($_GET['complete'])) would evaluate to false. Also if your button is generated dynamically using php then change your click handler to the following:
$('document').on('click', '#markComplete', function (){
// Your code here
})
If you have more than one "Mark Complete" button; you need to use classes rather than ID to bind the event.
<button id="test">
Test 1
</button>
<button id="test">
Test 2
</button>
<script>
$('#test').click(function (e) {
console.log('test', e.target);
});
</script>
In this example, only the first button works. jQuery will only return the first element when you specify an ID.
If you use classes to bind the event; both buttons will work:
<button class="test">
Test 1
</button>
<button class="test">
Test 2
</button>
<script>
$('.test').click(function (e) {
console.log('test', e.target);
});
</script>
i think you have an error in your javascript at this line...
var input = input = $(this).text()
try to replace by this..
var input = $(this).text();

jQuery How to put a data in HTML (.data)

Hi all i have a question, I have a web page with a datatable filled with data from my DB. I have a columns of checkbox and a button.
When i click on my button, I open a new page that generate an invoice.
I have done a script in jQuery which get the ID of my order with the checkbox.
Code of my check box ( i use bootstrap):
<td><div class="ckbox ckbox-success">
<input type="checkbox" class="select-invoice" data-idcommande="<?= $commande->getId()?>"/>
<label for="checkboxSuccess"></label>
</div>
</td>
This is the code of my button (bootsrap too):
<a class="btn btn-labeled btn-warning" href="facture-facture_groupee.html" id="invoicebtn"> <span class="btn-label"><i class="fa fa-eur"></i></span>Facturer les commandes sélectionnées </a>
Now this is the script i've made when i click on my button:
$( "#invoicebtn" ).click(function() {
$('.select-invoice').each(function() {
$(this).data("idcommande");
});
});
This work fine (I have tested with alert())
But now i want to put the id I've collected in the other page but i don't know how to do it.
Thanks for reading and sorry for my english i'm french.
Use Ajax to communicate between client and server.
Client :
$.post( "test.php", { name: "John", time: "2pm" } );
Server :
if($_POST) {
$name = $_POST['name'];
$time = $_POST['time'];
}
I have found the solution of my question thanks for anwsering it.
this is my JS :
$("#boutonfacturer").click(function () {
var checked = $('input[name="id_commande[]"]:checked');
var tab = [];
checked.each(function () {
var value = $(this).val();
tab.push(value);
});
$.post("genererfacture-facture_groupee.html",
{
id: tab
}
).success(function(retour) {
console.log("Data Loaded: " + tab);
});
});

Add to cart adding first item

I have a simple cart where I can add items on the fly and it update via AJAX. Issue being I am pulling my items from the database but when I click 'add to cart' it populates the cart but with the first item only so no matter which one I click it adds item 1.
I am looping through a result and getting the row:
while ($row = mysqli_fetch_array($r)) {
echo '
<div class="items" id="item">
'.$row["prod_name"]. '';
echo "
<div class='product_display'>
<p><img src='../admin/uploads/".$row['file_upload']."'></p>";
echo"
<input type='button' value='Add To CART' onclick='cart(\"item\");' ";
echo'
<p>Price - '.$row["prod_price"]. '</p>
<input type="hidden" id="item_name" value="'.$row["prod_name"]. '">
<input type="hidden" id="item_price" value="'.$row["prod_price"]. '">';?>
<?php echo'
</div>
</div>
';
}
The echo's really need cleaning up but they confuse me so much!
I am using a little bit of JS to do the AJAX:
$(document).ready(function(){
$.ajax({
type:'post',
url:'store_items.php',
data:{
total_cart_items:"totalitems"
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
});
And my JS does the rest:
function cart(id)
{
var ele=document.getElementById(id);
var img_src=ele.getElementsByTagName("img")[0].src;
var name=document.getElementById(id+"_name").value;
var price=document.getElementById(id+"_price").value;
$.ajax({
type:'post',
url:'store_items.php',
data:{
item_src:img_src,
item_name:name,
item_price:price
},
success:function(response) {
document.getElementById("total_items").value=response;
}
});
}
function show_cart()
{
$.ajax({
type:'post',
url:'store_items.php',
data:{
showcart:"cart"
},
success:function(response) {
document.getElementById("mycart").innerHTML=response;
$("#mycart").slideToggle();
}
});
}
I thought I would share it all so you can see - but the main issue is the fact it just adds item 1 form the list no matter which one you click on - I am getting no errors and the console is giving me nothing?
It is because you are using the same id for all your items. IDs should only be used once per page, and in cases where you are using it multiple times, document.getElementById(id) will only get the first one that it finds which is why you keep on getting the first item in the list only.
You can give each item different ids and pass that id to the cart function. Or to make things simplier, use event delegation (since you're already using jQuery) to listen for clicks on the Add To Cart button so that you don't have to use the onclick attribute anymore. You can do it like this:
$(document).on('click', 'ADDTOCARTBUTTONSELECTOR', function() {
var element = $(this).closest('.items');
var image = element.find('img')[0].src;
var name = element.find('NAMESELECTOR').val();
var price=document.find('PRICESELECTOR').val();
// the ajax part follows here
});
The ADDTOCARTBUTTONSELECTOR, NAMESELECTOR, and PRICESELECTOR are just placeholders to the actual selectors to those elements, and just replace them appropriately to select the proper elements.

Categories

Resources