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

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

Related

Ajax is not working when I fetch data from MySQL

I'm building an ecommerce.and for this I'm fetching data products from database, I want to let people add products in cart without refreshing the page, I have tried AJAX but I don't know why but it works only when data is not in a loop, I'm in PHP, and MySQL.
Code:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="upcart(<?php echo $list['id']; ?>)">
</form>
<?php
}
?>
<script>
$(document).ready(function() {
function upcart(id){
e.preventDefault();
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId"+ id).serialize(),
// dataType: "text",
success: function (response) {
alert("success");
}
// return false;
});
};
});
</script>
Use events instead of manually calling the javascript function.
We then don't need to generate id's for the forms since it we will have access to the correct form in the callback.
The PHP part:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" class="some-form-class">
<input type="hidden" name="name" value="value" />
<input type="submit" />
</form>
<?php
}
?>
The JS part:
<script>
$(document).ready(function() {
// Bind the forms submit event
$('.some-form-class').on('submit', function (event) {
event.preventDefault();
// Here we can use $(this) to reference the correct form
$.ajax({
method: "POST",
url: "data.php",
data: $(this).serialize(),
success: function (response) {
alert("success");
}
});
});
});
</script>
NOTE: Magnus Eriksson answer is far cleaner
since function upcart(id) is not in the global scope, onclick="upcart(<?php echo $list['id']; ?>)"> will fail due to the missing function
You need to declare that function in the global scope
Also, you need to prevent the form submission properly
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="return upcart(<?php echo $list['id']; ?>)">
</form>
<?php
note the return upcart .... - very important
NOT INSIDE $(document).ready(function() { since you don't need to wait for document ready to declare a function!
function upcart(id) {
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId" + id).serialize(),
success: function (response) {
alert("success");
}
});
return false; // to prevent normal form submission
}

.html file redirect to .php file after clicking a button

<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];;
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /><strong>Remove</strong></td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3><strong>{$obj->product_name}</strong></h3>
<div class="product_img"><img src="product_images/{$obj->product_img}"class="img-responsive img-thumbnail" width="150px" height="150px"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
<div class="product-price"><strong>
Price {$currency}{$obj->price}
</strong>
</div>
<fieldset>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" class="add_to_cart">Add to cart</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
Im developing a ecommerce website. I'm new to AJAX.I don't know how to solve this problem. In index.html i put ajax code to load the index.php inside the html body. And when i click "add to cart" "checkout" "update" button its redirecting to index.php instead staying on index.html.
UPDATED*
<script >
function load_data(){
$.ajax({
url: "index.php",
dataType: 'html',
cache: false,
success: function(data){
$("#mydiv").html(data);
}
});
}
$(document).ready(function(){
load_data();
});
</script>
index.html
index.php
The jQuery $.ajax() function is used to perform an asynchronous HTTP request. It was added to the library a long time ago, existing since version 1.0. The $.ajax() function is what every function discussed in the previously mentioned article calls behind the scene using a preset configuration. The signatures of this function are shown below:
$.ajax(url[, options])
$.ajax([options])
The url parameter is a string containing the URL you want to reach with the Ajax call, while options is an object literal containing the configuration for the Ajax request.
In its first form, this function performs an Ajax request using the url parameter and the options specified in options. In the second form, the URL is specified in the options parameter, or can be omitted in which case the request is made to the current page.
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
In Your case your code should be
$(document).ready(function(){
auto_load();
});
setInterval(auto_load,10000);
function auto_load(){
$.ajax({
url: 'path/to/file/index.php',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
alert(data);
//auto_load(); your code assignment and result goes here
},
type: 'GET'
});
}
and also refer https://www.sitepoint.com/use-jquerys-ajax-function/

Insert text before submitting HTML button

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>

Getting form $_POST data from Ajax/Jquery in php

As always thanks in advance if you can help with this one.
I'm trying to use Ajax to call a script and post the form data at the same time. Everything works as expected except the $POST data which comes back blank when I try to echo or print it. Can anyone shine a light on what I have missed here please?
<form id="guestlist" name="guestlist">
<?php // Collect CLUBS data to pass to guestlist script ?>
<input type="hidden" name="gl_clubname" value="<?php echo $ptitle; ?>" />
<input type="hidden" name="gl_clubnumber" value="<?php echo $phoneno_meta_value; ?>" />
<input type="hidden" name="gl_clubemail" value="<?php echo $email_meta_value; ?>" />
<?php // Collect USERS data to pass to guestlist script ?>
<input type="hidden" name="gl_name" value="<?php echo $fullname;?>" />
<input type="hidden" name="gl_email" value="<?php echo $email;?>" />
<input type="hidden" name="gl_dob" value="<?php echo $birthday;?>" />
<input type="hidden" name="gl_propic" value="<?php echo $profile_url;?>" />
<div id="clubcontactleft">
<textarea id="clubmessage" name="gl_message" placeholder="Your message" rows="4" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/userreview.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 94px; width:250px; margin-bottom:15px;"></textarea>
<input type="text" name="gl_when" placeholder="Enquiry Date" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/calendaricon.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
<input type="text" name="gl_phonenumber" placeholder="Phone Number" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/phonecall.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
</div>
<div class="guestlistbutton">Send Message</div>
</form>
<script type="text/javascript">
$(document).ready(function($){
$(".guestlistbutton").on('click',function(event) {
event.preventDefault();
$("#clubcontactform").empty();
var url = "http://www.xxxxxx.com/wp-content/themes/xxxxxx/guestlist.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#guestlist").serialize(), // serializes the form's elements.
success: function(data)
{
$('#clubcontactform').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
Here is the php file that it pulls in
<?php
echo 'Pulling in guestlist.php<br/>';
$gl_message = $_POST['gl_message'];
print_r($gl_message);
echo $gl_message;
?>
Thanks!
Every thing seems to be correct only you forget to include the jquery file. please include and try once. If still persist the issue will create the Jsfiddle
I checked your code in my local machine and I got the following error "Caution provisional headers are shown". If you have the same message in your browser console, this information can help you: "CAUTION: provisional headers are shown" in Chrome debugger
Also, I see that js work perfectly. Problem in your url address. Try send your form to itself, just write html part and php part of code in one file.
<div>
<form id="Get_FRm_Data">
/*
Some field using.....
/*
</form>
<button type="button" name="submit" class="submit_act">Submit</button>
</div>
<script>
var file_pathname = window.location.protocol + "//" + location.host + "/foldername/";
$(document).on("click", ".submit_act", function ()
{
var $this_val=$(this);
$this_val.html("Loading...").prop("disabled",true);
var $data_ref = new FormData($("#Get_FRm_Data")[0]);
$data_ref.append("action", "fileaction_name");
$pathname = file_pathname + "filename.php";
$.ajax({
url: $pathname,
type: 'POST',
data: $data_ref,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (result, status)
{
console.log(result);
if (status == "success")
{
$this_val.html("Submit").prop("disabled",false);
}
}
});
});
</script>
<?php
if (isset($_POST['action']))
{
$action = $_POST['action'];
if($action=="fileaction_name")
{
print_r($_POST);
}
}
?>

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