How can I pass the data back to index file? - javascript

I have an index.php file to contain the layout of my website. In the index file, I have a search form which sends data to another php file to process(action="search.php"). My problem is: I can select the data that suits the user's keyword and output it, but the output isn't with the layout, it's just text on white background. What I need to know is: How can I pass the data that I've selected back to index.php so that it can have layout? I've tried window.location and include but it didn't work. Here's my code:
<?php
$search=$_GET['search'];// name of the text field is "search"
include('connectdb.php');
$result=mysql_query("SELECT * FROM article WHERE header LIKE '%".$search."%'");
while($row=mysql_fetch_array($result))
{?>
<?php echo $row['header'];
echo $row['content'];
}
?>

Use php Header function to go back to index.php. This is a demo only. You just get the idea and design what you want.
<?php
$search=$_GET['search'];// name of the text field is "search"
include('connectdb.php');
$result=mysql_query("SELECT * FROM article WHERE header LIKE '%".$search."%'");
while($row=mysql_fetch_array($result))
{?>
header("index.php?header=".$row['header']."&content=".$row['content']);
}
?>
Then catch these details in your index file
<?php
$header=$_GET['header'];
$content=$_GET['content'];
?>

You can make something like this:
var text = $(this).val();
$.ajax({
url: "search.php",
type: "POST",
data: {search: text},
datatype: 'json',
success: function(data){
if(data){
//here you are parsing json object
var data = JSON.parse(data);
//0: Object
//header: "blablabla"
//content: "blablabla"
//1: Object
//header: "wwwwwws"
//content: "wewesssss"
//length will be equal of results amount
var length = data.length;
var li = '';
//here you are making li
for(var i = 0; i < length; i++){
li += '<li>';
li += data[i]['header'] . data[i]['content'];
li += '</li>';
}
//appending element in dom
$('ul').html(li);
}
}
});
this ajax...
$row = mysql_fetch_array($result);
$row = json_encode($row);
eco $row;
//this will return json object
//[{"header":"blablabla","content":"blablabla"},{"header":"wwwwwws","content":"wewesssss"}]
this your php

here is a simple example, you just gotta copy the exact same layout of index.php and implement it on search.php if you are selecting data from database on index.php then do the same query on search.php
style.css
.center_content{
width:500px;
height:300px;
background:yellow;
border:1px solid;
}
.right_column{
width:200px;
height:300px;
background:Red;
display:inline-block;
}
.right_column{
width:200px;
height:300px;
background:green;
display:inline-block;
}
index.php
<link type="text/css" rel="stylesheet" href="style.css">
<form method="get" action="send.php">
<input type="text" name="search" placeholder="search here">
<input type="submit" value="submit">
</form>
<div class="left_column">blah blah</div>
<div class="center_content">
put whatever you want here
</div>
<div class="right_column">blah blah</div>
search.php
<form method="get" action="">
<input type="text" name="search" placeholder="search here">
<input type="submit" name="submit" value="submit">
</form>
<div class="left_column">blah blah</div>
<div class="center_content">
<?php
if(isset($_GET['submit'])){
$search=$_GET['search'];// name of the text field is "search"
include('connectdb.php');
$result=mysql_query("SELECT * FROM article WHERE header LIKE '%".$search."%'");
while($row=mysql_fetch_array($result))
{?>
<?php echo $row['header'];
echo $row['content'];
}}
?>
</div>
<div class="right_column">blah blah</div>

Related

PHP: multiple button with different name to update MySQL database with AJAX

I have an problem, I have multiple button generate with while, with different names (button[$nostation]).
Now, I want to update MySQL database (table: smt, column: no) with the same id ($nostation).
How I can generate AJAX function for that?
This is my code:
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
echo "
<div class='col-xs-2-2'>
<form action='coba.php' method='post'>
<button name='button[$nostation]' value='2' style='background-color:#02780d; width:140px; height:75px; margin : 2px; border-radius:10%;'>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
";}?>
And this is my code for update database with PHP:
<?php
include 'connect.php';
$array=$_POST['button'];
foreach ($array as $nostation => $value) {
$updch=mysqli_query($connect,"UPDATE smt SET status='$value' WHERE no='$nostation'");
}?>
How I can update with AJAX without refreshing the page?
View Part :-
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
?>
<div class='col-xs-2-2'>
<form method='post'>
<input type="hidden" value="<?php echo $nostation;?>" id="name_<?=$nostation;?>" name="name">
<button type="submit" id="button_<?=$nostation;?>" data-id="<?=$nostation;?>">SAVE</button>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
<?php } ?>
jQuery / AJAX Part:-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ //when DOM is Ready.
$("[id^=button_]").click(function () { //when Button is Clicked.
var id = $(this).data('id'); // Get the ID of the button that was clicked on.
var name = $("#name_"+id).val(); // value from `input` which is connected the clicked button.
// console.log(id+"---"+name);
$.ajax({ // AJAX request
url: 'update.php', // send request to server.
method: 'POST', // method is POST.
data: { //data which is sent to server.
id: id,name: name
},
success: function (data) { //success function called.
alert(data); // alert success data.
}
});
});
});
</script>
update.php:-
And in the php-side We catch it by:-
echo $id = $_POST['id'];
echo $name = $_POST['name'];
//use update query.
Note:- For more info regarding click()
https://api.jquery.com/click

How to pass the id from url in php function without refreshing the page?

I have a div which contains a button(Book it).When I press the button I want to add to the current url the id of the item I clicked on.Then get that id to pop up a box with clicked item data without refreshing the page, because I need to pop up in the current page.
Here it gets the treatments Id
<div class="treatments">
<ul>
<?php
global $treatments;
foreach($treatments as $treatment){
echo ' <li>'.$treatment['name'].'</li>';
};
?>
</ul>
<div class="line"></div>
</div>
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" id="hidden_input" name="id_item" value="'.$item['id'].'">
<a class="bookBtn" id="btn"><button>BOOK IT</button></a> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
</div>
Pop up box
<div class="bookDetails">
<div class="details">
<?php
global $iController;
$itemm;
if(isset($_GET['id_item'])){
$itemm = $iController->getItemById($_GET['id_item']);
}
echo'
<h1>Book your treatment</h1>
<p>Treatment Name : '.$itemm['name'].'</p>
<p>Treatment Time :'.$itemm['time'].' </p>
<p>Treatment Price : '.$itemm['price'].'</p>
';
?>
<form action="" method="POST">
<label for="date">Choose your date:</label>
<input type="date" for="date" name="date"><br>
<input type="submit" value="Cancel" id="cancel">
<input type="submit" value="Book Now">
</form>
Jquery code
$(".bookBtn").click(function(){
$(".bookDetails").show();
})
getItemById function
public function getItemById($id){
$sql="SELECT * FROM treatments_item WHERE id=$id";
echo $id;
$items = mysqli_query($this->connection,$sql);
$returnArray = array();
if($items){
while($row = mysqli_fetch_assoc($items)){
array_push($returnArray, $row);
}
return $returnArray[0];
}else{
echo'It doesn't work';
}
}
You can use ajax or mix php and javascript like this:
<script>
$(document).ready(function() {
<?php session_start(); ?>//Remove session_start
if (!<?php $_GET(['id'])?'true':'false'; ?>) {
alert something
} else {
something ..
}
});
</script>
hope this was helpful. :)
<div class="treatment-items">
<?php
global $iController;
$items;
if(isset($_GET['treatmentID'])){
$items = $iController->getItemByTreatmentId($_GET['treatmentID']);
}else{
$items = $iController->getItemByTreatmentId(4);
}
foreach($items as $item){
echo '
<div class="col-30 items">
<div>
<p>'.$item['id'].'</p>
<img src="'.$item['img_url'].'" alt="'.$item['name'].'" />
<h3>'.$item['name'].'</h3>
<p>'.$item['time'].' min</p>
<p>'.$item['price'].'$</p>
<input type="hidden" class="id_item" value="'.$item['id'].'">
<div class="bookBtn"><button>BOOK IT</button></div> // when I press this button I want that box to pop up
</div>
</div>
';
}
?>
Note: Never use id same name in one Page i.e., id="hidden_input" // In for loop same name will be generated. It will create bug down the line. Same goes for Input name, instead use class.
$(document).ready(function(){
$('body').on('click','.bookBtn',function(){
var treatmentID = $(this).siblings('.id_item').val();
// $(this) --> it will read the data of the property you have clicked
// .siblings --> adjacent class with name ('.id_item')
$.ajax({
url: 'treatments.php',
type: "get", //send it through get method
data: {
treatmentID: treatmentID
},
success: function(response) {
//operation to show the data in div
//e.g., $('#divId').html(data.name);
$(".bookDetails").show();
}
});
})
})

how to change the html tag element when onclick to a input text, so the user can edit comment

I am actually trying to make comments and also edit option when the comment enters it will show in a 'div'through ajax.
<?php
$q="select * from discuss where rownum=1 order by id desc";
$s=oci_parse($conn, $q);
$r=oci_execute($s) or die(oci_error());
echo "<table border=1>";
while($m=oci_fetch_assoc($s))
{
echo "<tr style='background-color:red'><th style='float:left;color:white'>Name : ".$m['NAME']."</th><th style='float:right;color:white'>Date: "."".$m['DATE_TIME']."</th></tr>";
echo "<tr class='edit_option' style='width:1000px;height:10px;background- color:white'><div><td id='input_text' style='width:1000px;height:10px;background- color:white'>".$m['COMMENTS']."</div><div class='anchor_edit' id='anchor_id_edit'><span onclick=\"edit_text('".$m['COMMENTS']."')\">edit</span></div></td></tr>";
}
echo "</table>";
?>
<script>
function edit_text(edit_option){
alert(edit_option);
}
</script>
onclick the function value is coming to edit_text() function getting alert, here i am not getting how can iput logic for this comment.
when edit option is clicked the user has to get his/her comment in a input text 'value' so the user can edit comment.
onclick how can i do the edit comment, please anyone can help!!
This may be help to you
Here I take a sample array input data
PHP SCRIPT
<?php
$r=array(
array('COMMENT-ID'=>'1','NAME'=>'Comment1','COMMENTS'=>'Comment1Comment1Comment1Comment1','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'2','NAME'=>'Comment2','COMMENTS'=>'Comment2Comment2Comment2Comment2','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'3','NAME'=>'Comment3','COMMENTS'=>'Comment3Comment3Comment3Comment3','DATE_TIME'=>'12547896321'),
array('COMMENT-ID'=>'4','NAME'=>'Comment4','COMMENTS'=>'Comment4Comment4Comment4Comment4','DATE_TIME'=>'12547896321')
);
echo "<div>";
foreach($r as $m)
{ ?>
<div>
<div>
Name : <?php echo $m['NAME']; ?>
</div>
<div>
Date: <?php echo $m['DATE_TIME']; ?>
</div>
</div>
<div class="comment">
<div class="comment-text" id="comment<?php echo $m['COMMENT-ID']; ?>">
<?php echo $m['COMMENTS']; ?>
</div>
<div class="commentEditBtn">
Edit
</div>
<div class="editedText"></div>
<div class="commentInput" data-id="<?php echo $m['COMMENT-ID'] ?>">
<input type="text" name="comment" /><br/>
<button class="commentSubmit">Submit</button>
</div>
</div><br/>
<?php }
echo "</div>";
?>
jQuery
$(".commentEditBtn").on('click',function(){
$('.commentinput').hide();
var parentDiv = $(this).parent();
var commentText = parentDiv.find('.comment-text').html();
parentDiv.find('.commentInput input').val(commentText.trim());
parentDiv.find('.commentInput').show();
});
$(".commentInput > input").keypress(function(){
var commentData = $(this).val();
$(this).parent().parent().find('.editedText').html(commentData.trim()).show();
});
$(".commentInput .commentSubmit").on('click',function(){
var commentId = $(this).parent().attr('data-id');
var commentText = $(this).parent().find('input').val().trim();
$(this).parent().parent().find('.editedText').html('').hide();
$.ajax({
url: "AJAX_POST_URL",
type: "POST",
data: {
commentId: commentId,
commentText: commentText
},
dataType: 'json',
success: function (data) {
if (data.error == 'false') {
$('#comment' + commentId).html(commentText);
}
}
});
});
CSS
.commentInput{display: none;}
.editedText{display: none;}
Check out this jquery plugin: http://jsfiddle.net/2u89gnn8/1/
You can make, for example, an h1 editable when a user clicks a button:
$('h1').editable({
"enable": true,
"trigger": $('button')
});

AJAX comment system Validation problems

So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique

Using passed variable from jquery to php dynamically update fields

I have a bunch locker numbers in a drop down list (populated from MYSQL/PHP). I want to display the locker's combination and location when you select a locker number from the list in two input fields below on the same page.
I have used jquery to tell me which item in the list is selected dynamically. Then I used the $.ajax() function to send that item to my server.
My problem: Can I use $.ajax() to send my variable to the same page I am on? I have tried this and I get an error. I am not sure how to accomplish this. My knowledge of AJAX is very minimal.
My code is as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Locker Backend</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="form.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
function show()
{
$('#addlocker').toggle();
}
function lockerSelected(sel)
{
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(){
alert(selected);
}
});
}
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<?php
$url = $_SERVER['REQUEST_URI'];
$studID = substr($url, strpos($url, "=") + 1);
$db_handle = mysql_connect("localhost", "root", "pickles") or die("Error connecting to database: ".mysql_error());
mysql_select_db("lockers",$db_handle) or die(mysql_error());
$result = mysql_query("SELECT * FROM students WHERE studID = $studID");
?>
<div class="container">
<header> <img src="images/headmast.png" alt="Insert Logo Here" width="686" height="180" id="Insert_logo" /> </header>
<div id="data1">
<form id ="studData" name="studData" action="update.php" medthod="post">
<fieldset>
<legend>Student Details</legend>
<?php
while($row = mysql_fetch_array($result))
{
echo '<ol>';
echo '<li>';
echo '<label for=studid>Student ID</label>';
echo '<input id=studid name=studid type=text value='.$row['studID'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>First Name</label>';
echo '<input id=fname name=fname type=text value='.$row['firstName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=fname>Last Name</label>';
echo '<input id=lname name=lname type=text value='.$row['lastName'].'>';
echo '</il>';
echo '<li>';
echo '<label for=email>Email</label>';
echo '<input id=email name=email type=text value='.$row['email'].'>';
echo '</il>';
echo '<li>';
echo '<label for=progam>Program</label>';
echo '<input id=progam name=progam type=text value='.$row['program'].'>';
echo '</il>';
echo '</ol>';
$program = $row['program']; //get name of program
}
?>
<input type="submit" value="Update" class="fButton"/>
</fieldset>
</form>
<form id="locker" name="locker" action="" method="post" >
<fieldset>
<input type="button" onclick="show()" value="Add Locker"/>
<div id="addlocker" style="display:none;">
<!--
query lockers where $program = program parsed in & student id is equal to 0 (this makes it available)
get select list to 10
populate select list --> <br/>
<legend>Lockers Available: </legend>
<select size="10" name="lockerSelect" multiple="yes" style="width:200px;" onChange="lockerSelected(this);">
<?php
$result1=mysql_query("SELECT * FROM lockers WHERE progName = '$program' && studID = 0") or die($result1."<br/><br/>".mysql_error());
while($row1 = mysql_fetch_array($result1))
{
echo '<option value=\"'.$row1['lockerScan'].'">'.$row1['lockerNo'].'</option>';
}
echo '</select>';
echo '<br>';
$lockerNo = $_POST['selected']; \\doesn't work - displays error
echo $lockerNo; \\errors out
?>
</div><!--end of add locker section-->
</fieldset>
</form>
</div><!--end of data1 -->
Search
</div><!-- end of container-->
</body>
</html>
Firstly, you can use :
function show()
{
$('#addlocker').toggle();
}
Then, you should learn more about Ajax and PHP. Your call shoud be :
var selected = (sel.options[sel.selectedIndex].text);
$.ajax({
type:"POST",
url: "studentdata.php",
data: {selected: selected},
success: function(data){
alert(data);
}
});
And in your PHP file :
<?php
$select = $_POST['selected'];
//....
// Do what you have to do then return your result
echo '<div>Send to your page !</div>';
First Arrange your files.
js's is in js folder
php's in php folder
best way is to assaign a seperate php page and then in js use on change event
$(document).on("change", "#selectfieldid", function(){
var selected = $('#selectfieldid').val();
$.ajax({
type:"POST",
url: "studentdata.php",
data: selected,
success: function(data){
$('#addlocker').val(data); //echoed result placed here that has id addlocker
}
});
});
send those to a php page echo the result in that php.

Categories