简体   繁体   English

将变量从JS传递到PHP

[英]Passing variables from JS to PHP

I'm trying to pass a variable from JS to PHP but so far no luck. 我正在尝试将变量从JS传递给PHP,但到目前为止还没有运气。 I've been searching here for solution, but it seems that nothing helps.. 我一直在这里寻找解决方案,但似乎没有任何帮助。

Ok, I have php file with pagination: 好的,我有分页的php文件:

$pagination .= '<li><a href="#" class="paginate_click" id="'.$i.'-page">'.$i.'</a></li>';

Paginate_click launches js function: Paginate_click启动js函数:

$(".paginate_click").click(function (e) {

    $("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');

    var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
    var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need 

    $('.paginate_click').removeClass('active'); //remove any active class

    //post page number and load returned data into result element
    //notice (page_num-1), subtract 1 to get actual starting point
    $("#results").load("views/fetch_articles.php", {'page':(page_num-1)}, function(){

    $(window).scrollTop(0);

    });

    $.post('views/articles_list.php', {'page':(page_num)});

    $(this).addClass('active'); //add active class to currently clicked element (style purpose)

    return false; //prevent going to herf link

}); 

In php file I need information which page of pagination I'm currently on so I want to retrieve page_num value back to my php. 在php文件中,我需要信息我当前在哪个页面上,因此我想将page_num值检索回我的php。 I tried this: 我尝试了这个:

$.post('views/articles_list.php', {'page':(page_num)});

And in php: 并在php中:

$page_number = $_POST["page"];

I tried also many other options, but nothing helps. 我也尝试了许多其他选择,但没有任何帮助。 I thought it will be easier :/ 我以为会更容易:/

As you probably noticed there's another php file (fetch_articles.php) and in this case $_POST["page"]; 您可能已经注意到,还有另一个php文件(fetch_articles.php),在这种情况下为$ _POST [“ page”]; works. 作品。 But for articles_list.php I can't use load function. 但是对于articles_list.php,我无法使用加载功能。

EDIT: What I want and entire code. 编辑:我想要什么和整个代码。

I have simple and nice pagination. 我的分页简单明了。 The only problem is that it has no option for prev/next and it shows all the buttons. 唯一的问题是,它没有上一个/下一个选项,并且显示所有按钮。 It's a problem when you have a lot of pages. 当您有很多页面时,这是一个问题。 So my idea is to shrink it down and instead of heaving 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,15,16,17,18,19 and so on I want this: prev,1,2,3...67,68,next. 所以我的想法是缩小它,而不是留下1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,15,16,17,18, 19,依此类推:prev,1,2,3 ... 67,68,next。 To do this I need to pass to my php file an information about actual page . 为此,我需要将有关实际页面的信息传递给我的php文件 With this variable I can calculate everything and organize my pagination with for/if/else statements. 使用此变量,我可以计算所有内容并使用for / if / else语句组织分页。

The code. 编码。

articles_list.php: article_list.php:

<?php
include("../config/connection.php");
include('../config/css.php');

$results = mysqli_query($dbc_connection,"SELECT COUNT(*) FROM articles");
$get_total_rows = mysqli_fetch_array($results); //total records

//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);     

//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';

for($i = 1; $i<=$pages; $i++)
{
    $pagination .= '<li><a href="#" class="paginate_click" id="'.$i.'-page">'.$i.'</a></li>';
}
$pagination .= '<li><a href="#" class="paginate_click" id="'.$page_number.'-page">'.$page_number.'</a></li>'; // only to check if variable is passed
$pagination .= '</ul>';
}

?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="js/pagination.js"></script>
</head>
<body>
<?php $page_number = $_POST["page"];
echo $page_number; // only to check if variable is passed ?> 
<div id="results"></div>
<?php echo $pagination; ?>
</body>
</html> 

pagination.js: pagination.js:

$(document).ready(function() {
$("#results").load("views/fetch_articles.php", {'page':0}, function() {$("#1-page").addClass('active');});  //initial page number to load

$(".paginate_click").click(function (e) {

    $("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');

    var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
    var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need 

    $('.paginate_click').removeClass('active'); //remove any active class

    //post page number and load returned data into result element
    //notice (page_num-1), subtract 1 to get actual starting point
    $("#results").load("views/fetch_articles.php", {'page':(page_num-1)}, function(){

    $(window).scrollTop(0);

    });

    $.post('views/articles_list.php', {page:page_num}, function(data){});

    $(this).addClass('active'); //add active class to currently clicked element (style purpose)

    return false; //prevent going to herf link

}); 
});

fetch_articles.php: fetch_articles.php:

<?php

include("../config/connection.php"); //include config file

//sanitize post value
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);

//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}

//get current starting point of records
$position = ($page_number * $item_per_page);

//Limit our results within a specified range. 
$result = mysqli_query($dbc_connection,"SELECT * FROM articles ORDER BY id DESC LIMIT $position, $item_per_page");

//output results from database

while($row = mysqli_fetch_array($result))
{
?>
<h2><?php echo $row['title']; ?></h2>
<p><i><?php echo 'By '.$row['author']; ?></i></p>
<p><?php echo $row['header']; ?></p>
<a href="http://localhost/site/articles/<?php echo $row['slug'] ?>">Read</a><br>
<hr>
<?php
}

?>

尝试删除page_num周围的括号:

$.post('views/articles_list.php', {'page':page_num});

You didn't said in which one of the requests you can't get the value you're trying to pass. 您没有说在哪个请求中您无法获取要传递的值。 So, I'm guessing it is in the first one: 所以,我猜这是第一个:

$("#results").load(...);

The problem here is that you're using the .load() method, which is equivalent to .get() . 这里的问题是您正在使用.load()方法,该方法等效于.get() So, when you try, in the PHP file to get $_POST ["page"], it will not be there, because it is actually in the $_GET array. 因此,当您尝试在PHP文件中获取$ _POST [“ page”]时,该文件将不存在,因为它实际上位于$ _GET数组中。

I may be missing something here, but couldn't you just append a query string to the url manually? 我可能在这里丢失了一些内容,但是您是否不能手动将查询字符串附加到url?

$.post('views/articles_list.php?pn=' + page_num);

Then in your fetch_articles.php you just pull it off with 然后在您的fetch_articles.php中使用

$page_number = $_GET["pn"];

If that fails you can always use a cookie. 如果失败,您可以随时使用cookie。

Instead of 代替

$.post('views/articles_list.php', {'page':(page_num)});

try 尝试

$.post('views/articles_list.php', {page:page_num}, function(data){ 
   console.log(data);
},'json');

And also double check if 'views/articles_list.php' is the correct path. 还要仔细检查“ views / articles_list.php”是否正确。 If you were using Chrome, kindly read the parsing via right click -> inspect elements -> Network. 如果您使用的是Chrome,请通过右键单击->检查元素->网络来阅读解析。

Addition(After posted your edit code) :- Please remove the Doctype and HTML and leave something like this. 加法(在发布您的编辑代码之后):-请删除Doctype和HTML并留下类似的内容。

<?php
include("../config/connection.php");
include('../config/css.php');

$results = mysqli_query($dbc_connection,"SELECT COUNT(*) FROM articles");
$get_total_rows = mysqli_fetch_array($results); //total records

//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);     

//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';

for($i = 1; $i<=$pages; $i++)
{
    $pagination .= '<li><a href="#" class="paginate_click" id="'.$i.'-page">'.$i.'</a></li>';
}
$pagination .= '<li><a href="#" class="paginate_click" id="'.$page_number.'-page">'.$page_number.'</a></li>'; // only to check if variable is passed
$pagination .= '</ul>';
}

//Assuming you're doing ajax here. so either pagination or page number posting back? if both try below.

$page_number = $_POST["page"];

echo json_encode(array("pagination"=>$pagination,"pageNumber"=>$page_number));

?>

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM