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

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);
});
});

Related

How to submit form when any value selected from populated textbox using javascript or jQuery without clicking submit button

search.php
In this form, when we type something in textbox, matching words are fetched from api_search.php page and displayed as seen in attached screenshot.
<form role="form" id="frm_search" name="frm_search" method="POST" action="./api_search_p.php" enctype="multipart/form-data" >
<script type="text/javascript">
$(function()
{
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php'
});
});
</script>
<input type="text" id="txt_itemname" name="txt_itemname" class="form-control" required data-validation-required-message="Please enter something here">
<button type="submit" class="btn btn-warning"><i class='fas fa-search'></i> </button></span>
</form>
api_search.php
Textbox on search.php is populated from API result data from this page.
-- API data are coming using curl in $result array --
$json = json_decode($result, true);
$arr_searchTerm = array();
if (is_array($json) && !empty($json))
{
foreach ($json as $key1 => $level1)
{
if (is_array($level1) && !empty($level1))
{
foreach ($level1 as $key2 => $level2)
{
array_push($arr_searchTerm, $level2['TITLE']);
}
}
}
}
echo json_encode($arr_searchTerm);
Currently need to click submit button to submit the form. But I want to do so when any word from fetched result is selected / clicked then form should be submitted immediately without clicking submit button.
I tried onselect="this.form.submit()" & onchange="this.form.submit()" with textbox but form is not submitted on any of javascript events.
Please let me know how can I make this working as expected.
Screenshot
You can use select function in your code
$( "#txt_itemname" ).autocomplete({
source: '../user/api_search.php',
select: function(e, ui){
this.value = ui.item.value;
this.form.submit();
}
});
You can try this way. in this case, you can make your API call every time someone inserts something. This means every single letter will make a call
document.querySelector("#txt_itemname").addEventListener('input',(e)=>{
...
})
and additionally, if you do it as an API try to look at this too http_responses with PHP

Having issue while counting clicks of view number using php and 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: ");
});

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();

Save input on cache when button click

this is a part of my html:
<p>City: <input type="text" id=city value="New York"> </p>
<p>State: <input type="text" id=state value="NY"> </p>
<button id="search">Search!</button>
<button id="favorite">mark as favorite!</button>
Bellow is my .js
The search function is working like a charm, it does an ajax call with the inputs and receive weather infos.
my problem is with the favorite button, what i need is to search for example Baltimore and click on Mark as favorite. This will make Baltimore to be the one to opens when I refresh the page.
I believe that one alternative would be changing the standard input text because my ajax call is made when document its ready or when search button is clicked but i have no idea how to do it yet.
$('#search').click(function() {
ajax();
});
$('#favorite').click(function() {
var $city= $('#city')
document.getElementById('city').value= $city.val();
});
any ideas??
edit: solution:
$(document).ready(function() {
var $city= $('#city')
document.getElementById("city").value = localStorage.getItem("city");
ajax();
});
...
...
...
$('#favorite').click(function() {
var $city = $('#city')
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("city", $city.val() );
// Retrieve
document.getElementById("city").innerHTML = localStorage.getItem("city");
} else {
document.getElementById("city").innerHTML = "not possible to store";
}
ajax();

Delete Record Confirmation Message

I wonder whether someone may be able to help me please.
Firstly, my apologies because I'm really very new to this, so please forgive me what some may seem a very basic question/error.
The extract of code below, successfully creates a table of records pertinent to the current user.
Working Solution - Baylor Rae' worked tirelessly with me over the last 3-4 days to find a solution. All Baylor Rae' was unable to provide a fully successful script, they certainly helped considerably in moving this on . However the full working script below is Courtesy of jazzman1 # PHP Freaks
Main Script
<script type="text/javascript">
$(document).ready(function(){
$('form.delete').submit(function(e){
console.log('submit'); return false;
})
})
</script>
<script type="text/javascript">
$(document).ready(function(){
$('form.delete').submit(function(e){
e.preventDefault();
var elem = $(this).closest('.delete');
var lid = $(this).serialize();
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this Location. <br />It cannot be restored at a later time! Do you wish to continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
//elem.slideUp();
$.ajax({
url: 'deletelocation.php',
type: 'POST',
data: lid,
success: function(response) {
console.log('success', response);
},
error: function() {
console.log('error')
}
});
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
})
</script>
jqueryconfim.js
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
Form In Main Script
<form name="delete" id="delete" class="delete">
<input type="hidden" name="lid" id="lid" value="<?php echo $theID ?>" />
<input type="submit" value="Delete Record"/>
</form>
deletelocation.php
<?php
$lid = intval($_POST['lid']);
$query = mysql_query("DELETE FROM table WHERE locationid='".$lid."'");
?>
You'll see that the end of the table are four buttons, which, through the locationsaction.php script navigate the user to four different screens all linked back to the main table record via the lid value. This script is shown below.
I'm now trying to implement a confirmation message for the Delete function. The source code for this can be found here.
This is where I've become a little unsure about what to do next. I've tried to link the button on click event with the name of the Delete function, but rather than the confirmation message, the user is taken to a blank screen and the record is deleted.
I've run the JavaScript Console and there are no errors created, so I'm a little unsure about how to continue.
I just wondered whether someone could possibly take a look at this please and let me know where I'm going wrong.
Many thanks and kind regards
Prevent the Redirection
It looks like you're getting the redirection because the form is still submitting. You need to prevent the form from submitting by adding the following line at the beginning of your click event.
$('#btn-delete').click(function(e) {
e.preventDefault();
var elem = $(this).closest('.item');
Calling e.preventDefault() will prevent the browser's default action from occuring, in this case submitting the form.
Changing the way buttons are handled
As far as I can tell locationsaction.php redirects to a page based on the value of the button.
A better way to do this would be to create a link to each page and pass the lid as a parameter. This is the standard way of linking pages while providing some context for the next page.
Note: You will need to change each page to use $_GET['lid'] instead of $_SESSION['lid'].
Note 2: It is perfectly valid to "close" and "open" PHP tags in the middle of a page. In the code I provided below I closed PHP so I could write HTML, and reopened PHP when I was done.
<?php // this line is for syntax highlighting
/* display row for each user */
$theID = $row['locationid'];
?>
<tr>
<td style="text-align: center"><?php echo $row['locationname'] ?></td>
<td>Images</td>
<td>Add Finds</td>
<td>View Finds</td>
<td>
<form method="post" action="deletelocation.php" class="delete-record">
<input type="hidden" name="lid" value="<?php echo $theID ?>" />
<input type="submit" value="Delete Record" />
</form>
</td>
</tr>
<?php
The only time I didn't use a link was when I linked to the deletelocation.php file. This is because you should never use a GET request when modifying a database.
Using a POST request is an easy way to prevent Cross-site Request Forgery.
Rename your table column names
I noticed that your column names for locationid and locationname didn't have any type of separation. I would recommend renaming these to location_id and location_name.
This applies to your file names as well. You can include an underscore or dash to separate the words in your filename. I usually use an underscore because I think it reads better, but it's your choice.
POST directly to the delete page
Because you're using AJAX, you can specify the deletelocation.php url directly. With the changes I've suggested above, there isn't a reason to keep locationsaction.php.
$.ajax({
url: 'deletelocation.php',
type: 'post',
data: $(this).parent().serialize(),
success: function () {
img.parent().fadeOut('slow');
}
});
I also changed how the data was passed. .serialize() will automatically grab the location id from input[name=lid] and create a query string like lid=1.
Edit #1
If possible, I'd like to keep the locationsaction script. A lot of my pages further down the line rely on a SESSION id, and using a Get isn't an option without re-writing a lot of code.
The way you're using locationsaction.php and sessions isn't the way I'd do it. But it's your application structure and you can build it however you like.
Could I change the button type to button rather than submit, keeping the id the same so the JS code will pick this up?
You can change the type to button, but when javascript is disabled it won't submit the form. In general, you write your page to work without JS, and then write the JS to modify the browser's default behavior.
Could you also confirm for me whether your AJAX just replaces the top section of my code?
No, I only changed the way you set the lid. You still need to include all the JS wrapped around it, I just didn't want to paste the whole block of code.
Observation 1:
function delete(){
$(document).ready(function(){
Is that really the order of the lines in your code? The jQuery ready hook lies INSIDE of your function definition? Or have you, by mistake, posted them here in the wrong order here.
If it's the former case, then please, fix this first before anything else. Otherwise, read on:
Why $('.item .delete')? I don't see any markup with class .item? Where is it? Are you sure that this selector matches some elements in the first place? Also, you should use #delete for referencing elements through their id attributes, not .delete, as that looks for elements with the class delete.
Your id:delete button and the other buttons are submit type buttons, which means that their click handlers simply will not block the submission flow. You can change all the button types to button, instead of having them as submit. Code example below.
Why the declarative onClick on the delete button? Get rid of it.
(Also, you really don't need a form in this case, unless you want to deserialize the form, which doesn't seem like a requirement or intent given your markup).
<td><input type='button' name='type' id='details' value='Details'/></td>
<td><input type='button' name='type' id='images' value='Images'/></td>
<td><input type='button' name='type' id='addFinds' value='Add Finds'/></td>
<td><input type='button' name='type' id='viewFinds' value='View Finds'/></td>
<td><input type='button' name='type' id='delete' value='Delete' /></td>
And your JS:
//please, be careful with the selector.
//it could be that it is not matched at all,
//hence jQuery will not bind to anything
//and nothing will ever fire!
//note the #delete for Id! .delete is for a class!!!!!!
$('.item #delete').click(function () {
var elem = $(this).closest('.item');
$.confirm({
'title': 'Delete Confirmation',
'message': 'Delete?',
'buttons': {
'Yes': {
'class': 'blue',
'action': function () {
//elem.slideUp();
$.ajax({
url: 'locationsaction.php',
type: 'post',
data: {
lid: "VALUE",
type: 'Delete' //you need to add the type here!
},
success: function () {
img.parent().fadeOut('slow');
}
});
}
},
'No': {
'class': 'gray',
'action': function () {} // Nothing to do in this case. You can as well omit the action property.
}
}
});
Also, you can redudantly add a false return to your form's onsubmit event.
Actually I don't find any button of id btn-delete on your form.If your using delete button present in form then change this
<input type="submit" value="Delete Record" />
to
<input type="button" id="btn-delete" value="Delete Record" />
Or your using any other input then make sure that it type is not submit for example
<input type="submit" value="Your button" />
should be
<input type="button" value="Your button" />
u can use jquery ui dialog for confirmation :
<script type="text/javascript">
$('#btn-delete').click(function (e) {
e.preventDefault();
var elem = $(this).closest('.item'), formSerialize = $(this).parent().serialize(), objParent = $(this).parent();
$('<div></div>').appendTo('body')
.html('<div><h6>Delete?</h6></div>')
.dialog({
modal: true, title: 'Delete Confirmation', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
$.ajax({
url: 'deletelocation.php',
type: 'post',
data: formSerialize//,
//success: function (data) {
// objParent.slideUp('slow').remove();
//}
});
//Or
objParent.slideUp('slow').remove();
$(this).dialog("close");
},
No: function () {
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
});
</script>
The problem isn't anything to do with JavaScript.
The fundamental problem seems to be that your form's action is to delete the record (regardless of what you've coded in JavaScript). Change the form's action to "." and onsubmit="return false" (which stops the form from doing anything on its own). Now attaching your $.confirm to the appropriate button should work.
Stepping back from this -- you don't need a form at all (or a submit button). Then you wouldn't have to fight the default behavior of a form.
Try to use e.stopPropagation();
$('#btn-delete').click(function(e) {
e.preventDefault();
e.stopPropagation();

Categories

Resources