Get $_POST from PHP to Javascript and pass it to another php - javascript

I build a search feature with infinite scroll. How do i get search string from search page to my scroll page for query database.
PHP :
search.php
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style/css/scroll.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<link href="css/search.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="search">
<form action="search" method="post">
<input type="text" name="search" id="search" autocomplete="off">
<button type="submit" class="btn btn-primary">Search</button>
</form>
</div>
<img id='loading' src='img/loading.gif'>
<div id="demoajax" cellspacing="0">
</div>
</body>
<script type="text/javascript" src="js/infinitescroll/search.js"></script>
scroll.php
<?php
include('db.php');
$searchstring = $_POST['search'];
if(isset($_REQUEST['actionfunction']) && $_REQUEST['actionfunction']!=''){
$actionfunction = $_REQUEST['actionfunction'];
call_user_func($actionfunction,$_REQUEST,$con,$limit);
}
function showData($data,$con,$limit){
$page = $data['page'];
if($page==1){
$start = 0;
}
else{
$start = ($page-1)*$limit;
}
$sql = "SELECT fm_product.p_name, fm_product.p_descp, fm_product.p_id, fm_product.p_price, fm_product.p_discount, fm_product.p_img, fm_member.member_display_name, fm_product.p_member_id, fm_package.package_name, fm_package.package_id FROM fm_member LEFT JOIN fm_product ON fm_member.member_id = fm_product.p_member_id LEFT JOIN fm_package ON fm_member.package_id = fm_package.package_id order by p_created_date desc limit $start,$limit";
$str='';
$data = $con->query($sql);
if($data!=null && $data->num_rows>0) {
while( $row = $data->fetch_array(MYSQLI_ASSOC)){
if($row['package_id']=='1'){
$package = "No Package";
} else {
$package = "<form class='form-item'><input name='product_code' type='hidden' value='".$row['p_id']."'><button type='submit'>Add to Cart</button></input></form>";
}
$id = $row['p_id'];
$str.="<div style=align: center class='data-container'><a href=item?id = $id><img src=upload/".$row['p_img']." width=300px style=max-width:100%; height: auto; vertical-align: middle></a><p>By ".$row['member_display_name']."</p><p>Product Name : ".$row['p_name']."</p><p>Price : ".$row['p_price']."</p><p>Discount : ".$row['p_discount']."</p><p>Description : ".$row['p_descp']."</p><p>Package ".$_POST['search']." : ".$row['package_name']."</p><p>".$package."</p></div>";
}
$str.="<input type='hidden' class='nextpage' value='".($page+1)."'><input type='hidden' class='isload' value='true'>";
} else {
$str .= "<input type='hidden' class='isload' value='false'><p>Finished</p>";
}
echo $str;
}
?>
Javascript :
search.js
var ajax_arry=[];
var ajax_index =0;
var sctp = 100;
$(function(){
$('#loading').show();
$.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page=1",
cache: false,
success: function(response){
$('#loading').hide();
$('#demoajax').html(response);
}
});
$(window).scroll(function(){
var height = $('#demoajax').height();
var scroll_top = $(this).scrollTop();
if(ajax_arry.length>0){
$('#loading').hide();
for(var i=0;i<ajax_arry.length;i++){
ajax_arry[i].abort();
}
}
var page = $('#demoajax').find('.nextpage').val();
var isload = $('#demoajax').find('.isload').val();
if ((($(window).scrollTop()+document.body.clientHeight)==$(window).height()) && isload=='true'){
$('#loading').show();
var ajaxreq = $.ajax({
url:"scroll.php",
type:"POST",
data:"actionfunction=showData&page="+page,
cache: false,
success: function(response){
$('#demoajax').find('.nextpage').remove();
$('#demoajax').find('.isload').remove();
$('#loading').hide();
$('#demoajax').append(response);
}
});
ajax_arry[ajax_index++]= ajaxreq;
}
return false;
if($(window).scrollTop() == $(window).height()) {
alert("bottom!");
}
});
});
I want to get $_POST['search'] from search.php to scroll.php for replace it into WHERE on this query like.
$sql = "SELECT ... FROM ... LEFT JOIN ... ON ... LEFT JOIN ... ON ... WHERE p_name LIKE '%$_POST['search']' ORDER BY ... LIMIT ..."
Appreciated.

<form action="search" method="post">
This redirects to /search page, which you don't have. You have /search.php and /scroll.php. I think you should just put scroll.php as the action, and you'd get your result.
<form action="scroll.php" method="post">
EDIT:
I seem to have misunderstood the code. scroll.php is an API endpoint in this. Then the action remains search.php, BUT, in order to have the submitted values, you can kill 2 birds with 1 stone.
Update the form HTML (you don't need action, you don't need the form either, but let's keep it):
<form action="" method="post">
<input type="text" name="search" id="search" autocomplete="off">
<button type="button" id="do_search" class="btn btn-primary">Search</button>
</form>
In your JS, make the function get triggered by the search:
jQuery(document).ready(function($) {
$("#do_search").on("click", function() {
var searchTerm = $("#search").val();
//this is where you do the AJAX stuff. You can use searchTerm variable.
});
});

Related

jQuery on("click",....) function doesn't execute for my dynamically created div

I'm creating a to-do list and I want to be able to click on a div with a "to-do" and directly delete it from the database. This is my main page.
<div class="hoofder">
<h2>Voegtoe:</h2>
</div>
<?php include('connect.php'); ?>
<form method="post" action="add.php">
<div class="input">
<label>Taak</label>
<input type="text" name="taak">
</div>
<div class="input">
<button type="submit" name="add_todo class="btn">Register</button>
<?php include('getthings.php'); ?>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready ( function () {
alert("1");
$(document).on("click", ".lijst", function () {
alert("2.");
var del_id = $(this).attr('id').substring(1);
alert(del_id);
var $ele = $(this).parent();
$.ajax({
type:'POST',
url:'delete.php',
data:{del_id:del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row");
}
}
});
});
});
alert("end");
</script>
</form>
</body>
</html>
delete.php:
<?php
include 'connect.php';
include 'add.php';
$delete_this = $_POST['del_id'];
$qry = "DELETE FROM tedoen WHERE id ='$delete_this'";
$result = mysqli_query($conn, $qry);
?>
When I load the page the "alert(del_id);" comes back as undefined.
This is a problem as I need it not to be undefined ofcourse. Do you have any idea why?

How to pass many ajax results to different input values?

My ajax return results are four values.I want assign these values to four input value.Here my ajax code:
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: {cabinetNum:id},
success:function (res)
{
}
});
modify_cbndtb.php code:
if(isset($_POST['cabinetNum']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
}
My html code:
<div id="content" class="content">
1U:<input type="text" id="1U" value="">11U:<input type="text" id="11U" value=""><br />
2U:<input type="text" id="2U" value="">12U:<input type="text" id="12U" value=""><br />
</div>
1U.value should be num1. 2U.value should be num2. 3U.value should be num3. 4U.value should be num4. But I don't know how to realize. Who can help me?
I think you can try this
modify_cbndtb.php
if(isset($_POST['cabinetNum']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
$arr = $sel->fetch(PDO::FETCH_ASSOC);
$data = json_encode($arr);
echo $data;
}
and AJAX
client file
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: {cabinetNum:id},
success:function (data) {
$('#1U').val(data[0].num1);
$('#11U').val(data[0].num2);
$('#2U').val(data[0].num3);
$('#12U').val(data[0].num4);
}
});
I hope it help you
Try this
modify_cbndtb.php
<?php
if(isset($_POST['action']))
{
$q=$_POST["cabinetNum"];
$sql="select num1,num2,num3,num4 from hpc WHERE sysid= '".$q."';";
$sel = $conn->query($sql);
while($row = $sel->fetch_assoc()){
echo $row['num1'].",".$row['num2'].",".$row['num3'].",".$row['num4'];
}
}
?>
your form
<script type="text/javascript" src="testing/jquery-3.2.1.js"></script>
<form id="form">
<input type="submit" name="submit" id="submit">
<input type="hidden" id="cabinetNum" name="cabinetNum" value="1">
</form>
<div id="content" class="content">
1U:<input type="text" id="1U" value="">3U:<input type="text" id="3U" value=""><br />
2U:<input type="text" id="2U" value="">4U:<input type="text" id="4U" value=""><br />
</div>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#submit',function(e){
e.preventDefault();
var dataen = $("#form").serialize() + "&action";
$.ajax({
type:"POST",
url:"modify_cbndtb.php",
data: dataen,
success:function (data) {
$(function(){
var valData = data;
var valNew=valData.split(',');
for (i = 0; i < valNew.length; i++) {
valNew[i] = valNew[i];
$('#'+(i + 1)+'U').val(valNew[i]);
}
});
}
});
});
});
</script>

JQUERY change value of an variable input field

i want to change the value of my input field with jquery. The problem is, that the input field has a variable and i don't know how describe this in jquery.
Without the variable all the code works, but this doesn't help because i use the form different times on my page.
function doSth(click) {
var value = ($(click).val());
var name_ekt = $('[name="name[]"]').map(function() {
return $(this).val();
}).get();
var dat = $("#dat").val();
$.ajax({
type: "post",
url: "get_test.php",
data: {
name: name,
dat: dat,
value: value
},
cache: false,
success: function(value) {
$("#output").html(value);
}
});
event.preventDefault();
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/style.css">
<script src="../js/jquery-3.2.1.js"></script>
<script src="../js/jquery-ui.js"></script>
<title>Modul </title>
</head>
<body>
<br>
<input type="text" id="dat" value="2017-06-30">
<br>
<br>
<div>
<?php for ($i = 1; $i <= 6; $i++) { ?>
<form>
<?php for ($x=0; $x<2; $x++) { ?>
<input type='text' name='name[]' id="name[]"><br>
<?php } ?>
<button type='submit' id='save' value='<?php echo $i; ?>' onclick="doSth(this);">save</button>
<br><br>
</form>
<?php } ?>
</div>
<div id='output'></div>
</body>
</html>
<?php
if ($row = (($value*2)-1)) {
$sql = "INSERT INTO test (dat, name)
VALUES ('$dat', '$name[$row]')";
$conn->query($sql);
if(($conn->affected_rows)>0) {
echo "<script>
$(document).ready(function(){
$('#name[$row]').prop('disabled', true).css('background-color','#C1FFC1');
$('#dat').prop('disabled', true).css('background-color','#C1FFC1');
});
</script>";
echo $row;
}
}
?>
Edit your code to this,
function doSth(click) {
var value = ($(click).val());
var name_ekt = $("#name[]").map(function() {
return $(this).val();
}).get();
var dat = $("#dat").val();

PHP messages aren't being written to the log file - tutsplus.com tutorial

tutsplus, there you will find a tutorial which guides you through the steps on how to create a simple web chat. I tried to follow all that was said, yet I noticed a problem when testing. It seems that the usermsg is not being posted to the log.html file.
here is the index.php, which in this case is named chat.php:
<?php
function loginForm() {
echo '
<div id="loginform">
<form action="chat.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="enter" id="enter" value="enter">
</form>
</div>
';
}
if(isset($_POST['enter'])) {
if($_POST['name'] != "") {
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}else {
echo '<span class="error">Please type in a name</span>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Chat Service</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" title="style" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<?php
if(!isset($_SESSION['name'])) {
loginForm();
}else{
?>
<div id="wrapper">
<div id="menu">
<div class="welcome">Welcome, <?php echo $_SESSION["name"]; ?></div>
<div class="logout">Exit Chat</div>
<div style="clear:both;"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0) {
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input type="text" name="usermsg" id="usermsg" size="63">
<input type="submit" name="submitmsg" id="submitmsg" value="Send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
//jQuery Document
$(document).ready(function() {
$("#exit").click(function() {
var exit = confirm("Are you sure you want to logout?");
if(exit == true) {
window.location = 'chat.php?logout=true';
}
});
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
console.log(clientmsg);
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url:"log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chatbox").animate({scrollTop: newscrollHeight}, 'normal');
}
}
});
}
setInterval(loadLog, 2500);
});
</script>
<?php
}
if(isset($_GET['logout'])) {
$fp = fopen("log.html", 'a');
fwrite($fp, '<div class="msgln"><i>User '.$_SESSION['name'].' has left the chat session.</i><br></div>');
fclose($fp);
session_destroy();
header("Location: chat.php");
}
?>
</body>
</html>
Here is the post.php:
<?php
session_start();
if(isset($_SESSION['name'])) {
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").")<b>".$_SESSION['name']."</b>:".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
I am using MAMP, and the files are located in the htdocs folder, so that's not the problem.
Thanks in advance for any help you can give me, and let me know if you need more info.
You should call session_start() in index.php.
(from Marc B in the comments)

ajax code200 error can't connect to the url

I am using ajax to run a test id, but it does not work with code: 200 error.
And since ajax is not returning a value, it keeps getting error and prints "failed"
The id of add_user.html is checked in real time through the ajax of id_check.js.
However, memid_check.php, which sends data from id_check.js, does not seem to run.
to confirm
memid_check.php
echo "<script> alert('test!!!'); </script>";
.....
But did not run.
All files are in one folder, so the path seems to be fine
id_check.js
$(function(){
var id = $('.id_tbox');
var pwd =$('.pwd_tbox');
var name =$('.name_tbox');
var email =$('.email_tbox');
var idCheck = $('.idCheck');
$(".memcheck_button").click(function(){
console.log(id.val());
$.ajax({
type: 'post',
dataType: 'json',
url: "memid_check.php",
data:{id:id.val()},
success: function(json){
if(json.res == 'good'){
console.log(json.res);
alert("사용가능한 아이디");
idCheck.val('1');
}
else{
alert("다른 아이디 입력");
id.focus();
}
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
console.log("failed");
}
});
});
});
memid_check.php
<?php
echo "<script> alert('test!!!'); </script>";
include "db_c.php";
$id = $_POST['id'];
$sql = "SELECT * FROM add_user WHERE id = '{$id}'";
$res = $database -> query($sql);
if( res->num_rows >= 1){
echo json_encode(array('res'=>'bad'));
}
else{
echo json_encode(array('res'=>'good'));
}
?>
add_user.html
<?php
include "database.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=medium-dpi">
<link rel="stylesheet" href="add_user_style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/default.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cinzel|Permanent+Marker|Rajdhani&display=swap" rel="stylesheet">
<script type="text/javascript" src="id_check.js"></script>
</head>
<body>
<div class="aus_portrait"></div>
<div class ="aus_form" align ="center">
<div class="aus_box">Sign Up</div>
<form action="loginP.php" method="post">
<p class = "id">ID</p><input type="text" name="id" class="id_tbox">
<p class = "pwd">PASSWORD</p><input type="text" name="pwd" class="pwd_tbox">
<p class = "name">MAIL</p><input type="text" name="email" class="email_tbox">
<p class = "email">NAME</p><input type="text" name="name" class="name_tbox">
<input type="submit" class="sub_button" value="Submit">
<input type="button" class="exit_button" value="Cancel">
<input type="hidden" name="idCheck" class="idCheck">
<div class="memcheck_button">중복확인</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() { $(".exit_button").on("click", function(){ location.href="login.html"});}); </script>

Categories