How to send $_GET by Ajax - php

I am trying to send an $_GET['CategoryID'] trought ajax to call in the destination file getdata.php and I can't make it work, I don't find the perfect info here. I know that I am really noob, but I am trying really hard to learn.
I been trying a lot of different code and it still not working.
<button type="button" name="btn_more" data-vid="<?php echo $stockID; ?>" id="btn_more" class="btn btn-success form-control">Ver Mais</button>
<input class="form-control" id="PresentCategoryID" name="PresentCategoryID" data-cat="<?php echo $_GET['categoryID']; ?>" value="<?php echo $_GET['categoryID'];
<script>
$(document).ready(function(){
$(document).on('click', '#btn_more', function(){
var last_video_id = $(this).data("vid");
var PresentCategoryID= ('PresentCategoryID');
$('#btn_more').html("<div class=loader></div>");
$.ajax({
url:"getdata.php",
method:"POST",
data:{
last_video_id:last_video_id,
PresentCategoryID:PresentCategoryID},
dataType:"text",
success:function(data)
{
if(data != '')
{
$('#remove_row').remove();
$('#result').append(data);
}
else
{
$('#btn_more').html("No Data");
}
}
});
});
});
</script>
My objective it's to call the categoryID in the getdata.php, like this,
<?php
$output = '';
$stockID = '';
$PresentCategoryID = '';
sleep(1);
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID > ".$_POST['last_video_id']." LIMIT 4";
?>

var PresentCategoryID= ('PresentCategoryID')
should be
var PresentCategoryID= $('#PresentCategoryID').val();
You need to use $ to select the element, add the # prefix to use it as an ID, and .val() to get the value of the input.

hey check this answer which will help your problem
$(document).ready(function() {
$(document).on('click', '#btn_more', function() {
var last_video_id = $(this).data("vid");
var PresentCategoryID = ('#PresentCategoryID').val();
$('#btn_more').html("<div class=loader></div>");
var data = {
last_video_id,
PresentCategoryID
};
$.get('getdata.php', JSON.stringify(data)).done(response => {
console.log(response);
if (response != '') {
$('#remove_row').remove();
$('#result').append(response);
} else {
$('#btn_more').html("No Data");
}
}).fail(() => {
console.log("Something went wrong");
});
});
});
PHP SCRIPT
<? php
include 'includes/dbh.inc.php';
include 'includes/rating.inc.php';
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
//if you using get request
//recommended way to get the data use the mysqlconn->real_escape_string($_GET['last_video_id']);
$last_video_id = $_GET['last_video_id'];
$PresentCategoryID = $_GET['PresentCategoryID'];
sleep(1);
$sql = "SELECT stock.stockID, stock.name, stock.marca, stock.origem, stock.categoryID, stock.thumbnail, category.name AS catname FROM stock JOIN category ON stock.categoryID=category.categoryID WHERE stock.categoryID='$PresentCategoryID' AND stockID='$$last_video_id'";
" LIMIT 4";
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//if you using post request then in jquery remove $.get to just $.post
$data = json_decode(file_get_contents('php://input'),true);
$last_video_id = $data['last_video_id'];
$PresentCategoryID = $data['PresentCategoryID'];
}

you want to send via 'GET' but you use the method 'POST'.
Best regards
MrKampf

Related

PHP - variable from GET is changing

I have a svg.php file with some shapes.
<rect onclick="window.location='search.php?filter=1'" width="50" height="50">
<rect onclick="window.location='search.php?filter=2'" width="50" height="50">
Search.php
div class="container">
<textarea class="search" id="search_id"></textarea>
<div id="result"></div>
<?php include("svg.php"); ?>
</div>
//This is for a autocomplete search, took it from http://www.2my4edge.com/2013/08/autocomplete-search-using-php-mysql-and.html
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var search_id = $(this).val();
var dataString = 'search='+ search_id;
if (search_id=='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).hide(); }
});
};
if(search_id!='') {
$.ajax({
type: "POST",
url: "search_database.php",
data: dataString,
cache: false,
success: function(html) {
$("#result").html(html).show(); }
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#search_id').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#search_id').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Then a search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
echo $search; //echos "2".
if ($search=="1") {
echo $search; //enters if, and it's not supposed to, and echos "1"
Select * from table;
}
Search_database.php
$search = isset($_GET['filter']) ? $_GET["filter"] : "1";
echo $search //echos "2";
if ($search=="1") {
$q = $_POST['search'];
$q_length = strlen($q);
$sql = <<<SQL
SELECT * FROM table
LIMIT 6
SQL;
if(!$result = $con->query($sql)){
die('There was an error running the query [' . $con->error . ']');
}
while($row = $result->fetch_array()) { ?>
<div class="show_search">
<?php echo $row['name'] ?> </a>
</div>
<?php } } ?>
I'm on search.php?filter=2 and the first echo is correct ("2") but for some reason it keeps entering the If Clause and echos that $search is "1".
I'm not defining the $search variable anywhere else. Thank you for your help.
Your code is a bit too complicated.
$search = isset($_GET['filter']) ? $_GET["filter"] : 1;
if($search == 1) {
echo $search;
}
Thats enough, you don't need the check if $_POST is available. That make not so much sense because you don't send a form and you don't have post data in that case when you it with window.location.
If there is no other code between following two lines:
echo $search; //echos "2".
AND
if ($_POST AND $search=="1") { ... }
Then, its not possible to go inside if condition. its only possible if your if condition is like if($_POST AND $search=1). Check that, whether you have single = or double == in comparing $search variable.
If there is some php code in between, then show us, whatever it is, so that we can help you.

How to update information by the click of a button?

I currently have two php files (index.php and update.php) In index.php, there is some javascript code and a button that sends a variable, called $sid, to update.php, where it is processed based on $sid. Here is the code for both index.php and update.php. I am not pasting it directly into StackOverflow, simply because of how you have to add code to your text on StackOverflow, and how JavaScript works with it's spacing hierarchy.
http://pastebin.com/fq87vvgz
Currently, when you press the button, an alert box does not pop up. If you put the PHP code in a PHP code checker, no errors appear.
Here is my code:
This is what is in index.php
<?php
$sid = 11;
?>
<script type="text/javascript">
$(document).ready(function(){
$('#vote').click(function(){
$.ajax({
url : 'update.php', // Notice how this sends to update.php
type : 'POST',
data : {
action : 'vote_server',
sid : $('#sid').data('sid')
},
dataType : 'JSON',
success : function(result) {
if (result.xhr == 'success') {
alert('You bumped your server!');
} else if (result.xhr == 'voted_already')
alert('You can only bump every 24 hours!')
}
});
});
})
</script>
<input type="button" class="btn btn-primary" id="vote" value="Vote up your server">
This is what is contained in update.php
<?php
define('action',$_POST['action']);
$result = array(
'xhr' => 'error'
);
if (action == 'vote_server')
{
$sid = (int)$_POST['sid'];
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$dbTime = #mysql_result(mysql_query("SELECT `id`, `last_updated` FROM `servers` WHERE `id` = '$sid'"), 0);
$timeDiff = $time - $dbTime;
if($timeDiff >= 86400){
mysql_query("UPDATE `servers` SET `last_updated` = '$time' WHERE `id` = '$sid'");
$result['xhr'] = 'success';
} else { $result['xhr'] = 'voted_already'; }
}
echo json_encode($result);
?>
Use query and ajax
in your index page...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$( ".button" ).click(function() {
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
$.ajax({
type: "POST",
url: 'update.php',
data: {postedVar:var1, postedVar2:var2},
success: function(data)
{
alert(data);
}
});
});
});
</script>
<html>
<button class="button" data-var1="<?php echo "this is var1"; ?>" data-var2="<?php echo "this is var2"; ?>">Button</button>
</html>
On you update page...
access your vars like this
<?php
var1 = $_POST['postedVar1'];
var2 = $_POST['postedVar2'];
echo var1;
?>
...NOT TESTED

Ajax call not working when sending data to another page

Here is my code:
<div class="category" id="<?php echo $cat->term_id; ?>"><?php echo $cat->cat_name; ?> </div>
$(".category").click(function(){
var categ = $(this).attr('id');
alert(categ);
ajax({
type:'POST',
url:'http://myweb.com/rel_notes/?page_id=238',
data:'cat='+categ,
success:function(data) {
if(data) {
} else { // DO SOMETHING
}
}
});
});
and the code behind the page which is receiving the posted data (http://myweb.com//rel_notes/?page_id=238) is here:
<?php
if (isset($_POST['cat']))
{
$cat_id = $_POST['cat'];
echo "<script>alert('$cat_id')</script>";
}
else
$cat_id = NULL;
?>
Problem: It didn't get the value in $cat_id. I tried changing $_POST to $_GET but that didn't work too. So kindly help me where am i missing something?
$.ajax({
type:'POST',
data: {cat: categ},
url:'http://myweb.com//rel_notes/?page_id=238',
error: function() {
alert("Data Error");
},
success:function(data) {
if(data) {
} else {
}
}
});
This is not good way dude.
None can make alert on server side.
You are doing alert code on the server side.
Just replace
<?php
if (isset($_POST['cat']))
{
$cat_id = $_POST['cat'];
echo "<script>alert('$cat_id')</script>";
}
else $cat_id = NULL;
?>
by
<?php
if (isset($_POST['cat']))
{
echo $cat_id = $_POST['cat'];
}
else {
echo $cat_id = "";
}
?>
and alert the code like
$(".category").click(function(){
var categ = $(this).attr('id');
alert(categ);
ajax({
type:'POST',
url:'http://myweb.com/rel_notes/?page_id=238',
data:'cat='+categ,
success:function(data) {
if(data != "") {
alert(data);
}else { // DO SOMETHING
}
}
});
});

How do I make an onclick ajax request for favorites button work properly

I have a list on my site that has a favorites button associated with each item on the list. I am using an image as the button to click. The PHP for it is:
echo "<img src=\"./images/emptystar.png\" alt=\"favorite\" class=\"favoritebutton\" billid=\"" . $count['id'] ."\" userid=\"". $_SESSION['userid'] ."\" />\n";
I have javascript/jQuery to make an onclick of that image submit an AJAX request to a PHP file.
$(document).ready(function() {
$(".favoritebutton").click(function () {
var billid = $(this).attr("billid");
var userid = $(this).attr("userid");
var ajaxrequest;
var params = "billid=" + billid + "&userid=" + userid;
ajaxrequest.open("POST","./ajaxphp/favorites.php",true);
ajaxrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxrequest.setRequestHeader("Content-length", params.length);
ajaxrequest.setRequestHeader("Connection", "close");
ajaxrequest.send(params);
ajaxrequest.onreadystatechange=function()
{
if (ajaxrequest.readyState===4 && ajaxrequest.status===200)
{
if(ajaxrequest.responseText === "true")
{
if($(this).attr("src") === "./images/emptystar.png")
{
$(this).attr("src","./images/fullstar.png");
}
else
{
$(this).attr("src","./images/emptystar.png");
}
}
}
};
});
});
The php file at ./ajaxphp/favorites.php is the following:
<?php
include("./includes/dbcxnfunction.inc");
$billid = $_POST['billid'];
$userid = $_POST['userid'];
$query = "IF NOT EXISTS (SELECT * FROM favoritebills WHERE userid = '$userid' AND billid = '$billid' )
INSERT INTO favoritebills (userid,billid) VALUES($userid,$billid)
ELSE
DELETE FROM favoritebills WHERE userid = '$userid' and billid = '$billid' ";
$result = mysqli_query(dbcxn('bill'),$query)
or exit("Couldn't execute query for favorites");
if($result)
{
$request = "true";
}
else
{
$request = "false";
}
echo $request;
?>
In particular I am concerned with the SQL query and the javascript because I am not certain of their correctness, but I used a validator for the javascript with JQuery and everything is valid.
When I click the image on the page, nothing happens even though I have tested both conditions for the image change. Either the javascript is written incorrectly, or there is never a response sent back from the favorites.php file.
The network tab in console.
Use JQuery's .ajax and pass the clicked element by storing it in var before you make the ajax call
$(".favoritebutton").click(function () {
//Store $(this) in var so that it can be passed inside the success function
var this$ = $(this);
var billid = this$.attr("billid");
var userid = this$.attr("userid");
$.ajax( { url : "./ajaxphp/favorites.php", type: 'post', data : { billid : billid , userid : userid },
success : function( responseText ){
if( responseText == "true"){
if( this$.attr("src") == "./images/emptystar.png"){
this$.attr("src","./images/fullstar.png");
}else{
this$.attr("src","./images/emptystar.png");
}
}
},
error : function( e ){
alert( ' Error : ' + e );
}
});
});

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories