Insert text before submitting HTML button - javascript

I have a button that calls an ajax once you submit but I need to add another input where you have to enter text and if that text is the same as the text found in the DB this button should execute the AJAX. How can this be done?
This is my AJAX code:
<script>
jQuery(function(){
jQuery(".canjear").click(function(e){
if(this.tagName==="A"){
e.preventDefault();
}
jQuery.ajax({
url: "index.php?option=com_cuphoneo&task=miscuponess.canjearCupon",
type: "POST",
data: {id:jQuery(this).data("id")},
success: window.location.href = "index.php?option=com_cuphoneo&view=miscuponess&layout=default"
});
});
});
</script>
This is my PHP/HTML button:
<div class="panel-boton-canjear">
<?php
foreach($campos_extra as $value){
if($value->id == 17){
if(!empty($value->value)){
?>
<input class="canjear btn" type="button" value="<?php echo JText::_('COM_CUPHONEO_BOTON_CANJEAR'); ?>" data-id="<?php echo $valor->item_id; ?>" />
<?php
}
}
}
?>
</div>

Related

HTML element passing first value in PHP array to Ajax

I have an HTML that gets its values from an array list. I'm submitting the form with Ajax and with a PHP script. The issue I'm facing is when clicking on the other array it only submits the first value array. Below is what my form looks like with the PHP loop of array listing:
index.php
$query_product = "SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare($query_product);
if($product_stmt->execute()){
while($row_product = $product_stmt->fetch(PDO::FETCH_ASSOC)){
$id = $row_product["id"];
$title = $row_product["title"];
$description = $row_product["description"];
$price = $row_product["price"];
$img = $row_product["img"];
?>
<form onsubmit="clickButton()">
<input type="hidden" value="<? echo $title ?>" name = "title" id="title" >
<input type="hidden" value="<? echo $id ?>" name = "id" id="id" >
<input type="hidden" value="<? echo $price; ?>" name="price" id="price">
<input type="hidden" value="<? echo $img; ?>" name="img_src" id="img_src">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton();">Add Cart</button>
</form>
<?php
}
}
?>
My Ajax looks like the below:
<script type="text/javascript">
function clickButton(){
var title = $("#title").val();
var price = $("#price").val();
var img_src = $("#img_src").val();
var id = $("#id").val();
alert(title);
$("#add_to_cart").attr("disabled", true);
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src,
'id' :id
},
cache:false,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
},
success: function (data)
{
// alert(data['message']);
//enable loading
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>
When I tried to alert(title); above it return just the first array value even though I click the other arrays.
If you ignore the need for a form as you are using ajax you could streamline your code so that each record displays a single button that has various attributes set which are read by the javascript click handler and used to construct the payload sent via ajax to the php server.
$query_product="SELECT * FROM products ORDER BY id DESC";
$product_stmt = $conn->prepare( $query_product );
if( $product_stmt->execute() ){
while( $rs = $product_stmt->fetch( PDO::FETCH_ASSOC ) ){
printf(
'<input type="button" class="btn btn-outline-secondary btn-sm ajax" value="Add to cart" data-id="%s" data-title="%s" data-price="%s" data-img="%s" />',
$rs["id"],
$rs["title"],
$rs["description"],
$rs["price"],
$rs["img"]
);
}
}
?>
<script>
document.querySelectorAll('input.ajax').forEach( bttn => bttn.addEventListener('click',function(e){
let fd=new FormData();
fd.set( 'id', this.dataset.id );
fd.set( 'title', this.dataset.title );
fd.set( 'price', this.dataset.price );
fd.set( 'img_src', this.dataset.img );
alert( this.dataset.title );
$.ajax({
type:"post",
url:"my_add_cart.php",
data:fd,
cache:false,
beforeSend: function(){
$("#loading").show();
},
success:function( data ){
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
},
complete: function(){
$("#loading").hide();
}
});
}))
</script>
So I was able to solve this myself by adding the ID of each item from the loop to the ID of the input form in the HTML making the ID of each item unique. Below is how I solved it:
<form onsubmit="clickButton(<? echo $id ?>)">
<input type="hidden" value="<? echo $title ?>" name = "<? echo $id.'_title' ?>" id="<? echo $id.'_title' ?>" >
<input type="hidden" value="<? echo $id ?>" name = "<? echo $id.'_id' ?>" id="<? echo $id.'_id' ?>" >
<input type="hidden" value="<? echo number_format($price); ?>" name = "<? echo $id.'_price' ?>" id="<? echo $id.'_price' ?>" >
<input type="hidden" value="<? echo "url".$row_product_img[0]; ?>" name = "<? echo $id.'_img_src' ?>" id="<? echo $id.'_img_src' ?>">
<button type="submit" id="add_to_cart" name="add_to_cart" class="btn btn-outline-secondary btn-sm" value="Add to cart" onclick="return clickButton(<? echo $id ?>);">Add Cart</button>
</form>
And my Javascript is as below:
<script type="text/javascript">
function clickButton(id){
var title=document.getElementById(id+'_title').value;
var price=document.getElementById(id+'_price').value;
var img_src=document.getElementById(id+'_img_src').value;
var id=document.getElementById(id+'_id').value;
$("#add_to_cart").attr("disabled", true);
$.ajax({
type:"post",
url:"my_add_cart.php",
data:
{
'title' :title,
'price' :price,
'img_src' :img_src,
'id' :id
},
cache:false,
beforeSend: function(){
$("#loading").show();
},
complete: function(){
$("#loading").hide();
},
success: function (data)
{
// alert(data['message']);
//enable loading
$("#add_to_cart").attr("disabled", false);
$('#msg').html(data['message']);
$('#count').html(data['count']);
}
});
return false;
}
</script>

Unable to get button value/attribute in jquery using php loop

I'm working on "like" and "dislike" module in jQuery with PHP,And I'm facing these two problems:
Right now unable to get id of button (like=1, dislike=0)
Query showing correct result but how to display ajax response under "like dislike" section ?
Here is my code, following code inside foreach loop:
<?php foreach // ?>
<form class="form-horizontals1" method="post" >
<input type="hidden" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
<button class="likebutn_r" id="show<?php echo "1";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumb.png" height="24" width="24"></button>
<label class="lilkcount">10(dynamic) </label>
<button class="likebutn_r" id="shows<?php echo "0";?>" type="submit"><img src="<?php echo base_url(); ?>/assets/img/thumbdown.png" height="24" width="24"></button>
<label class="lilkcount">5(dynamic)</label>
<div id="counter"></div>
</form>
<?php end foreach // ?>
<script type="text/javascript">
$(document).ready(function(){
//likebutn_r
$('.form-horizontals1').submit(function(e){
var ids = $(this).attr('ids');
console.log(ids);
alert($(this).attr("id"));
e.preventDefault();
$.ajax({
url:'<?php echo base_url();?>main/AddVote',
type:"post",
data:new FormData(this),
//dataType: 'json',
processData:false,
contentType:false,
cache:false,
async:false,
success: function(data){
console.log(data);
alert(data);
$('#counter').html(data);
}
});
});
});
</script>
Here is my controller code, please tell me how I can get "like dislike" value in script and how I can show result in views ?
function AddVote()
{
$ReviewId=$_POST['ReviewId'];
$vote=$_POST['vote'];
echo $result['TotalUpVotes'] = $this->M_main->CountSubmittedCoinVote($ReviewId,$vote);
echo $result['TotalDownVotes'] = $this->M_main->CountSubmittedDownVotes($ReviewId,$vote);
}
First, move the form ouside the loop.
<form class="form-horizontals1" method="post" >
<?php foreach // ?>
<div class="my-rev-container js-rev-container">
...
</div>
<?php end foreach // ?>
</form>
Add a class to the inputs, you whould access with
<input type="hidden" class="js-form__rev" id="ReviewId" name="ReviewId" value="<?php echo $rev->id;?>">
Finaly access them
$('.form-horizontals1').submit(function(e){
var ids = $(this).find(".js-form__rev");
console.log(ids);

javascript php AJAX refresh part of a DIV

I was trying to refresh the sidebar class "login" only when a user clicked on the button, however, I am not being able to access the login.php when the user makes the click. When I click on it it's doing nothing and it's refreshing the entire page too.
For what I could understand AJAX needs to be used to refresh only that DIV and the console.log is not being triggered. What I am doing wrong here?
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form action="" method="post">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#login_button").click("login.php", function() {
console.log("login_button clicked");
});
})
</script>
<?php
}
else {
echo '<p>User is logged in</p>';
echo '<form action="" method="post">';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#logout_button").click("logout.php", function() {
console.log("logout_button clicked");
});
})
</script>
<?php
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
</body>
Thanks in advance
Your page is refreshing because of action="" on your form tags.
Also you don't need method="POST" on form tag if you are using AJAX to do so. Just remove it!
You may efficiently use ajax request in your scenario.
A suggestion: you could separate your js code out of the PHP code.
so your code will look like this -
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form id="loginForm">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
} else {
echo '<p>User is logged in</p>';
echo '<form>';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
<script type="text/javascript">
$("#login_button").click(function () {
var data = $("#loginForm").serialize();
$.ajax({
type: "POST",
url: 'login.php',
data: data,
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("login_button clicked");
});
$("#logout_button").click(function () {
$.ajax({
type: "POST",
url: 'logout.php',
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("logout_button clicked");
});
</script>
</body>

submitting a form through ajax for each ID

please guys, have some posts which i outputted from my database and now i want to make a comment form for each post and the form will be submitted through ajax method, but my problem is
the ajax method works for only the first outputted post and the form inserts into the database the mysqli_num_rows($query). ie if mysqli_num_rows($query) is =5, the form inserts into 5 rows in the database.
the remaining outputted forms reloads the page when the submit button is clicked.
This is what I want to achieve:
I want each form to be submitted without reloading.
I want the form to be inserted in only one row for each.
Here is my code:
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>
Change the input type="submit" to type="button" and make ajax on click of button.
For eg.:
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="button" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $("#my-form").serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
Above code will post the data without refreshing the page.
try this code
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form-"<?php echo $id; ?>>
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form-<?php echo $id; ?>').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>

Refresh div with jquery in ajax call

I have a div that has foreach's in them like so:
<div id="conversation">
<?php foreach($singles as $question): ?>
<div class="well well-sm">
<h4><?php echo $question['question_title']; ?></h4>
</div>
<div class="bubble bubble--alt">
<?php echo $question['question_text']; ?>
</div>
<?php endforeach; ?>
<?php foreach($information as $answer): ?>
<div class="bubble">
<?php echo $answer['answer_text']; ?>
</div>
<?php endforeach; ?>
</div>
And I also have a form to put in a new answer:
<form method="post" style="padding-bottom:15px;" id="answerForm">
<input type="hidden" id="user_id" value="<?php echo $_SESSION['user_id']; ?>" name="user_id" />
<input type="hidden" id="question_id" value="<?php echo $_GET['id']; ?>" name="question_id" />
<div class="row">
<div class="col-lg-10">
<textarea class="form-control" name="answer" id="answer" placeholder="<?php if($_SESSION['loggedIn'] != 'true'): ?>You must be logged in to answer a question <?php else: ?>Place your answer here <?php endif; ?>" placeholder="Place your answer here" <?php if($_SESSION['loggedIn'] != 'true'): ?>disabled <?php endif; ?>></textarea>
</div>
<div class="col-lg-2">
<?php if($_SESSION['loggedIn'] != 'true'): ?>
<?php else: ?>
<input type="submit" value="Send" id="newAnswer" class="btn btn-primary btn-block" style="height:58px;" />
<?php endif; ?>
</div>
</div>
</form>
I am submitting the form via ajax and would like the div #conversation to refresh and reload the for each every time the user submits an answer to the question. Right now I have the following ajax code:
<script type="text/javascript">
$("#newAnswer").click(function() {
var answer = $("#answer").val();
if(answer == ''){
$.growl({ title: "Success!", message: "You must enter an answer before sending!" });
return false;
}
var user_id = $("input#user_id").val();
var question_id = $("input#question_id").val();
var dataString = 'answer='+ answer + '&user_id=' + user_id + '&question_id=' + question_id;
$.ajax({
type: "POST",
url: "config/accountActions.php?action=newanswer",
data: dataString,
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
});
return false;
});
</script>
You will notice that I have tried $("#conversation").hide().html(data).fadeIn('fast'); but it did not successfully do the job. It only reloaded the information that was passed through ajax into the div instead of just reloading the foreach.
How can I refresh the div or the <?php foreach(); ?> in the success function of the ajax call?
Mitch, I'm looking at this part:
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
See the expression ".html(data)"??? Where is "data" being declared? The code above will never work. Now, look at the lines below. Particularly the first one. See my change?
success: function(data) {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
Once you make this change, you need to use a debugger (chrome's or otherwise) to examine that what's coming back from your ajax call (which we don't have here) is what you need. But first, fix the bug.
Good luck.
jQuery .load() method (http://api.jquery.com/load/) can fetch and update single block from webpage. It will reload whole webpage in background, so some overhead is generated..
Change your ajax success to something like below:
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#conversation").load("config/accountActions.php #conversation >*");
}
This should load your conversation block and all it's childs and replace current(old) conversation block.

Categories

Resources