I'm developing a kind of question search engine based on Course wise, Subject wise by entering the keyword or question.
Here I am querying the database based on search term against 3 tables namely table_one, table_two, and table_three. Code as follows
<?php
if(isset($_GET['submit']))
{
$query = $_GET['query'];
$query = htmlspecialchars($query);
$query = mysqli_escape_string($link,$query);
$searchTerms = explode(' ', $query);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "question LIKE '%$term%'";
}
}
$subject_id = $_GET['subject'];
$course_id = $_GET['course'];
$min_length = 1;
if(strlen($query) >= $min_length)
{
$res = "SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_one
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_two
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_three
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')";
$raw_results = mysqli_query($link,$res) or die (mysqli_error());
if(mysqli_num_rows($raw_results) > 0)
{
echo "<h3 style='text-align:center;color:#3366CC'><span style='color:#000000'>Search Results For : </span> $query </h3>";
while($results = mysqli_fetch_array($raw_results))
{
echo "<div class='content'>";
echo"<h4 id=".$results['id'].">" .preg_replace("/".preg_quote($query, "/")."/i", "<span class=\"highlight\">$query</span>", $results['question']) . "</h4>";
echo"<p id=".$results['id']."><span style='padding-left:20px'>option A : " .$results['option_a']."</span> <br><span style='padding-left:20px'> option B : ".$results['option_b']."</span><br/><span style='padding-left:20px'>option C : ".$results['option_c'].
"</span><br><span style='padding-left:20px'>option D : ".$results['option_d']."</span><br><span style='padding-left:20px'> option E : ".$results['option_e']."</span><br><span style='color:#253E66;font-weight:bold;padding-left:20px'>Correct Ans : ".$results['correct_ans'].
"</span><br><span style='padding-left:20px'>Question Year : ".$results['question_year']."</span><br><span style='padding-left:20px'>Contributor : ".$results['contributor']."</span><br />
<a onclick=addQuestion('".$results['id']."') href='#'><span class='button'>Add to Question Bank</span></a></p>";
echo "</div>";
}
}
else{
echo "<span style='height:21px;syle=background-color: #F1F0FF;font-size:25px;color:#CC0000'>Your search - $query - did not match any queries.</span> ";
}
}
}
?>
I'm Calling the following addQuestion() function when i click the Add to Question Bank link.
<script>
function addQuestion(val)
{
var conf=confirm("Are you sure you want to add this question to Question Bank")
if(conf){
//Here I Want some code to update my database.
}
}
</script>
The script above displaying confirmation box when i click the button,
My Question is,
After confirmation I want to insert my question into the new table in the database and display message like "Question added" in front of the question permanently as i know i can't write PHP inside Jquery function Any help may appreciated.
You can achieve this by including the ajax.
put the ajax code which may looks like the following:
if(conf){
$.ajax({
type: "POST",
url: "$$phpfilepath",
data: {param:'$$value'},
success: function(data) {
// do the message display code
}
});
}
Don't forget to include the jquery cdn link in the head tag of the html page.
you need to send an ajax request.
you need to send it either by a post or get method to a php script that will return json so you can be updated on the page with results.
the answer above has an example ajax script sent with a post method:
data needs to be sielized if you are submitting it via form or an array.
this should help you
http://www.w3schools.com/php/php_ajax_database.asp
https://api.jquery.com/serialize/
Onclick - You need to do that with ajax. So basically, you need PHP plus javascript involved. You can use Jquery of similar JS library for easy ajax support.
Just and example with jquery library version 1.11.2 how to include:
<head>
<script src="jquery-1.11.2.min.js"></script>
</head>
For example, if this is your input field you want to save and button for submitting:
<input id="title" name="title" />
<input type="submit" value="Save">
Change it to button and give it javascript save() function (can be any name you give).
<input type="button" onclick="save($('#title').val());" value="Save">
In this example, I added 1 param to that save function, which is supposed to grab a value from html input filed with id "title".
On this page, there that html is, you need to include mentioned jquery(or similar) library and also include piece of javascript function for generating ajax request, which is named "save" here.
If you included jquery library, you must call javascript function for saving your data before your tag:
<script type"text/javascript">
function save(){
$.ajax({
type: "POST",
url: "yourpath/yourfile.php",
data: {title: title},
success: function(data) {
alert("Ajax save executed!");
}
});
}
</script>
When javascript function you named save() will execute, it will send POST request to yourpath/yourfile.php
There, you can easily get your POST data by in yourpath/yourfile.php:
if(isset($_POST['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}
If you want to send it with GET, you easily replace POST with GET:
function save(){
$.ajax({
type: "GET",
and also in .php file you write:
if(isset($_GET['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}
Related
What I am trying to accomplish is to pass the correct value from php to a jquery function. What is the proper way to get that value to my jquery function so that I can use it.
Here is an example of how I tried to pass the php variable to the javascript function. Of course that does not give the desired effect.
index.php
User starts typing in username and live search displays matching usernames in dropdown
<input type="text" class="form-control" id="keywords" placeholder="Search..." autocomplete="off">
getUsername.php
Username gathered from database and displayed to user in dropdown. (when user clicks on a username it will send the username value to jquery function, then queries database and displays the specified info to user). Obviously sending a php variable directly through a jquery function is not going to work, but what other workaround is there in jquery to grab that $row['Username'] value to pass to the jquery function (searchFilterUsername). EDIT: Actually, sending the value through the jquery function is exactly what was needed. The Selected answer is the correct way to send the values through the jquery function
foreach($results as $row){
<td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername();">
}
functions.js
Need to be able to get that specific username to this jquery function, so that it can be sent to the database function to display proper selection back to user
function searchFilterUsername(page_num, userName) { //Username needs to be sent to this function somehow, so that I can store the proper value inside the variable $keywords
page_num = page_num?page_num:0;
var keywords = $('.searchTerm').data("username-id"); //Adding this will only allow the first item in the dropdown to be grabbed for the query
var keywords = userName;
alert(keywords);
$.ajax({
type: 'POST',
url: 'getData.php',
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.screenLoader').show();
},
success: function (html) {
$('#displayPage').html(html);
}
});
}
Now if I remove the value from the onclick="searchFilterUsername()" then I am able to grab the first value, but of course that will not work since the data is dynamic. It is a live search, (user types username into input box and dropdown appears with queried usernames) and when the user clicks on the username, it displays values in display div based off of that username selection. The live search ties into the pagination class which allows user to search through returned values. Thanks.
getData.php
getData.php grabs those $_POST values and sends them to the database query and then the searchFilter function is sent to the pagination class
if(isset($_POST['keywords']) && !empty($_POST['keywords']) && $_POST['keywords'] !== 'null'){
$keywords = $filter->filter($_POST['keywords']);
$usersSQL .= "AND users.userName LIKE :keywords ";
}else{
$keywords = '';
$usersSQL .= "AND users.userName LIKE :keywords ";
}
$query= "SELECT * FROM users WHERE stuff = :stuff $usersSQL";
class.pagination.php
$_POST Values sent to this pagination class to create pagination links
$paginationConfig = array('link_func' => 'searchFilterUsername');
I would suggest you to pass the values via some data-* attribute of each td.
foreach($results as $row){
echo '<td class="searchTerm" data-pagenum="'.$row['something'].'" data-username="'.$row['userName'].'">blah blah blah</td>';
}
And use delegation for those dynamic elements.
$(document).on("click", ".searchTerm", function(){
// Get the values via the data-* attributes
var pagenum = $(this).data("pagenum");
var keywords = $(this).data("username");
alert(keywords);
$.ajax({
type: 'POST',
url: 'getData.php',
data:'page='+pagenum+'&keywords='+keywords,
beforeSend: function () {
$('.screenLoader').show();
},
success: function (html) {
$('#displayPage').html(html);
}
});
});
Pass userName with onclick event called in td.
foreach($results as $row){
<td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername(null,\''.$row['userName'].'\')">
}
As searchFilterUsername has first parameter is page_num and second is userName.
Hope this will be useful
All Code is good but you need to echo this line in getUsername.php like this
foreach($results as $row){
echo '<td class="searchTerm" data-username-id="'.$row['userName'].'" onclick="searchFilterUsername();">';
}
I am trying to pass the link's text as a value to the next page so I can use it to search the database for the item and retrieve the information related to the value .I have tried using the POST method but regardless the information is not passed. This is the code I tried .
<form action="DetailedMenu.php" method = "POST" action = "<?php $_PHP_SELF ?>">
<?php
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
echo str_repeat(' ', 4); ?>
<a href="DetailedMenu.php" ><?php echo $array[$i]["Food_Name"];?></a>
<?php echo " " .str_repeat('. ', 25). "€".$array[$i]["Food_Price"]."<br>"; ?>
<input type="hidden" name="name" value="<?php echo $array[$i]["Food_Name"];?>">
<?php
}
}
?>
</form>
You don't need the form.
The easiest way to do what you're trying to do....
In addition to including the text in the content of the link, include it as a query string parameter.
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
I would actually recommend something more like this. I obviously don't know the names of your fields, so I've just taken a guess...
for($i=0;$i<sizeof($array);$i++) {
if($array[$i]["Food_Category"]=="starters") {
...
<?php echo $array[$i]["Food_Name"];?>
...
}
}
You'll be able to access "FoodID" as a parameter within your PHP, just as you would if it had been submitted from a form.
You may be looking for AJAX. AJAX lets you send the form data to a back end PHP file (that can then insert data into a DB, and/or get data from the DB) without refreshing the page.
In fact, when you are using AJAX you don't even need to use a <form> structure -- simple DIVs work just fine. Then you don't need to use event.preventDefault() to suppress the built-in form refresh.
Just build a structure inside a DIV (input fields, labels, etc) and when the user is ready to submit, they can click an ordinary button:
<button id="btnSubmit">Submit</button>
jQuery:
$('#btnSubmit').click(function(){
var fn = $('#firstname').val();
var ln = $('#lastname').val();
$.ajax({
type: 'post',
url: 'ajax_receiver.php',
data: 'fn=' +fn+ '&ln=' +ln,
success: function(d){
if (d.length) alert(d);
}
});
});
ajax_receiver.php:
<?php
$fn = $_POST['fn'];
$ln = $_POST['ln'];
//Do your stuff
Check out this post and especially its examples. Copy them onto your own system and see how they work. It's pretty simple.
I have a problem with updating the data I display from my db. Initially, when the page opens I display the date corresponding to the current date but then the user can change the date by entering it in a text box and when he clicks update all the data displayed should be deleted and the data corresponding to the new date should be displayed. Right now I have a javascript function which deleted all the data in the div when the button is clicked. The div holds the data I want to change. But I don't know how to add new data into the div. I tried to add php code to look up the database for the data in the javascript function but I don't know how to add it to the text box.
function changedate()
{
document.getElementById("label1").innerText=document.getElementById("datepicker").valu e;
document.getElementById("selecteddate").innerText=document.getElementById("datepicker" ).value;
document.getElementById("teammembers").innerHTML = "";//empties the div(teammembers)
<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
}
}
?>
}
You can use a combination of jQuery and AJAX to do this. Much simpler than it sounds. To see that this is the right answer for you, just view this example.
In the below example, there are two .PHP files: test86a.php and test86b.php.
The first file, 86A, has a simple selection (dropdown) box and some jQuery code that watches for that selection box to change. To trigger the jQuery code, you could use the jQuery .blur() function to watch for the user to leave the date field, or you could use the jQueryUI API:
$('#date_start').datepicker({
onSelect: function(dateText, instance) {
// Split date_finish into 3 input fields
var arrSplit = dateText.split("-");
$('#date_start-y').val(arrSplit[0]);
$('#date_start-m').val(arrSplit[1]);
$('#date_start-d').val(arrSplit[2]);
// Populate date_start field (adds 14 days and plunks result in date_finish field)
var nextDayDate = $('#date_start').datepicker('getDate', '+14d');
nextDayDate.setDate(nextDayDate.getDate() + 14);
$('#date_finish').datepicker('setDate', nextDayDate);
splitDateStart($("#date_finish").val());
},
onClose: function() {
//$("#date_finish").datepicker("show");
}
});
At any rate, when the jQuery is triggered, an AJAX request is sent to the second file, 86B. This file automatically looks stuff up from the database, gets the answers, creates some formatted HTML content, and echo's it back to the first file. This is all happening through Javascript, initiated on the browser - just like you want.
These two files are an independent, fully working example. Just replace the MYSQL logins and content with your own fieldnames, etc and watch the magic happen.
TEST86A.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//alert('Document is ready');
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "test86b.php", // "another_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#LaDIV').html(whatigot);
$('#theButton').click(function() {
alert('You clicked the button');
});
} //END success fn
}); //END $.ajax
}); //END dropdown change event
}); //END document.ready
</script>
</head>
<body>
<select name="students" id="stSelect">
<option value="">Please Select</option>
<option value="John">John Doe</option>
<option value="Mike">Mike Williams</option>
<option value="Chris">Chris Edwards</option>
</select>
<div id="LaDIV"></div>
</body>
</html>
TEST86B.PHP
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
$server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
$login = 'abcd1234';
$pword = 'verySecret';
$dbname = 'abcd1234_mydb';
mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
mysql_select_db($dbname) or die($connect_error);
//Get value posted in by ajax
$selStudent = $_POST['theOption'];
//die('You sent: ' . $selStudent);
//Run DB query
$query = "SELECT `user_id`, `first_name`, `last_name` FROM `users` WHERE `first_name` = '$selStudent' AND `user_type` = 'staff'";
$result = mysql_query($query) or die('Fn test86.php ERROR: ' . mysql_error());
$num_rows_returned = mysql_num_rows($result);
//die('Query returned ' . $num_rows_returned . ' rows.');
//Prepare response html markup
$r = '
<h1>Found in Database:</h1>
<ul style="list-style-type:disc;">
';
//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
if ($num_rows_returned > 0) {
while ($row = mysql_fetch_assoc($result)) {
$r = $r . '<li> ' . $row['first_name'] . ' ' . $row['last_name'] . ' -- UserID [' .$row['user_id']. ']</li>';
}
} else {
$r = '<p>No student by that name on staff</p>';
}
//Add this extra button for fun
$r = $r . '</ul><button id="theButton">Click Me</button>';
//The response echoed below will be inserted into the
echo $r;
Here is a more simple AJAX example and yet another example for you to check out.
In all examples, note how the user supplies the HTML content (whether by typing something or selecting a new date value or choosing a dropdown selection). The user-supplied data is:
1) GRABBED via jQuery: var sel_stud = $('#stSelect').val();
2) then SENT via AJAX to the second script. (The $.ajax({}) stuff)
The second script uses the values it receives to look up the answer, then ECHOES that answer back to the first script: echo $r;
The first script RECEIVES the answer in the AJAX success function, and then (still inside the success function) INJECTS the answer onto the page: $('#LaDIV').html(whatigot);
Please experiment with these simple examples -- the first (simpler) linked example doesn't require a database lookup, so it should run with no changes.
You want to output a literal JS statement with whatever you get back from php, basically:
document.getElementById("teammembers").innerHTML = // notice no erasing, we just
// overwrite it directly with the result
"<?php
$con=mysqli_connect("localhost","*****","*****","*****");
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
if(trim($user_data['email'])!=trim($row['email']))
{
$email_users = $row['email'];
//I want to first show this email but I don't know how to add it to the div.
// so just show it!
echo $email_users; // think about this for a second though
// what are you trying to achieve?
}
}
?>"
This is a vast question, not very specific. Checkout more about AJAX requests - basically from javascript you will have a call to the server that retrieves your data.
This is a snippet from the javascript library jQuery :
$.ajax({
type: "POST",
url: "emails.php",
data: { user: "John" }
}).done(function( msg ) {
$('teammembers').html(msg);
});
hope this will give you a starting point
The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston"
success: function(data){
alert('done');
});
I am trying to do pagination using javascript but all in vain, please help..
<script language="Javascript">
function nextclicked()
{
document.getElementById("clickednext").value = document.getElementById("clickednext").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$_POST['clickednext']. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
UPDATE :
<div class=d2 align=left>
<a href="#" onclick=" nextclicked(); submit();" >
Next
</a>
UPDATE ENDS......
The first time when i click the Next hyperlink label, then it works, that is, 10 is assigned $_POST['clickednext'] and the next 10 values appear from the database, but the second time i click the label , then it doesn't?
Your code is completely wrong.
You should scrap it and start all over again.
I will show you how to do so.
I have a rule when it comes to Ajax, and it goes like this.
If you cannot do the functionality without Ajax, there's no way you should attempt to do it with Ajax.
If you know anything about javascript, you'll know that XmlHttpRequest makes working with Ajax hellish. Hence why we have javascript frameworks such as JQuery and Mootools. You might also like a php ajax framework called PHPLiveX. I only use JQuery, so here's how to do the solution in JQuery.
Step 1: Strip your ajax and create the solution in php
This pagination tutorial in php will help.
Step 2a: Create the ajax with PHPLiveX
PHPLiveX is really cool and underated, as it allows you to use php functions without reloading the whole page, in a more convienient way, than if you'd used javascript.
PHPLiveX will help you the best.
It's pretty straightforward. You call a php function to do something, return some values, and choose the target: of where you want the values to go.
I personally would use PHPLiveX for this job, as it's better suited. JQuery is more for postdata.
Step 2b: Create the ajax in JQuery
I'm going to assume that you know how to select elements by id with JQuery and append or replaceWith them. If not you can look the function up.
Below is the code required to submit a POST or GET with JQuery. Adapt this to your code. You'll have to modify the code below to add appending and stuff.
$(".tornfieldcard").click(function() {
var dataString = $("#addfieldForm").serialize();
//lets get the form data and use that
var newValue = $("#newValue").val();
var itemid4 = $(this).attr("itemid4");
var dataString = "itemid=" + itemid + "&newValue=" + newValue;
//or get the attr/valu from elements
$("#loading5").show();
$("#loading5").fadeIn(400).html('<img src="icons/loading.gif">');
$.ajax({
type: "POST",
url: "ajaxcontrols.php",
data: dataString,
cache: false,
success: function(html){
$("#loading5").remove();
$(".fieldcardNEW").fadeOut('slow');
$('.fieldcardNEW').remove();
$("#conveyorbelt_"+itemid4+"").append("<div class=\"fieldcard\"><b>"+attribute+"</b> <br><div itemid=\""+itemid4+"\" attribute=\""+attribute+"\">"+value+"</div></div>");
}
});
Here's a little algorithm I wrote using php to create pagination:
$x=$numStories;
$y=$x%5;
$z=($x-$y)/5;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
Where 5 is the number of stories per page, and $numStories is the total amount of stories (or in your case, news articles) you wish to use.
Then, just display the amount of pages ($numPages) in any way you'd like, and your good to go.
[EDIT]
I created an archive.php page, that took a page number as a GET parameter (archive.php?page=3). From there, I selected the first five entries in my database after $pageNum (in this case 3) * 10 (or however many posts per page you are wanting to display.
The best thing to do is make as much of your code dynamic and flexible, so that it is self sustaining.
[EDIT 2]
<script>
function nextclicked()
{
document.forms["newsmanager"].submit();
}
</script>
<?php
$currentPage = $_POST['page'];
$numStories = //get the total amount of entries
$x=$numStories;
$y=$x%10;
$z=($x-$y)/10;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
if(isset($currentPage) && $currentPage>=1)
{
$currentPage = $currentPage +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$currentPage. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
<form>
<input type='hidden' name='page' text='' value='<?php echo "$currentPage"' />
</form>
Next-->
PHP is server-side language. you have to put your php code to
<?php
=====
<script language="Javascript">
function nextclicked()
{
document.getElementById("next").value = document.getElementById("next").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
<?php
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .intval($_POST['clickednext']). ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
additionally, user can't click to hidden form field. you need, for example button and have onclick event ready
<button name="next" value="1" onclick="nextclicked();">Next</button>