HTML not showing in a div when called from ajax - javascript

This is the script of ajax I am using
mypage.php
$(".sales_anchor").click(function(e)
{
e.preventDefault();
var store_username = $("#storeUsername").val();
var store_id = $("#storeID").val();
var sale_id = $(this).attr('id');
$.ajax(
{
url: 'scripts/sales_sales_products.php',
data: {"store_id": store_id, "sale_id": sale_id,"store_username": store_username},
method: 'POST',
success: function(data)
{
data = $(data).find("div#mainContentOfSale");
$("#contents").html(data);
console.log(data);
}
});
})
<div id="contents"></div>
And
sales_sales_products.php
include_once '../includes/custom_functions.php';
$stmtgetallsales = $mysqli->prepare("SELECT * FROM store_sales ss
INNER JOIN store s ON s.store_id=ss.store_id
WHERE s.store_id=?");
$stmtgetallsales->bind_param("i",$_POST['store_id']);
$stmtgetallsales->execute();
$getallsales = $stmtgetallsales->get_result();
$sales_rows = $getallsales->num_rows;
$stmtgetallsales->close();
?>
<script src="js/3.1.1/jquery.min.js"></script>
<script src="../js/jquery.countdown.min.js"></script>
<div class="container" id="mainContentOfSale">
<?php while($allsales = $getallsales->fetch_assoc())
{
$stmtgetsaleproducts = $mysqli->prepare("SELECT * FROM store_products sp
INNER JOIN store_sale_products ssp ON sp.product_id = ssp.product_id
WHERE ssp.sale_id=? AND sp.store_id=?");
$stmtgetsaleproducts->bind_param("ii",$allsales['sale_id'],$_POST['store_id']);
$stmtgetsaleproducts->execute();
$getsaleproducts = $stmtgetsaleproducts->get_result();
$sale_product_rows = $getsaleproducts->num_rows;
$stmtgetsaleproducts->close();
?>
<script>
$(document).ready(function() {
$('.products_title').hide();
$(".timer").each(function() {
var time = this.id;
var timeLeft = time.split('-').reverse().join('-');
$(this).countdown(timeLeft, function(event) {
$(this).text(event.strftime("%D days %H hours %M minutes %S seconds remaining"));
});
})
});
</script>
<div class="sale_title">
<h2 class="title" id="sale_products"><?php echo $allsales['sale_name']; ?></h2> <span class="badge"><?php echo $sale_product_rows; ?></span> <span class="timer" id="<?php echo $allsales['sale_till']; ?>"></span></div>
<div class="sale_title"><span class="discount">Discount: <span class="color-text"><?php echo $allsales['sale_discount']; ?></span>%</span></div>
<div class="product_area wrapper ">
<?php while($saleproducts = $getsaleproducts->fetch_assoc()){?>
<div class="product">
<a href="<?php echo " index.php?store=".$_POST['store_username']." &view=single&product=".$saleproducts['product_id']; ?>">
<div class="product-image">
<img src="<?php echo image_check($saleproducts['product_image1']); ?>" />
</div>
</a>
<div class="product-details">
<div class="product-name">
<a class="name" href="<?php echo " index.php?store=".$_POST['store_username']." &view=single&product=".$saleproducts['product_id']; ?>"><span><?php echo substr($saleproducts['product_name'], 0, 20); ?></span></a>
</div>
<div class="product-price">
<span class="price"># Rs. <?php echo sale_price($allsales['sale_discount'],$saleproducts['product_price']); ?>/</span>
</div>
</div>
</div>
<?php }?>
<?php } ?>
When I call the anchor tag with class sales_anchor it calls this script and in the inspect element and in network tab when I check the script it does populated the data and html and everything is fine. But it isn't getting called in the current page and in contents div. What am I doing wrong?

You are encountering an JSON.parse error in your screenshot. (Notice the red bar above your result window saying SyntaxError: JSON.parse: unexpected character at line 1 column 9 of the JSON data)
This is because $.ajax is trying to parse the response as a JSON string to an object (the default behaviour).
Please change your ajax function to this:
$(".sales_anchor").click(function(e)
{
e.preventDefault();
var store_username = $("#storeUsername").val();
var store_id = $("#storeID").val();
var sale_id = $(this).attr('id');
$.ajax(
{
url: 'scripts/sales_sales_products.php',
dataType: "text",
data: {"store_id": store_id, "sale_id": sale_id,"store_username": store_username},
method: 'POST',
success: function(data)
{
data = $(data).find("div#mainContentOfSale");
$("#contents").html(data);
console.log(data);
}
});
})
<div id="contents"></div>

Related

Error on Infinite scroll with Ajax, PHP and MySQL

I am trying to implement an infinite scroll in my application but at the moment of reaching the end of my page, this throws the error that places.
This is the ajax code:
<script type="text/javascript">
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var last_id = $(".post-id:last").attr("id");
loadMoreData(last_id);
}
});
function loadMoreData(last_id){
$.ajax(
{
url: '/loadMoreData.php?last_id=' + last_id,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
Here, is where I show the data from th DataBase:
<?php while ($post = $result -> fetch(PDO::FETCH_ASSOC)){ ?>
<div class="box-list" id="post-data">
<div class="item">
<div class="row">
<p class="post-id hidde" id="<?php echo $post['id']; ?>">
<div class="col-md-1 hidden-sm hidden-xs">
<div class="img-item"><img src="<?php echo OTRA; ?>/images/<?php echo $post['thumb']; ?>" alt=""></div>
</div>
<div class="col-md-11">
<h3 class="no-margin-top"><?php echo $post['titulo']; ?> <i class="fa fa-link color-white-mute font-1x"></i></h3>
<h5><span class="color-black"><?php echo $post['company']; ?></span> - <span class="color-white-mute"><?php echo $post['locacion']; ?></span></h5>
<p class="text-truncate "><?php echo $post['extracto']; ?></p>
<div>
<span class="color-white-mute"><?php echo fecha($post['fecha']); ?></span>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
and this id the other PHP file to load more data:
<?php session_start();
require 'extras/config.php';
require 'functions.php';
comprobarSession();
$conexion = conexion($bd_config);
$qry = "SELECT * FROM publications WHERE id > '$_GET['last_id']' ORDER BY id DESC LIMIT 8";
$result = $conexion->query($qry);
print_r ($result);
$json = include('views/empleos.php');
echo json_encode($json);
on the Developer Tool of Chrome the error that show me is
jquery.js:8706 GET http://localhost/loadMoreData.php?last_id=9 404 (Not Found)
What is the name of that php file? Sounds like it is not loadMoreData.php? Perhaps it is loadData.php, and the AJAX call should be changed?

I want to count coupon usage on my page.But it keeps updating whenever i refresh the page

HERE IS THE CODE I'M USING TO UPDATE THE COUPON COUNT.
<div id="click" class="coupon-detail coupon-button-type">
<a href="#" class="coupon-button coupon-code" data-aff-url="https://example.com">
<span class="code-text">CODE</span>
<span class="get-code">Get Code</span>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="coupon-footer coupon-listing-footer">
<ul class="clearfix">
<script type="text/javascript">
$(document).ready(function(e) {
$('#click').click(function(){
<?php
$update = "UPDATE coupon_stats SET today = today + 1";
$query_coupon = mysqli_query($con , $update)or die(mysqli_error($con));
?>
})
});
</script>
<?php
$select = "SELECT * FROM coupon_stats";
$query_select = mysqli_query($con,$select);
$data = mysqli_fetch_assoc($query_select);
?>
<li><span><i class="wifi icon"> </i> <?php echo $data['today'].' Coupon Used'; ?>
</span>
</li>
but my coupon count is getting +1 whenever I refresh the page instead of clicking on the button.
I'm not getting an idea. What am I doing wrong?
Can anyone help me to solve this?
This should do what you need.
We set data: 1 in the ajax request, so you can perform a check when the page loads if(isset($_POST['data])) on the process_request.php file.
<div id="click" class="coupon-detail coupon-button-type">
<a href="#" class="coupon-button coupon-code" data-aff-url="https://example.com">
<span class="code-text">CODE</span>
<span class="get-code">Get Code</span>
</a>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="coupon-footer coupon-listing-footer">
<ul class="clearfix">
<?php
$select = "SELECT * FROM coupon_stats";
$query_select = mysqli_query($con,$select);
$data = mysqli_fetch_assoc($query_select);
?>
<li>
<span>
<i class="wifi icon"></i> <?php echo $data['today'].' Coupon Used'; ?>
</span>
</li>
<script>
$(document).ready(function(e) {
$('#click').click(function(){
$.ajax({
url : "process_request.php",
type: "POST",
data: {data: 1},
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
})
});
</script>
In process_request.php
<?php
//Add db connection details
if(isset($_POST['data'])){
$update = "UPDATE coupon_stats SET today = today + 1";
$query_coupon = mysqli_query($con , $update)or die(mysqli_error($con));
}
?>
You can go further and add a response from process_request.php and then handle that in the success function of AJAX.

trying to add ajax request html to page source

I'm working on a project using ajax and PHP, my problem is when I add HTML markup with ajax it's not showing in page source and that preventing my from making another request to delete this markup and the only way that makes my delete it redirect to the same page.
this is my markup code:
<div class="card">
<div class="card-content">
<form>
<div class="input-field">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Type something here</label>
</div>
</form>
</div>
<div class="card-action">
<button id="submit" class="btn waves-effect waves-light" type="submit" disabled>Submit</button>
</div>
</div>
<div id="cards--wrapper">
<?php
$query = "SELECT * FROM messages ORDER BY id DESC";
$retrieve_posts_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($retrieve_posts_query)){
$content_id = $row['id'];
$post_content = $row['posts'];
$post_date = $row['date'];
$post_date = strtotime($post_date);
$post_date = date('j F, Y', $post_date);
?>
<div class="card" data-id = "<?php echo $content_id; ?>">
<a class="btn-large waves-effect waves-light red right delete">+</a>
<div class="card-content">
<?php echo $post_content; ?>
<span> <?php echo $post_date; ?> </span>
</div>
</div>
<?php } ?>
</div>
and this is my ajax code :
window.onload = function(){
$('#textarea1').keyup(function(){
var messageInput = $(this).val();
if( messageInput !== '' ){
$('#submit').attr('disabled', false);
}else {
$('#submit').attr('disabled', true);
}
});
$('#submit').on('click', function(){
retrieveData();
return false;
});
function retrieveData(){
var messageInput = $('#textarea1').val();
$.ajax({
url: 'server.php',
type: 'POST',
data: {
message : messageInput
},
success: function(data) {
$('#cards--wrapper').prepend(data);
$('#textarea1').val('');
$('#submit').attr('disabled', true);
window.location.href = 'index.php';
}
});
}
$('.delete').on('click', function(e){
e.preventDefault();
var that = $(this);
var cardID = that.parent().data('id');
var el = that.parent();
$.ajax({
url: 'delete.php?delete='+ cardID +'',
type: 'GET',
success: function(){
el.remove();
}
});
});
}

How to get my link into a variable?

I got these files:Updating script:
<script>
function TradeURLTimer() {
setInterval(function(){
jQuery.ajax({
url: "assets/cores/check_username.php",
data:'TradeURL='+$("#TradeURL").val(),
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
},
error:function (){}
});
}, 3000);
}
</script>
My check_username.php:
<?php
// Variables to connection
$mysql_hostname = "localhost";
$mysql_user = "*******";
$mysql_password = "*********";
$mysql_database = "**********";
$prefix = "";
// Create connection
$conn = mysql_connect($mysql_hostname, $mysql_user, $mysql_password);
$connect = mysql_select_db($mysql_database, $conn);
$TradeURL=$_POST['TradeURL'];
$count_TradeURLs = mysql_num_rows(mysql_query("SELECT * FROM users WHERE TradeURL='$TradeURL'"));
switch ($count_TradeURLs) {
case "0":
?>
<section class="feed-item col-md-2 pull-left">
<div style="padding-top: 5px;" class="icon">
<i class="fa fa-check color-green"></i>
</div>
</section>
<?php
echo $TradeURL;
break;
case "1":
?>
<section class="feed-item col-md-2 pull-left">
<div style="padding-top: 5px;" class="icon">
<i class="fa fa-remove color-red"></i>
</div>
</section>
<?php
break;
}
?>
My inserted text $_POST['TradeURL'] is = https://steamcommunity.com/tradeoffer/new/?partner=53756765&token=bnsKYKib But somehow when I ask the check_username.php to echo the variable $TradeURL, then it is only https://steamcommunity.com/tradeoffer/new/?partner=53756765 So something is removing the last part of the link: "&token=bnsKYKib" Why does this happen? I can't figure it out. I tried to convert it into a string and split it, but still the same outcome...
As #leonardo_palma pointed out, your TradeURL variable is being parsed by PHP.
You have to encode it to send it to the other page, and then to decode it.
Here is how you can do it:
updating script:
// ...
data: 'TradeURL='+encodeURIComponent($("#TradeURL").val()),
// ...
check_username.php:
// ...
$TradeURL = urldecode($_POST['TradeURL']);
// ...

how to change the html tag element when onclick to a input text, so the user can edit comment

I am actually trying to make comments and also edit option when the comment enters it will show in a 'div'through ajax.
<?php
$q="select * from discuss where rownum=1 order by id desc";
$s=oci_parse($conn, $q);
$r=oci_execute($s) or die(oci_error());
echo "<table border=1>";
while($m=oci_fetch_assoc($s))
{
echo "<tr style='background-color:red'><th style='float:left;color:white'>Name : ".$m['NAME']."</th><th style='float:right;color:white'>Date: "."".$m['DATE_TIME']."</th></tr>";
echo "<tr class='edit_option' style='width:1000px;height:10px;background- color:white'><div><td id='input_text' style='width:1000px;height:10px;background- color:white'>".$m['COMMENTS']."</div><div class='anchor_edit' id='anchor_id_edit'><span onclick=\"edit_text('".$m['COMMENTS']."')\">edit</span></div></td></tr>";
}
echo "</table>";
?>
<script>
function edit_text(edit_option){
alert(edit_option);
}
</script>
onclick the function value is coming to edit_text() function getting alert, here i am not getting how can iput logic for this comment.
when edit option is clicked the user has to get his/her comment in a input text 'value' so the user can edit comment.
onclick how can i do the edit comment, please anyone can help!!
This may be help to you
Here I take a sample array input data
PHP SCRIPT
<?php
$r=array(
array('COMMENT-ID'=>'1','NAME'=>'Comment1','COMMENTS'=>'Comment1Comment1Comment1Comment1','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'2','NAME'=>'Comment2','COMMENTS'=>'Comment2Comment2Comment2Comment2','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'3','NAME'=>'Comment3','COMMENTS'=>'Comment3Comment3Comment3Comment3','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'4','NAME'=>'Comment4','COMMENTS'=>'Comment4Comment4Comment4Comment4','DATE_TIME'=>'12547896321')
);
echo "<div>";
foreach($r as $m)
{ ?>
<div>
<div>
Name : <?php echo $m['NAME']; ?>
</div>
<div>
Date: <?php echo $m['DATE_TIME']; ?>
</div>
</div>
<div class="comment">
<div class="comment-text" id="comment<?php echo $m['COMMENT-ID']; ?>">
<?php echo $m['COMMENTS']; ?>
</div>
<div class="commentEditBtn">
Edit
</div>
<div class="editedText"></div>
<div class="commentInput" data-id="<?php echo $m['COMMENT-ID'] ?>">
<input type="text" name="comment" /><br/>
<button class="commentSubmit">Submit</button>
</div>
</div><br/>
<?php }
echo "</div>";
?>
jQuery
$(".commentEditBtn").on('click',function(){
$('.commentinput').hide();
var parentDiv = $(this).parent();
var commentText = parentDiv.find('.comment-text').html();
parentDiv.find('.commentInput input').val(commentText.trim());
parentDiv.find('.commentInput').show();
});
$(".commentInput > input").keypress(function(){
var commentData = $(this).val();
$(this).parent().parent().find('.editedText').html(commentData.trim()).show();
});
$(".commentInput .commentSubmit").on('click',function(){
var commentId = $(this).parent().attr('data-id');
var commentText = $(this).parent().find('input').val().trim();
$(this).parent().parent().find('.editedText').html('').hide();
$.ajax({
url: "AJAX_POST_URL",
type: "POST",
data: {
commentId: commentId,
commentText: commentText
},
dataType: 'json',
success: function (data) {
if (data.error == 'false') {
$('#comment' + commentId).html(commentText);
}
}
});
});
CSS
.commentInput{display: none;}
.editedText{display: none;}
Check out this jquery plugin: http://jsfiddle.net/2u89gnn8/1/
You can make, for example, an h1 editable when a user clicks a button:
$('h1').editable({
"enable": true,
"trigger": $('button')
});

Categories