How to get my link into a variable? - javascript

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']);
// ...

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.

HTML not showing in a div when called from ajax

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>

jQuery scrollTop after ajax load not working

After ajax load of html content I need to scroll to specific element. The element has attr data-event-id="" But sometimes this variable $('.timelineToolPanel[data-event-id="'+id+'"]').offset().top; returns 0. Whole ajax code is:
function refreshContent(id)
{
var scrollNumber = 0;
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("user/ajaxEventLoad"); ?>',
dataType:'html',
success:function(data){
$("#eventListBlock").empty().append(data);
if(id!=null) {
console.log(id);
scrollNumber = $('.timelineToolPanel[data-event-id="'+id+'"]').offset().top;
console.log(scrollNumber);
$("html, body").animate({
scrollTo: scrollNumber
}, 1000, function() {
// alert("Finished animating");
});
}
},
error: function(data) { // if error occured
alert("Error occured. please try again");
}
});
}
and html:
<div id="eventListBlock">
<?
$this->renderPartial('/windows/timelineWindow', array(
'dataProvider'=>$dataProvider
));
?>
</div>
with rendering this part:
<div class="cd-timeline-block">
<div class="cd-timeline-icon" style="background: <? echo $data->color ?>">
<i class="fa fa-<? echo $data->icon ?>"></i>
</div>
<div class="cd-timeline-content">
<div class="timelineToolPanel" data-event-id="<? echo $data->id ?>">
<i class="fa fa-pencil timelineToolPanelEdit"></i>
<i class="fa fa-trash timelineToolPanelDelete"></i>
</div>
<h2><? echo $data->title ?></h2>
<p><? echo $data->content ?></p>
<span class="cd-date"><? echo date("d. m. Y", strtotime($data->date_event)); ?></span>
</div>
</div>
where #eventListBlock is fixed container.
custom attributes in html have to be defined with "data-*", otherwise it won't work.
http://www.w3schools.com/tags/att_global_data.asp
name your attr in "data-event-id=" and it should do the job, even when i have not proofed the JS code :D

Codeigniter: Retrieving data on button click with Ajax

I have a simple webpage which generates a random quote from my database upon refreshing the page. I wish to implement some AJAX and JQuery in order to generate quotes via the button rather than having to refresh the page. I have done some research but I am not sure how to implement this in Codeigniter. My current code is below...
Page controller:
public function index() {
$this->load->model('quote_model', '', TRUE);
$data['quotes'] = $this->quote_model->getRandom();
$this->load->view('home', $data);
}
The view:
<?php include ('layout/header.php'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 quote-holder">
<img src="application/assets/alan1.jpg" alt="..." class="img-circle img-responsive">
<br>
<blockquote class="text-center">
<p><?php echo $quotes[0]['quote']; ?></p>
<footer class="text-center"><?php echo $quotes[0]['character_name']; ?> in <cite title="Source Title"><?php echo $quotes[0]['series_name']; ?></cite></footer>
</blockquote>
<button type="button" class="btn btn-default center-block">Generate quote</button>
</div>
</div>
<?php include ('layout/footer.php'); ?>
Here is the function in the model I am retrieving the data from:
function getRandom() {
$query = $this->db->query("
SELECT * FROM quotes, characters, series
WHERE quotes.series_id = series.series_id AND quotes.character_id = characters.character_id
ORDER BY rand()
LIMIT 1
");
return $query->result_array();
}
Should I simply be using something like this?
$("button").click(function(){
$.get( "Page/index", function( data ) {
//output data to page element...
}
});
getI would do something like: controller:
public function callme()
{
$this->load->model('quote_model);
$data['quotes'] = $this->quote_model->getRandom();
}
Then in my footer:
condole.log("click button")
var_url = "controller/callme" // the url to the controller and method
$.get({
url: url
})
But meh, im bad at programming and even worse at jquery :D
Make hidden input for offset
<button onclick="showmore()" value="showmore" />
<input type="hidden" name="offset" id="offset" value="15"/>
Now Your Ajax Call
function showmore(){
$.ajax({
url:my_controller/showmore,
data:{
offset :$('#offset').val()
},
type:json,
success :function(data){
$('#show-more').prepand(data.view)
$('#offset').val(data.offset)
}
})
}
Your Controller
function showmore(){
$limit = '10';
$offset = $this->input->get('offset');
$result = $this->yourmodel->getdata($offset,$limit);
$data['view'] = $result;
$data['offset'] =$offset +10;
echo json_encode($data);
}
Your Model
$query = $this->db->get('your_table', $limit, $offset);
$data=$query->result_array();
return $data;

Categories