Ajax call not working when sending data to another page - php

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

Related

How to send $_GET by Ajax

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

Checkbox an values to transmit to database

I'm new here and I need help with a PHP code.
I want to transform a radio button into a checkbox, make it calculate the fee depending on how much checkboxes are checked, and to transmit the checked values to the predefined database.
My code only takes the one predefined value for fee an doesn't actually adds them up when I click on the other checkbox. I tried everything but with no success. Here is the original unchanged code:
<script src="<?php echo URL_FRONT_JS;?>jquery.js"></script>
<script>
function get_tutor_course_details()
{
course_slug = $('#course_slug option:selected').val();
selected_date = $('#start_date').val();
if(!course_slug || !selected_date) {
$('#fee').text('');
$('#duration').text('');
$('#days_off').text('');
$('#content_li').remove();
$('#time_slot_div').text('<?php echo get_languageword("please_select_course_and_date_first"); ?>');
return;
}
$.ajax({
type: "POST",
url: "<?php echo URL_HOME_AJAX_GET_TUTOR_COURSE_DETAILS; ?>",
data: { "course_slug" : course_slug, "tutor_id" : <?php echo $row->id; ?>, "selected_date" : selected_date },
cache: false,
beforeSend: function() {
$('#time_slot_div').html('<font color="#5bc0de" size="6"> Loading...</font>');
},
success: function(response) {
if(response == "") {
$('#fee').text('');
$('#duration').text('');
$('#days_off').text('');
$('#content_li').remove();
$('#time_slot_div').html('<?php echo get_languageword("no_slots_available."); ?> <?php echo get_languageword("click_here_to_send_me_your_message"); ?>');
$('#request_tutor_btn').slideUp();
} else {
var fee_duration = response.split('~');
var fee = fee_duration[0];
var duration = fee_duration[1];
var content = fee_duration[2];
var time_slots = fee_duration[3];
var days_off = fee_duration[4];
$('#fee').text(fee +'€');
$('#duration').text('EUR');
if(content) {
$('#content_li').remove();
$('#course_li').after('<li id="content_li"><?php echo get_languageword("course_content"); ?><p>'+content+'</p></li>');
}
time_slot_html = "";
if(time_slots != "")
time_slots = time_slots.split(',');
total_available_timeslots = time_slots.length;
if(total_available_timeslots > 0) {
for(i=0;i<total_available_timeslots;i++) {
check_radio = "";
if(i == 0)
check_radio = 'checked = "checked"';
time_slot_html += '<li><div><input id="radio1'+i+'" type="radio" name="time_slot" value="'+time_slots[i]+'" '+check_radio+' ><label for="radio1'+i+'"><span><span></span></span>'+time_slots[i]+'</label></div></li>';
}
$('#time_slot_div').html(time_slot_html);
$('#request_tutor_btn').slideDown();
} else {
$('#time_slot_div').html('<?php echo get_languageword("no_slots_available."); ?> <?php echo get_languageword("click_here_to_send_me_your_message"); ?>');
$('#request_tutor_btn').slideUp();
}
}
}
});
}

Stop Execution Php

I have this code , iam trying to use javascript to stop executing but its not working with javascript , any suggestions ? Am just trying to stop executing if the return was false from the javascript
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if (r == true) {
return true;
} else {
return false;
}
}
check();
</script>
<?php
}
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run)die("error".mysql_error());
I am adding sample code to give you an idea, how you could use AJAX Call with it.
<?php
if(mysql_num_rows($runzz)==0){
echo "<p align='center'><font size='5'>This Item $code1 - $code2 - ".$rw2['description']. "</br></br> Doesn't Exist In The <u><b>".$rowto['name']."</b></u></br></br> Wanna Add IT ?</font></p>";
?>
<script>
function check(){
var r = confirm("Press a button!");
if(r) {
// Add additional parameter
// You could use POST method too. Use whatever make sense to you.
var urlLink = 'http://www.example.com/warehouse/record.php?from=<?php echo $from?>&to=<?php echo $to?>';
$.ajax({
type: 'GET',
url: urlLink,
success: function(data) {
if(data == 'success') {
return 'You have successfully added new record!';
}
},
error: function(data) {
console.log(data);
}
});
} else {
return false;
}
}
check();
</script>
<?php } ?>
<?php
// -- New File: record.php File
//
// You might wanna add the check, that it's the legit request and all the PHP Validation
$form = $_GET['from'];
$to = $_GET['to'];
$qty = $_GET['qty'];
$codeid = $_GET['codeid'];
$uid = $_GET['uid'];
$insert="INSERT INTO transfercopy(warehouseidfrom,warehouseidto,qty,itemid,uid)VALUES('$from','$to','$qty','$codeid','$uid')";
$run=mysql_query($insert,$con);
if(!$run) die("error".mysql_error());
else return 'success';
?>

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.

passing params through ajax to php

I know this is a very basic question, but i couldnt figure how to fix the code even after crawling the web for past 1 hour.
I have an unordered list containing the information about the categories in the database, with cat_id as primary key. and a subject table with cat_id as its foreign key, so i want to access the subjects table through ajax request for given category ID. below is the code i used to generate categories. Where i am stuck is, i dont know which DOM element to fetch in order to send the unique id in the url parameter ..
thanks ..
<ul id="search_form">
<?php
$cat = Category::find_all();
foreach($cat as $category) {
echo '<li id="';
echo $category->cat_id;
echo '"><a href="subject.php?id=';
echo $category->cat_id;
echo'">';
echo $category->category;
echo '</a></li>';
}
?>
</ul>
<div id="results">
<!-- ajax contents goes here -->
</div>
the ajax file is
window.onload = init;
function init() {
if (ajax) {
if (document.getElementById('results')) {
document.getElementById('search_form').onclick = function() {
ajax.open('get', 'subject.php?id='+id ); // subject.php?id=
// how will i pass the variable
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
}
}
function handleResponse(ajax) {
if (ajax.readyState == 4) {
if ((ajax.status == 200) || (ajax.status == 304) ) {
var results = document.getElementById('results');
results.innerHTML = ajax.responseText;
results.style.display = 'block';
}
}
}
and the subject.php
<?php
//include("tpl/header.php");
include("includes/initialize.php");
?>
<h2></h2>
<?php
if (isset($_GET['id'])) {
$id= mysql_real_escape_string($_GET['id']);
$subject = Subject::find_subject_for_category($id);
foreach($subject as $subj) {
echo $subj->subject_title;
}
} else {
echo "No ID Provided";
}
?>
I have used Jquery to do these kind of things and it works fine for me.
$.ajax({
type: GET,
url: "subject.php",
data: {id: $('#search_form :selected').val()},
success: function(result){
// callback function
}
});

Categories