hello i want to set a $_POST value in php when someone click a div element , here's part of my code :
<?php
$looperone = 1;
$judulcountquery = "SELECT nomorsoal FROM soal";
$judulcountrun = mysqli_query($konek,$judulcountquery);
if ( $judulcountrun == FALSE ) {
die(mysqli_error());
} else {
}
$judulcount = mysqli_num_rows($judulcountrun);
$amountofrows = $judulcount;
while($looperone == 1) {
$judulherequery = "SELECT * FROM soal WHERE nomorsoal = $amountofrows";
$judulsatuqueryconnect = mysqli_query($konek,$judulherequery);
$judulsatufetch = mysqli_fetch_assoc($judulsatuqueryconnect);
if($judulsatufetch != NULL) {
$judulsatu = $judulsatufetch['judul'];
} else {
break;
}
$judulnya = $judulsatufetch['judul'];
echo "<div class=\"head-main-recenttest-result\" style=\"text- decoration:none;\">". "".$amountofrows.".".$judulnya." </div>";
$looperone++;
$amountofrows--;
}
?>
example of output from echo :
<div class="head-main-recenttest-result" style="text-decoration:none;">
Latihan 1
</div>
as you see that only will redirect people to the link without giving post data , anyone know the method ? also im new so i can't ask well
By the looks of your code, you are not sending any post variable to the bacasoal.php. If you just want to submit then this will suffice.
<form method="post" action="bacasoal.php">
<div class="head-main-recenttest-result" style="text-decoration:none;">
<input type="submit" name="button" value="Latihan 1">
</div>
</form>
Note: Your <a> tag was replaced by a an submit input
And if you want to do it via AJAX when click on the <a> then
HTML
<div class="head-main-recenttest-result" style="text-decoration:none;">
Latihan 1
</div>
AJAX
$('a').click(function(){
$.ajax({
url: "bacasoal.php",
type: "post",
success:(unction(){
alert("success");
},
error:function(){
alert("error");
}
})
});
In the first approach the page will be redirected to bacasoal.php.
In second one the page will stay(unless you make it to).
Related
I have a small box that is part of a PHP-site that lists all members who attended a certain event. In the box there is also a checkbox that communicates with a database to store values of who attended. I want the box to update dynamically when someone checks the checkbox. The code I have is working good, and whenever the DIV is refreshed I get an updated list of members and correct count, but loose both the checkbox value and the label!
I am sure there is a simple solution I've missed, but after trying for hours I need someone to point me in the right direction. Whenever I press F5 to refresh, the label and correct checkbox value reappears.
Javascript:
function check_my_attendance() {
var user_attending = Number(<?php echo in_array($_SESSION['username'],$attending_users) ?>);
if (user_attending > 0) { $("label[for='attending_checkbox']").text("You attended!"); }
else { $("label[for='attending_checkbox']").text("You did not attend."); }
$('#attending_checkbox').prop('checked',user_attending);
}
function set_attendance(cb) {
if($(cb).is(":checked")) {
$("label[for='attending_checkbox']").html('Setting..');
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=1",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance();
}
}); }
else {
$("label[for='attending_checkbox']").html('Removing..');
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=0",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance();
}
}); }
}
$(document).ready(function(){
check_my_attendance();
});
</script>
PHP/Html:
<div id="containerAttend">
<?php $query_attendance="SELECT link_attending.attended_memberid,link_attending.attended_gigid,members.username FROM link_attending
LEFT JOIN members ON (members.id = link_attending.attended_memberid) WHERE attended_gigid=".$ut;
$result_attendance = mysqli_query($mysqli,$query_attendance);
$attending_users = array();
for( $i = 0; $i < mysqli_num_rows ($result_attendance); $i++)
{mysqli_data_seek($result_attendance,$i); $usr=mysqli_fetch_array($result_attendance); $attending_users[] = $usr["username"];}
$chkattendance = array_filter($attending_users);
if (empty($chkattendance)) {$attendance_int = 0;} else {$attendance_int = count($attending_users);}
?>
<div id="list_attended">
<div class="col-md-3 col-md-offset-5">
<div class="panel panel-default">
<div class="panel-heading">
<b><?php echo $attendance_int; ?> users attended:</b>
</div>
<div class="panel-body">
<?php
if ($attendance_int > 0) {foreach($attending_users as $usr_att) {echo "<a href='profile.php?user=$usr_att'>$usr_att</a>"." - ";} echo "<br>";}
if (login_check($mysqli) == true)
{echo "<form><input id='attending_checkbox' type='checkbox' onclick='set_attendance(this)' />
<label for='attending_checkbox'></label></form>";}
else
{echo "<br>Log in to set attendance!";}
?>
</div></div></div></div>
Thanks for any help!
Based on the comments, this is where I believe you can make changes and everything might just work fine for you
function check_my_attendance(result) {
var user_attending = Number(<?php echo in_array($_SESSION['username'],$attending_users) ?>);
if(typeof result != 'undefined') {
user_attending = result;
}
if (user_attending > 0) {
$("body label[for='attending_checkbox']").text("You attended!");
} else {
$("body label[for='attending_checkbox']").text("You did not attend.");
}
$('body #attending_checkbox').prop('checked',true);
}
In function set_attendance(), you can pass the result value to your check_my_attendance() function like this:
$.ajax({
type: "POST",
url: "setattendance.php",
data: "gig="+<?php echo $ut ?>+"&action=1",
cache: false,
success: function(result){
$("#containerAttend").load(document.URL + " #containerAttend");
check_my_attendance(result);
}
});
You can do console.log(result) and check what you are getting as result in in the after the AJAX Callback. If it is an empty string, you can add this line at the end of setattendance.php - echo 1; or echo 0;
I also created this fiddle as a small example for setting this checked property and label text. Even though I am not using any AJAX in it, I just wanted to let you know why we are using the body tag before #attending_checkbox in $('#attending_checkbox'). The basic reason behind showing it to you is that whenever a new DOM element is loaded or an old DOM element is replaced the old javascript doesn't work. So, you need to set the parent name and then the DOM id first, so that the JavaScript is able to locate the new element. - https://jsfiddle.net/prateekkathal/3kbtp2am/
Thanks,
I have a textarea in which user enter url and link is extracted successfully and appended to a div. How can I store that extracted data into database as the extracted data is in a div not in any input?
<textarea id="get_url" placeholder="Enter Your URL here" class="get_url_input" spellcheck="false" ></textarea>
<input type="button" value="Share">
<div id="results">
</div>
Extracted data is shown in result div, do I need to store the response into any hidden input and check if it is empty while clicking on share button?
There are several ways to do this but I would recommend using:
Ajax and JQuery
In your JavaScript file add:
var data = $('#div id').text();
$.ajax ({
url: "www.websitename.com/addurl.php",
type: 'POST',
data: { urltoadd: data},
success: function (response){
If (response = 'successful'){
return true;
}else {
return false;
}
}
});
Now in your addurl.php file:
<?php
$urltoadd = $_POST ['urltoadd'];
... add Code to save $urltoadd in your database.
If (file was added successfully){
echo 'successful';
}else {
echo 'failed';
}
? >
On form submit you can bind a function and in that functiom
using jquery you can do $('#result').text()
Please, can somebody publish a mistakes corrected and tested code for my problem?
Program does - 22.php has the form. When the user enter and click Submit button, the result should be taken from 23.php and displayed in div on 22.php
I already tried solutions below and none of them solve my problem;
1) I changed to: $("#testform").submit(function(event){
2) I included "return false;" at the end to prevent it to actually submit the form and reload the page.
3) clear my browser cache
I can see what happen the program with my computer;
1) I do not get error message after I click submit.
2) I can see the tab of the page reloads quickly and the entered text fields are cleared.
3) No error message or result shows.
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').val(data);
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
you don't need to change your php code
try submit form with submit event ...
$("#testform").submit(function(event){
use `dataType:json`; in your ajax ..
yourData =$(this).serialize();
Your php
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
$data['name']= 'welcome '.$name;
$data ['age']= 'you are '.$age;
print_r(json_encode($data));exit;
}
?>
Now In Your Success function
var message = data.name + ' ' + data.age;
$('#result').html(message );
You are sending myname and checking name(isset($_POST['name']) in php.
don't use .value() use .html() for data rendering. and console log the data and see whats request and response using firebug.
Can you try this one?
To be changed
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
and
$('#result').html(data); // here html()
the code becomes
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
alert('Submitted');
}else{
return false;
}
}
});
});
});
Try formatting your post data like this inside your ajax function.
$.ajax({
type:'POST',
data : {
myname: myname
myage: myage
}
...
}
EDIT
Try removing the ; in
return false;
}
};
to
return false;
}
}
You can change at both end ajax and php:
#PHP:
You can check for correct posted data which is myname and myage not name and age.
<?php
if ( isset($_POST['myname'])) { // was the form submitted?
echo "Welcome ". $_POST["myname"] . "<br>";
echo "You are ". $_POST["myage"] . "years old<br>";
}
?>
or #Ajax:
yourData ='name='+myname+'&age='+myage;
//--------^^^^^^----------^^^^----change these to work without changing php
Just noticed the #result is an div element. So, you can't use .val() but use .html(), .append() etc:
$('#result').html(data);
What I am trying to do is create a "save" button for my website which saves specific posts and comments, exactly like the "save" button on Reddit. For now I am trying to self teach jQuery AJAX and attempting to figure out how to submit data to the database without having to reload the whole page. What I am attempting to do here is save a string by submitting it to a table called "Saved" when I click on "save".
HTML
<div id="message1">
<div id="pmessage"><p><?php echo $myComment;?></p></div>
Save
Edit
Hide
</div>
<form action="ajaxexample.php" method="post" style="display: none" id="1234">
<input type="hidden" name="message" id="message" value="<?php echo $myComment; ?>">
</form>
jQuery
$('a.Save').click(function () {
if ($(this).text() == "Save") {
$("#1234").ajax({ url: 'ajaxexample.php', type: 'post', data: 'message' });
$("a.Save").text("Unsave");
} else {
$("a.Save").text("Save");
}
});
PHP5.3
$message = $_POST['message'];
$query = "INSERT INTO saved (comment) VALUES (?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $message);
$statement->execute();
$statement->store_result();
$submissionWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($submissionWasSuccessful)
{
header ("Location: index.php");
}
$myComment = "This is my message!";
As of now all I am trying to do is submit the message "This is my message!" into the database table "Saved". What is wrong with my code? Why can I not submit the data to the table and how can I fix it? Thanks in advance!
Submit form when someone clicks on a.Save
$('a.Save').click(function (e) {
e.preventDefault();
$("#1234").submit();
});
submit handler on form#1234
$("#1234").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'ajaxexample.php',
data: $("#1234").serialize(),
success: function(data)
{
// data stores the response from ajaxexample.php
// Change the html of save by using $("a.Save").html("Unsave");
}
});
});
Serialize automatically makes a query string.
$(".save").bind("click",function(e){e.preventDefault();
$.ajax({
url : $("#1234").attr("action"),
type : "POST",
data : $("#1234").serialize(),
success : function(data){},
fail : function(data){},
});
});
I am using smarty framework in my project, I perfectly did my comment system but I cannot get the exactly result I want.
This is my PHP code inside event-detail.php :
$event_comment = $eventComment->geteventcomment($record, $startfrom, $max);
$tpl->assign("event_comment", $event_comment);
$tpl->display("event-detail.html");
This is HTML code inside event-detail.php :
//this is javasctipt
<script type="text/javascript">
// on post comment click
$('.bt-add-com').click(function(){
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&event_id='+theEventId.val()+'&comment='+theCom.val()+'&user_id='+theUserId.val()+'&user_name='+theUserName.val()+'&file_path='+theFilePath.val(),
success: function(html){
theCom.val('');
theEventId.val('');
theUserId.val('');
theUserName.val('');
theFilePath.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
});
});
</script>
<div class="content-container-left">
<{section name=thisrsa loop=$event_comment}>
<div class="comment-box">
<div class="comment-listing">
<div><small><{$event_comment[thisrsa].date}></small></div>
<div class="avatar">
<img src="<{$smarty.const._CONST_CONTENT_MEMBER_THUMBNAIL}><{$event_comment[thisrsa].file_path}>"/>
<p><{$event_comment[thisrsa].name}></p>
</div>
<div class="comment-template">
<p><{$event_comment[thisrsa].content}></p>
</div>
</div>
</div>
<{/section}>
</div>
This is SQL statement which I had did it limit 3 record shows each page :
function geteventcomment($record, $startfrom, $max){
global $db,$comment;
$arrResult = array();
$stmt = "SELECT tbl1.event_id, tbl2.name, tbl2.file_path, tbl1.text, tbl1.modified_timestamp, tbl1.creation_timestamp FROM "._CONST_TBL_EVENT_COMMENT." tbl1, "._CONST_TBL_ALUMNI." tbl2 WHERE tbl1.event_id = $record AND tbl1.member_id = tbl2.id ORDER BY tbl1.creation_timestamp DESC";
$stmt .= " LIMIT $startfrom, $max";
if($rs = $db->Execute($stmt))
{
while($rsa = $rs->FetchRow())
{
array_push($arrResult, array(
"id" => $record,
"name" => $rsa['name'],
"file_path" => $rsa['file_path'],
"content" => $rsa['text'],
"date" => $rsa['modified_timestamp']
));
}
}
return $arrResult;
}
I had get the following result in my website :
But what I really want is to refresh div and make it only display the latest 3 comment in my website, like below :
I hope I can get some help from you guys.
Please check if following code helps.
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').empty().append(html);
});