I was trying to pass the variable thecode, which is in the table using jquery into the function named getComments(). My code has as following. First I have my jquery script which is this:
$(document).ready(function(){
$("#comment_process").click(function(){
if($("#comment_text").val() != ""){
$('.post_loader').show();
$.post("comments_business.php?action=post", {
comment: $("#comment_text").val()
}, function(data) {
$(".comments").hide().html(data).fadeIn('slow');
$("#comment_text").val("");
$('.post_loader').hide();
});
}
});
});
Next I have the following script with html and php:
<!--- more code at the top---->
<?php $auto = $profile_data_business['business_code']; ?>
<table>
<textarea rows="3" id="comment_text" placeholder="share an update."></textarea>
<input type="" id="comment_code" name="thecode" value="<?php echo $auto; ?>" />
<input type="button" id="comment_process" />
</table>
<div class="comments"><?php include_once("comments_business.php");?> </div>
the page named comments_business.php includes a function which is the following:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
// can't get variable $thisemail
$thisemail = mysql_real_escape_string($_POST['thecode']);
$sql = mysql_query("SELECT * FROM comments_business WHERE ( `flag`=0 and `user`='$thisemail' and `comments_id` NOT IN (SELECT `comments_id` FROM `hide_comment_business` where `user`='$session_user_id') ) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
//more code here
return $comments;
}
?>
Any idea how should I change my jquery code so that I will be able to pass $thisemail variable successfully into getComments() function?
When you use $.post don't need to write GET parameter in URL (action=post).
When you post data by comment name, you must get data by some name
in php ($_POST['comment']).
When you use ajax shouldn't use function in php or call function
after defintion.
When you use ajax must print or echo data in php file to display in
post result.
Related
I have a really simple web app which allows a user to enter a first and last name and hit submit to insert the name into a sql database.
Below the form, there is a HTML table displaying the contents of the database table.
If a user clicks on any row of the database, the ID of the HTML element (which is set to the same value of the database ID) is saved to a javascript variable using the following function.
<!--JS Functions-->
<script>
//Determine which record is selected.
var id;
function TableSelect(el) {
id = el.id;
alert(id);
}
</script>
Here is the form:
<!--HTML Form -->
<form method="post" action="index.php">
First Name: <input type="text" name="FirstName" value="">
<br><br>
Last Name: <input type="text" name="LastName" value="<?php echo $LastName;?>">
<br><br>
<input type="submit" name="submit" value="Submit">
<input type="submit" name="delete" value="Delete" onclick="Delete()">
</form>
Here is the PHP processing of the data and the output of the SQL table:
//prepare query to insert data from form into DB
if (isset($_POST['submit'])){
$query = "INSERT INTO tbl_HR_Master (First_Name, Last_Name) VALUES ('{$FirstName}', '{$LastName}') ";
$result = mysqli_query($connection, $query);
//Test if there was a query error
querycheck($result);
}//end if
//prepare query to populate table from DB
$query2 = "Select id, First_Name as 'First Name', Last_Name as 'Last Name' from tbl_HR_Master";
$result2 = mysqli_query($connection, $query2);
//Test if there was a query error
querycheck($result2);
//display table
echo "</br>";
echo "<table id=\"tbl_HR_Master\" border='1'><tr class=\"nohover\"\">";
// printing table headers
$fields_num = mysqli_num_fields($result2);
for($i=0; $i<$fields_num; $i++) {
$field = mysqli_fetch_field($result2);
echo "<td>{$field->name}</td>";
} //end for
echo "</tr>\n";
// print table rows
while($row = mysqli_fetch_row($result2))
{
echo "<tr>";
$id = $row[0];
foreach($row as $cell){
echo "<td onclick=TableSelect(this) id=". $id .">".$cell."</td>";
}//end foreach
echo "</tr>\n";
}//end while
I want to run a PHP function which deletes the selected record from the database however, obviously PHP runs on the server, therefore, I need some way to tell PHP which record is selected. Once again, if you look at my Javascript function, var id = the last selected record. How can I parse this JS variable to the server for processing?
In a nutshell, want to do this in PHP:
//delete selected record
if (isset($_POST['delete'])){
$query3 = "Delete from tbl_HR_Master where id = ". JS VARIABLE HERE." ";
} //end if
Form-based
You could do this with an hidden form field which you give a specific id:
<input type="hidden" id="your-id" value="" />
and then in your TableSelect function you assign the value:
document.getElementById('your-id').value = id;
Then you can access the variable like the other request (post / get) parameters, in your case:
$_POST['id']
Ajax-based
With jQuery you could perform an ajax request like this in your TableSelect function:
$.ajax({
url: 'file.php',
type: 'post',
data: {'id': el.id},
success: function(data, status) {
// ...
}
});
Request parameter access is the same:
$_POST['id']
You can have a hidden variable inside your form and use javascript to set the value of that hidden variable onclick.
<!--JS Functions-->
<script>
//Determine which record is selected.
var id;
function TableSelect(el) {
document.getElementById('selectedRow').value = el.id;
}
</script>
And add the following within your form tag
<input type="hidden" name="selectedRow" id="selectedRow">
Then you can update your query to be something like
$query3 = "Delete from tbl_HR_Master where id = $_POST['selectedRow']";
Of course don't forget to add sanitization and validation and all that jazz.
I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();
I have this code to insert some data that comes from a while, in a db. I'm trying to use jQuery serializearray and jQuery post together. But it seems I do some errors
$query= "SELECT * FROM barcode_prodotti";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo'
<input type="text" name="prodotto[]" class="prodotto" value="'.$row["prodotto"].'"></div>
<input type="text" name="prezzo[]" class="price" value="'.$row["prezzo"].'">
<input type="text" name="quantita[]" class="price" value="'.$row["quantita"].'">';
}
?>
<script src="js/mine.js"></script>
<button>Serialize form values</button>
</form>
<div id="results"></div>
This is my jQuery code I put in mine.js
$(document).ready(function(){
$('form').submit(function(msg) {
var mia =$(this).serialize();
$('#results').text(mia)
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("testtest.php",$(this).serializeArray(),function(data){
alert(data);
});
return false; });
});
This is my php file (testtest.php)
mysql_connect("localhost","root","");
mysql_select_db("db");
$arr = $_POST;
$sql="INSERT INTO table VALUES(
'".$arr['prodotto']."',
'".$arr['quantita']."',
'".$arr['prezzo']."'
)";
$rssql = mysql_query($sql);
?>
So I the serialize is ok (i tried to assign in a div a value to see if it was ok), but I can't insert values in my db
Your INSERT query ends up looking like this after variable substitution.
INSERT INTO table VALUES( 'product', '123', '321')
If your table has exactly three columns this will work fine. Otherwise it will fail. You may wish to use this query instead.
INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')
which enumerates the columns where you want your data.
After doing an insert (and after any query) you should check for errors. This can be done with code like this.
$res = mysql_query($q);
if ($res === false) {
echo $mysql_error ();
}
Note well: The mysql_xxx() interface is being removed from PHP for a good reason: it is vulnerable to cybercriminals. Please adopt mysqli_xxx() or PDO as soon as possible.
The simplest way to do this:
<form id="myform" method="post">
<input type="text" name="prodotto" id="prodotto">
<input type="text" name="prezzo" id="prezzo">
<input type="text" name="quantita" id="quantita">
</form>
Jquery is pretty simple too:
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'url/to/yourfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res); //the ajax response. you can alert it or whatever...
});
You can parse the fields in the ajax file like that:
yourfile.php
<?php
$product = mysql_real_escape_string($_POST["prodotto"]);
$prezzo = mysql_real_escape_string($_POST["prezzo"]);
$quantity = mysql_real_escape_string($_POST["quantita"]);
//here you have the variables ready to add them as values to database
$ins = "INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')";
mysql_query($ins);
?>
I wrote a php function which does the job perfectly if it is called standalone by PHP page. but I want to integrate this function in a program and want to call it when a button is clicked.
My PHP function is
function adddata($mobile){
// outside of this function, another database is already selected to perform different
//tasks with program's original database, These constants are defined only within this
//this function to communicate another database present at the same host
define ("HOSTNAME","localhost");
define ("USERNAME","root");
define ("PWD","");
define ("DBNAME","budgetbot");
// link to mysql server
if (!mysql_connect(HOSTNAME,USERNAME,PWD)) {
die ("Cannot connect to mysql server" . mysql_error() );
}
// selecting the database
if (!mysql_select_db(DBNAME)) {
die ("Cannot select database" . mysql_error() );
}
//inserting phone number into database
$query = "INSERT INTO `verify_bot` (phone_number) values('".$mobile."')";
if(!mysql_query($query)){
die( mysql_error() );
}
// wait for 2 seconds after adding the data into the database
sleep(2);
$query = "SELECT * FROM `verify_bot` WHERE phone_number = ".$mobile;
$result = mysql_query($query) or die( mysql_error() );
// if more than one records found for the same phone number
if(mysql_num_rows($result) > 1){
while($row = mysql_fetch_assoc($result)){
$data[] = $row['response'];
}
// return an array of names for the same phone numbers
return $data;
}else{
// if only one record found
$row = mysql_fetch_assoc($result);
$response = $row['response'];
return $response;
}
// end of function
}
HTML Code is written as
<form action="self_page_address_here" method="post" accept-charset="utf-8" class="line_item_form" autocomplete="off">
<input type="text" name="mobile_number" value="" placeholder="(000) 000-0000" class="serial_item" size="20" id="serialnumber_1" maxlength="10" />
<button id="verify" class="btn btn-primary">Verify</button>
<button id="cname" class="btn btn-primary"><!-- I want to print return value of the php function here --></button>
</form>
I want to call this function and assign the return value to a javascript variable by ajax/jquery.
My code to do this is...
<script type="text/javascript" language="javascript">
$('#verify').click(function(){
var value = $( ".serial_item" ).val();
//I have some knowledge about php but I am beginner at ajax/jquery so don't know what is happening below. but I got this code by different search but doesn't work
$.ajax({
url : "add_data.php&f="+value,
type : "GET"
success: function(data){
document.getElementById("cname").innerHTML = data;
}
});
});
</script>
I would like to share that the above javascript code is placed outside of documnet.ready(){}
scope
Any help would be much appreciated.
Thanks
Because your <button> elements have no type="button" attribute, they're supposed to submit the form using normal POST request.
You should either use type="button" attribute on your buttons, or prevent default form submission using event.preventDefault():
$('#verify').click(function(event){
event.preventDefault();
var value = $( ".serial_item" ).val();
$.ajax({
// there's a typo, should use '?' instead of '&':
url : "add_data.php?f="+value,
type : "GET",
success: function(data){
$("#cname").html(data);
}
});
});
[EDIT] Then in add_data.php (if you call AJAX to the same page, place this code at the top, so that no HTML is rendered before this):
if(isset($_GET['f'])){
// call your function:
$result = adddata(trim($_GET['f']));
// if returned value is an array, implode it:
echo is_array($result) ? implode(', ', $result) : $result;
// if this is on the same page use exit instead of echo:
// exit(is_array($result) ? implode(', ', $result) : $result);
}
Make sure you escape the value on $query.
I have a database and I get info from it and put it into php page. BUT the thing is, I cant put data from that php file to database. I use form to put there the value of variable, but it says [html span element]. and I get errors:
Notice: Undefined index: souls in xxx/the_cave.php on line 20
Notice: Undefined index: bones in xxx/the_cave.php on line 21
Here is the code:
JS:
document.getElementById("souls_form").value=<?php echo $souls_value; ?>;
document.getElementById("bones_form").value=<?php echo $bones_value; ?>;
function upload(){
<?php upload(); ?>}
PHP part:
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
function upload(){
mysqli_query($db,"UPDATE Data SET Souls=$current_souls, Bones=$current_bones WHERE Username='$username'");
HTML form
<form style="visibility:hidden" action="" method="post">
<input name="souls" id="souls_form">
<input name="bones" id="bones_form">
</form>
UPDATED CODE
<script>
var souls1=<?php echo $souls_value;?>
var bones1=<?php echo $bones_value;?>
//do your process
//after the values changes for variables souls1,bones1
//YOU HAVE TO CALL AJAX CALL TO SAVE YOUR UPDATED VARIABLES DATA INTO DB
$.ajax({
url:'updatedata.php',
type:"POST",
data:{souls:souls1,bones:bones1},
success:function(result)
{
if(result)
{
alert('updated succesfully');
}
}
});
updatedata.php
<?php
if(isset($_POST['souls'])&&isset($_POST['bones']))
{
$current_souls=$_POST['souls'];
$current_bones=$_POST['bones'];
if(mysqli_query($db,"UPDATE Data SET Souls='$current_souls', Bones='$current_bones' WHERE Username='$username'"))
{
echo 'TRUE';
}
}
?>
As the Php code executes first than all other codes, the $current_souls=$_POST['souls']; is executing first so you have to check form submission using isset() other wise no error will be printed