I have a small problem with a giftlist generated from SQL. My goal is to echo each row as a form with a textbox and a button, then when any button clicked, pass the textbox value, and an id number (hidden field value) to a function. Then this function would have get the values, and sends them with AJAX get method to a php, which would update a row with the giver's name in the SQL database. I cannot find the error in my code, so please help me in this regard.
EDIT: i need to figure out too, how to identify the button which was clicked.
This would be my script:
<script type="text/javascript">
var aname = '';
var tid = 0;
$('.giftok').click(function()
{
if ($('.aname').val() === '')
{
alert('You have not provided your name.');
}
else
{
aname = $('.aname').val();
tid = $('.id').val();
$.ajax
({
url: "kosarba.php",
data: { ganame: aname, tid: gtid },
type: "GET",
context: document.body
}).done(function() {
alert("OK, it works.");
});
alert('Thank you!');
}
});
</script>
Here is my HTML+PHP:
echo "<table id='giftlist' align='center' font-size='10pt'>";
while($sor=mysql_fetch_array($sordb))
{
echo "<tr>
<td width='420px'>$sor[gname]</td>
<td width='65px'>$sor[gprice] Ft</td>";
if (strlen($sor[aname]) !== 0)
{
echo "<td width='200px'>Sorry, someone already bought this one for us.</td>";
}
else
{
echo "<td width='335px'><form id='rendelget'>Your name: <input type='textbox' id='aname' name='aname' value='$aname'/><input type='hidden' class='id' name='id' value='$sor[id]'/> <button type='button' id='$sor[id]' class='giftok' value='Megveszem'>Megveszem</button></form> </td>";
}
echo "</tr>";
}
echo "</table>";
You have mistaken a variable name tid = $('.id').val() tid
should be gtid
I think that would be your script
$(document).ready(function(){
var aname = '';
var tid = 0;
$('.giftok').click(function()
{
if($(this).closest('form').attr('name') == 'myId'){ //or id
if ($('.aname').val() === '')
{
alert('You have not provided your name.');
}
else
{
aname = $('.aname').val();
gtid = $('.id').val();
$.ajax
({
url: "kosarba.php",
data: { ganame: aname, tid: gtid },
type: "GET",
context: document.body
})
.error(function(){
alert('Ajax worked but error form server.');
})
.done(function() {
alert("OK, it works.");
});
alert('Thank you!');
}
}
});
})
//Update: If you identify the form holding the button gitve the form a name or id
Inside the ajax call,
data: { ganame: aname, tid: gtid }
'tid' is the post parameter, while gtid is the javascript variable.
Mistakenly, you have used gtid instead of tid .
use :
data: { ganame: aname, tid: tid }
Related
I'm having a problem in datatable. Why I got a "Showing 0 to 0 of 0 entries", also can't search, it always show "no data available" and the pagination are disabled. What should I do?
Here's my code:
//Show Products Table
function show_products() {
var action = "Show Products";
$.ajax ({
type: 'POST',
url: '../admin/class.php',
data: {action: action},
success: function(data) {
//if success it will display the data
$('#show_products').html(data);
}
});
}
//class.php(data)
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'Show Products':
//call the function show_products();
show_products();
break;
}
}
//Function to fetch the all products
function show_products() {
GLOBAL $db_conn;
$search_query="SELECT p.product_id as productID, p.*, pe.* FROM tblproduct p JOIN (SELECT p.product_id, MIN(pe.product_extension_id) AS product_extension_id FROM tblproduct p LEFT JOIN tblproduct_extension pe ON pe.product_id = p.product_id GROUP BY product_id ORDER BY product_id) product_unique LEFT JOIN tblproduct_extension pe ON pe.product_extension_id = product_unique.product_extension_id WHERE p.product_id =product_unique.product_id";
$query = mysqli_query($db_conn, $search_query);
while($row = mysqli_fetch_array($query)) {
$status = ($row['product_stocks'] == 0) ? '<label class="label label-danger">Out of stocks</label>' : '<label class="label label-success">In stocks</label>';
?>
<tr>
<td><?=$row['product_name']?></td> /*fetch product_name*/
<td><?=$row['product_brand']?></td> /*fetch product_brand*/
<td><?=$row['category_name']?></td> /*fetch category_name*/
<td>₱<?=number_format($row['product_price'], 2)?></td> /*product_price*/
<td><?=$row['product_size']?></td> /*fetch product_size*/
<td><?=$row['product_stocks']?></td> /*fetch product_stocks*/
<td><?=$status?></td> /*display status if 0 stocks "outofstock"*/
</tr>
<?php
}
}
//Script of datatable
$(document).ready(function(){
//get the id of table
$('#datatable1').DataTable();
});
Screenshot:
PS: I included all the libraries.
Initialize your table only after you retrieve the data from the server.
$.ajax ({
type: 'POST',
url: '../admin/class.php',
data: {action: action},
success: function(data) {
// If table is initialized
if ($.fn.DataTable.isDataTable('#datatable1')){
// Destroy existing table
$('#datatable1').DataTable().destroy();
);
//if success it will display the data
$('#show_products').html(data);
// Initialize the table
$('#datatable1').DataTable();
}
});
If you will be making Ajax request multiple times.
$.ajax ({
type: 'POST',
url: '../admin/class.php',
data: {action: action},
success: function(data) {
// If table is initialized
if ($.fn.DataTable.isDataTable('#datatable1')){
// Destroy existing table
$('#datatable1').DataTable().destroy();
};
//if success it will display the data
$('#show_products').html(data);
// Initialize the table
$('#datatable1').DataTable();
}
});
Added some additional formatting
I am trying to send the parameter in a function but its in a loop so when i select the same function next time it first send me the previous value then send me the value that i want which causes the function to be empty and not take any value let me show you my code.
$(window).load(function(e) {
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore() {
var lastID = $('.load-more').attr('lastID');
// alert(lastID);
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("user/get_all_post"); ?>',
data: {
id: lastID
},
dataType: 'json',
beforeSend: function(data) {
$('.load-more').show();
},
success: function(data) {
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json == "") {
$("#bottom").append('<div class="btn btn-default col-md-6" >' + 'No More Results' + '</div>');
$("#Load_more_data").hide();
} else {
$postID = json[json.length - 1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function(key, data) {
var post_id = data.id;
var post_status = data.status;
var status_image = data.status_image;
var multimage = data.multimage;
if (!post_status == "" && !status_image == "") {
alert(post_id);
$("#status_data").append('<div class="media-body"><div class="input-group"><form action="" id="form_content_multimage"><textarea name="textdata" id="content_comment_multimage" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_multimage" onclick="comment_here_multimage(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
}
});
}
}
});
}
function comment_here_multimage(post_id) {
$(document).on('click', '#comment_button_multimage', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
});
}
The post_id is being passed onclick event of the comment_here_multimage but whenver i click on it after first time same id is being passed again first then the next id passes. what can i fo to empty the post_id value once it completes.
look at these images and tell me if there is something you dont understand.
[![first time comment][1]][1]
[![second time comment][2]][2]
[![second time comment][3]][3]
[1]: https://i.stack.imgur.com/b36o4.png
[2]: https://i.stack.imgur.com/ahg3W.png
[3]: https://i.stack.imgur.com/taHAS.png
Your problem is not isolated in code. However according to my understanding.
You are binding "comment_here_multimage" function on click event of button when creating dynamic html.
Once context is loaded and user clicks that button you again binds another function on same button, which is ultimately added to the event stack.
If user clicks the button first time nothing will happen, there is no action on it. On first time it will register a handler with it.
If user click second time it will fire the handler attached on first click resulting in old postid supplied to it.
I think your problem is with passing parameter. You can set it in a custom parameter and get it later in click handler. Or you can change your handler like below.
You can change your code like this
onclick="comment_here_multimage(this,' + post_id + ');"
function comment_here_multimage(e,post_id) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
;
}
For a link like this
DELETE
i am using this ajax call
$(function() {
$(".delete_msgs").click(function() {
var msgid = $(this).attr("id");
var dataString4 = 'msgid=' + msgid;
$('a#'+msgid).html('<img src="img/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "del_msg.php",
data: dataString4,
cache: false,
success: function(data){
if (data == 0) {
//alert('Sent!');
} else {
$('a#'+msgid).html(data);
$('.viewmessage'+msgid).hide();
}
}
});
return false;
});
});
The del_msg.php file contains that code:
if(isset($_POST)) {
$msgid = $_POST['msgid'];
$delmsg = mysql_query("DELETE FROM messages
WHERE id = $msgid") or die(mysql_error());
echo 'Message sent!';
} else {
echo 0;
}
My big question is, how can i protect my send throught AJAX function? Anyone can change the id of the #a element and, consequently, can delete any row from my database.
Is there a more secure way to call php with ajax, or at least, to hide my important variables sent via ajax?
I am trying to submit a form. In the form, I have a field calles sitename. If the user enters a sitename which is already in the database, it will show the message "That name is already in use" and give some suggestions. Up to this point, it works. But what I want, is to hide the submit button until the user enters a valid value to that field.
Here is my code:
form.php:
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
check_name.php:
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
/*echo "<span style='color:white;'>Available</span>";*/
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
}
Try this code,
<script type="text/javascript">
$(document).ready(function(){
$("#sitename").keyup(function() {
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html != 'success')
{
$("#disp").html(html);
$("#btn-signup").hide();
}
else
{
$("#btn-signup").show();
}
},
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none;">Submit</button>
</div>
And in your check_name.php
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo "success";
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>";
}
die;
}
?>
You will need to keep track on the outcome of your PHP script.
Change your code to:
PHP
<?php
include('dbconnect.php');
if(isset($_POST['sitename']))
{
$sitename=mysql_real_escape_string($_POST['sitename']);
$query=mysql_query("select * from template_users where sitename='$sitename'");
$row=mysql_num_rows($query);
if($row==0)
{
echo json_encode([ "status" => 1, "html" => "<span style='color:white;'>Available</span>" ]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode([ "status" => 0, "html" => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>" ]);
}
}
?>
HTML
<script type="text/javascript">
$(document).ready(function () {
$("#btn-signup").hide();
$("#sitename").keyup(function () {
$("#btn-signup").hide();
var sitename = $('#sitename').val();
if (sitename == "")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename=" + sitename,
dataType: "json",
success: function (result) {
if (result.status == 1) {
$("#btn-signup").show();
}
$("#disp").html(result.html);
}
});
return false;
}
});
});
</script>
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup">Submit</button>
</div>
That is, hide the button on start, if a user enters something, hide the button and wait till the text is validated. If it is valid, show it. If the user changes the text, then the button will be hidden again.
Please note:
1) mysql_* functions are deprecated since version 5.5 and have been removed in version 7. This on its own is enough indication that you need to move on and use something more secure and actively supported.
2) mysql_real_escape_string and mysqli_real_escape_string are not safe since they don't reliably consider server encoding. If you want to be safe, use real prepared statements (i.e. prepared statements which are prepared on the MySQL server).
I would suggest you to use json to return the data like this:
{
"status": "success",
"html" : "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"
}
and here's the javascript code:
$(document).ready(function()
{
/** Hide the button first */
$('button').hide();
$('#sitename').on('input', function()
{
var sitename = $('#sitename').val();
if(sitename == '')
{
$("#disp").html("");
}
else
{
$.ajax(
{
type : "POST",
dataType: "json"
url : "check_name.php",
data : "sitename=" + sitename ,
success : function(data)
{
/** When the data is invalid */
if(data.status === 'error')
{
$('button').hide();
$("#disp").html(data.html);
}
else
{
$('button').show();
/** Hide the html when the data is valid */
$("#disp").html('');
}
},
});
}
})
});
And your php code:
<?php
include('dbconnect.php');
header('Content-Type: application/json; charset=utf-8');
if(isset($_POST['sitename']))
{
$sitename = mysql_real_escape_string($_POST['sitename']);
$query = mysql_query("select * from template_users where sitename='$sitename'");
$row = mysql_num_rows($query);
if($row == 0)
{
echo json_encode(['status' => 'success',
'html' => "<span style='color:white;'>Available</span>"]);
}
else
{
$msg = $sitename.rand ( 1 , 10000 );
$msg1 = $sitename.rand ( 1 , 100 );
echo json_encode(['status' => 'error',
'html' => "<span style='color:antiquewhite;' ><b>Already exist please Use different Site Name such as<br/> $msg<br/>$msg1<br/><b/></span>"]);
}
}
?>
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
if(html !== "") {
$("#btn-signu").attr("disabled", true);
}
else {
$("#btn-signu").removeAttr("disabled");
}
$("#disp").html(html);
}
});
Check the html param in success callback function.
In form.php change Javascript to:
<script type="text/javascript">
$(document).ready(function(){
//get the button by its ID
var $button = $('#btn-signup');
$("#sitename").keyup(function() {
//hide the button always
$button.hide();
var sitename = $('#sitename').val();
if(sitename=="")
{
$("#disp").html("");
}
else
{
$.ajax({
type: "POST",
url: "check_name.php",
data: "sitename="+ sitename ,
success: function(html){
$("#disp").html(html);
if(!html.length){
//show the submit button if no error html
$button.show();
}
}
});
return false;
}
});
});
</script>
The Button should be initial hidden. If the field can be prefilled, you need to check if the value is not empty before hiding the button.
<div class="form-group col-sm-3 col-xs-12">
<button class="btn btn-1 btn-fill" type="submit" id="btn-signup" name="btn-signup" style="display:none">Submit</button>
</div>
I am storing my checkbox selections in an array then splitting each array and posting them using AJAX so my PHP function can use the posted id/ids to query my MySQL database.
First part of my JavaScript
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
alert(tbl);
This first part works as intended, where every time I click a checkbox the value is alerted.
AJAX post
$.ajax({
type: "POST",
url: "index.php",
data: "tbl=" + tbl
});
});
Finally my PHP
function describeTables() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}}
I don't get any vlaues of tbl even if I choose just one option. Why is this????
EDIT
My Checkbox
function showTables() {
if (isset ( $_GET ['db'] )) {
$db = $_GET ['db'];
$link = mysqli_connect ( 'localhost', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
echo '<ul>';
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
echo '<input type="checkbox" name="tbl[]" class="tbl_list" value="' . $row [0] . '" class="tablebox" />';
echo $row [0];
echo '<br>';
}
}
}
showTables ();
SECOND EDIT
After suggestions I have amended my code but now have a new problem where the page doesn't load #dbdisplay Below is my full JS code
if (!location.search.match(/db=[^&#]+/i)) {
$("#dbdisplay").show();
} else {
$("#qryDisplay").show();
}
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
window.sessionStorage.setItem("db", db);
window.location.assign("index.php?db=" + db);
$("#dbdisplay").hide();
});
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
//alert(tbl);
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl': tbl }
});
});
The old function
/*
$(document).on("change", ".tablebox", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var yourDB = window.sessionStorage.getItem("db");
window.location.assign("index.php?db=" + yourDB + '&tbl=' + tbl);
});
*/
How do I fix this??
In ajax call, data has to be object data: {'tbl': tbl}
This should to the job
$.ajax({
type: "POST",
url: "someurl",
data: {"tbl=" + tbl}
});
http://api.jquery.com/jquery.getjson/
See here for documentation
First thing in your ajax call, data has to be object
data: {'tbl': tbl}
Secondly Ajax can't call php function directly
so your index.php file should be something like this without function
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}
You should use "{ }" with data
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl' : tbl}
});
or
$.ajax({
type: "POST",
url: "index.php&tbl="+tbl
});