Displaying mysql query result using jquery - php

I'm trying to display data from mysql on the same page that i've got my form with checkboxes. The question is how to write js script that gonna display it.
The code is:
<form id="myForm" action="pdoakcja.php" method="post">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<div id='name-data'>Instruktorzy o podanych uprawnieniach:</div>
<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script>
............??????
</script>

You could solve your problem by using jquery form plugin, which will help you to submit the form without having to reload the page and show you the return from your target page in the same page. Just follow the instructions:
Download this jquery form plugin first and save it.
Then
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!-- This jquery.form.js is for Submitting form data using jquery and Ajax -->
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse
};
// bind form using 'ajaxForm'
$('#myForm').ajaxForm(options);
});
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
if(responseText==1){
$("#error").html('No Result Found');
} else{
$("#result").html(responseText);
}
}
</script>
<form id="myForm" enctype="multipart/form-data" action="pdoakcja.php"
method="post" name="myForm">
<!--Instruktor: <input type="text" name="name" /> -->
Permissions:<input type="checkbox" name="M1" value="M1" />M1
<input type="checkbox" name="M2" value="M2" />M2
<input type="submit" value="Szukaj" />
</form>
<span id="error"></span>
<span id="result"></span>
YOUR pdoakcja.php file: (I have got the following code from your another post here, haven't checked it though)
<?php
$query = mysql_query("SELECT * FROM permissions WHERE m LIKE '".$_POST['M1']."' OR m LIKE '".$_POST['M2']."' OR mn LIKE '".$_POST['MN1']."' ");
if($query) {
while($permissions = mysql_fetch_assoc($query)){
$query2 = mysql_query("SELECT name_surname FROM instruktorzy WHERE instruktor_id='".$permissions['instruktor_id']."'");
while($Mdwa = mysql_fetch_assoc($query2)){
echo "<p style=\"font-size: 14px; font-family: Helvetica; background-color: #FFFFFF\"> ".$Mdwa['name_surname']."<br />" ; "</p>" ;
}
}
} else {echo "1";}
?>
I hope this will work for you. For detail information you could study the jquery form plugin's website.

Heres a pseudo example showing how you can do it with jQuery, this will also update as you click the check box so you could remove the submit altogether;
You say you already have a database doing the job so I wont include that. Just copy and paste.
<?php
//Some pseudo data kinda as your receive it from a query
$datafromSql = array(
array('id'=>1,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>2,'permission'=>'M2','theData'=>'User has M2 permission'),
array('id'=>3,'permission'=>'M1','theData'=>'User has M1 permission'),
array('id'=>4,'permission'=>'M1','theData'=>'User has M1 permission'),
);
//Access the data
if($_SERVER['REQUEST_METHOD']=='POST'){
$is_ajax = false;
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
$is_ajax = true;
}
//pseudo code, really you would put your query here
// SELECT theData FROM your_table WHERE permission=POST_VALUE ... ...
//And then format your output
$result=array();
foreach($datafromSql as $row){
if($is_ajax == true){
foreach($_POST as $key=>$value){
if($_POST[$key] == 'true' && $row['permission']==$key){
$result[]=$row['theData'].'<br />';
}
}
}else{
foreach($_POST as $key=>$value){
if($_POST[$key] == $row['permission']){
$result[]=$row['theData'].'<br />';
}
}
}
}
$result = implode('<hr />',$result);
//AJAX Response, echo and then die.
if($is_ajax === true){
header('Content-Type: text/html');
//example output sent back to the jQuery callback
echo $result;
//echo '<pre>'.print_r($_POST,true).'</pre>';
die;
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js" charset="utf-8"></script>
<script type="text/javascript">
function update(){
$.post('./<?php echo basename(__FILE__)?>',
{
M1: $("#M1").is(':checked'),
M2: $("#M2").is(':checked')
},
function(data) {
$('#result').replaceWith('<div id="result"><h1>The Result:</h1>'+ data +'</div>');
});
}
</script>
</head>
<body>
<form method="POST" action="<?php echo basename(__FILE__)?>">
Permissions:
<input type="checkbox" id="M1" name="M1" value="M1" onChange="update()"/>M1
<input type="checkbox" id="M2" name="M2" value="M2" onChange="update()"/>M2
<input type="submit" value="Szukaj" />
</form>
<p id='result'><?php echo isset($result)?$result:null;?></p>
</body>
</html>

You should use the PHP MySQL functions to retrieve the data you want from your database and then display them via PHP, not javascript.
Especially have a look at this: mysql_fetch_assoc - there is a fully working example.

Related

Ajax submit one page PHP

I have code with single page PHP method
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<?php
if(isset($_POST['submit'])){
$date=$_POST['date'];
}else{
$date=date('Y-m-d');
}
?>
<form action="" method="post" id="formId">
<input type="text" name="date" id="datepicker">
<input type="submit" name="submit">
</form>
<?php echo $date; ?>
<script>
$(function() {
$('#datepicker').datepicker({
autoclose: true
})
});
</script>
how, if i want to use ajax to keep the page not to reload? please help me
ok so here is quick tutorial. ajax helps you to submit your form without page loading. You have to use action="somepage.php". when you click it it will pass the values there right away. so here is basic coding
<form id="formId">
<input type="text" name="dte" id="dte">
<button type="button" id="buttonsubmit">submit</button>
</form>
and ajax should be look like. In my coding id="buttonsubmit" is button id so when user will click it it run the function and takes the values
var dte;
$("#buttonsubmit").click(function(){
dte = $("#dte").val();
$.ajax({
url:"somepage.php",
method:"POST",
data:{dte: dte},
success: function (data){
if(data == "done"){
window.location='http://somedomain.com/';
}
}
});
});
in somepage.php you will have
<?php
if(isset($_POST['dte'])){
$date=$_POST['dte'];
echo "done";
}else{
$date=date('Y-m-d');
}
?>
note: i am writing echo "done"; in success method it will come and
according to code when success will see it will redirect the page

submit should not redirect to another page in HTML form

I have a HTML form which reads some data and saves in the text file with help of PHP. The form's HTML code looks like below.
What is happening now:
1. once i click on submit button it redirects to the 'myprocessing.php'
2. successfully saving in data.txt
The help i required on
1. when i click on submit it shouldn't redirect me to the php page, it should stay on the HTML form page
2. it should show the php file's output on the same HTML page
In simple words, I want to stay on the HTML page itself. Since I'm pretty new to HTML and PHP, struggling much to do these. Thanks in advance :-)
<html>
<head>
<title></title>
</head>
<body>
<form action="myprocessing.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
This is my data prcoessing PHP file.
<?php
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
?>
Try below. Call refresh_div() on button click :-
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'YOUR PHP page url',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
</script>
Write php code in same html file and use isset() function to check for $_POST data
Try this
<?php
if(isset($_POST['field1']) && isset($_POST['field2']))
{
echo "starting...";
if(isset($_POST['myTextBox']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('data.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
echo "Ended...";
}
else {
die('no post data to process');
}
}
?>
<html>
<head>
<title></title>
</head>
<body>
<form action="current_page.php" method="POST">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
</body>
</html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST" name="testForm" id="testForm">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Show data</a>
<div class="result"></div>
</body>
</html>
add the name and id for form tag. if you keep action as blank, it will submit your form to current page itself.
You need a ajax call to perform as per your requirement.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$( "#testForm" ).on( "submit", function( event )
{
$.ajax({
url:'myprocessing.php',
type:'POST',
data: $("#testForm").serialize()
success:function(results) {
jQuery(".result").html(results);
}
});
return false;
});
</script>
Dont forget to put a return false at the end. If we dont put return false, it will submit your form after the ajax call.

saveScrollPosition with unique form id

Im using the following (seemingly common) method to save scroll position on submit in a php page:
<script type="text/javascript">
<!-- script for scroll position on submit -->
function saveScrollPositions(theForm) {
if(theForm) {
var scrolly = typeof window.pageYOffset != 'undefined' ? window.pageYOffset : document.documentElement.scrollTop;
var scrollx = typeof window.pageXOffset != 'undefined' ? window.pageXOffset : document.documentElement.scrollLeft;
theForm.scrollx.value = scrollx;
theForm.scrolly.value = scrolly;
}
}
</script>
</head>
<body>
<form id="ReportForm<?php echo $userNumber; ?>" name="ReportForm" method="POST" action="<?php echo $editFormAction; ?>" onsubmit="return saveScrollPositions(this);">
<input type="hidden" name="scrollx" id="scrollx" value="0" />
<input type="hidden" name="scrolly" id="scrolly" value="0" />
-- various form controls here --
</form>
<?php
$scrollx = 0;
$scrolly = 0;
if(!empty($_REQUEST['scrollx'])) {
$scrollx = $_REQUEST['scrollx'];
}
if(!empty($_REQUEST['scrolly'])) {
$scrolly = $_REQUEST['scrolly'];
}
?>
<script type="text/javascript">
window.scrollTo(<?php echo "$scrollx" ?>, <?php echo "$scrolly" ?>);
</script>
</body>
In the body the form is wrapped by a repeat region to get multiple reports from a database, but each form in the loaded page at runtime needs a unique id, so in the form tag i have:
id="reportForm<?php echo $userNumber ?>"
which causes the saveScrollPositions to fail. Removing the userNumber that is tacked on to the end works. Any idea how i can fix this?
I very much appreciate any help you can offer on this and thank you in anticipation.
Kind regards,
John

submit normally newly created ajax form

I want to submit my form. In my form using first button I create a textbox through ajax and after that I use second button to submit the form normally. When I want to get the value of newly created textbox using $_POST it gives error. How can i get value of ajax created button on submission. my php code is :
<?php`enter code here`
session_start();
ob_start();
require_once "config.php";
if ($_SERVER['REQUEST_METHOD']=="POST")
{
if (isset($_POST['subtest']))
{
print $_GET['tt'];
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-ui-1.8.21.custom.min.js"> </script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#subt").click(function(){
jQuery("#divload").show();
jQuery.ajax({url:"adp.php", type:"post", success:function(result){
jQuery("#disp").html(result);
jQuery("#divload").hide();
}});
return false;
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#subtest").click( function() {
alert(jQuery("#tt").val());
});
});
</script>
</head>
<body id="#bdy">
<form id="FrmMain" method="post" action="">
<div id="Shd" style="font: 10%; margin: 50px; background-repeat:repeat-y; padding- left:120px;" >
<input type="text" id="txtFrom" name="txtFrom" />
<input type="text" id="txtUpto" name="txtUpto" />
<input type="text" id="txtOpt" name="txtOpt" />
<input type="submit" id="subt" name="subt" />
<input type="submit" id="subtest" name="subtest" />
<div id="RuBox" style="font-weight:bold;"><input type="checkbox" id="chkaccept" name="chkaccept" /> I accept terms and conditions.</div>
</div>
</form>
<div style="color:#F00; font-size:18px; display:none;" id="divload">Please wait loaidng... </div>
<div id="disp"></div>
</body>
</html>
Code of my adp.php file :
<?php
sleep(5);
?>
<div style="color:#30F; font-size:36px;">
Application testing............
<input type="text" id="tt" name="tt" />
</div>
I am not getting value of textbox named "tt" in temp form
Thanks
You're pretty much not posting anything from here:
jQuery(document).ready(function(){
jQuery("#subt").click(function(){
jQuery("#divload").show();
jQuery.ajax({url:"adp.php", type:"post", success:function(result){
jQuery("#disp").html(result);
jQuery("#divload").hide();
}});
return false;
});
});
So I would assume that you only want to generate a text field dynamically. And you can do it without the use of ajax:
var form = $('#FrmMain');
$('<input>').attr({'type' : 'text', 'id' : 'tt', 'name' : 'tt'}).appendTo(form);
Plus you're also trying to print out $_GET['tt'] while the form method is POST
if (isset($_POST['subtest']))
{
print $_GET['tt'];
}
This should also be:
echo $_POST['tt'];

Can a submit button work without refresh AJAX?

I have a problem with my very simple chat. The page is constanly refreshing with AJAX with an timeout of 750ms. If I press or use enter to submit my 'reaction', the page refreshes: is there an way to remove that, so that you can instantly see what you've posted?
You can see the chat at my website: chat
The code:
Index.php
<!DOCTYPE HTML>
<?php include 'config.php'; ?>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.js">
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
</script>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
enter code here
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="text" value="" name="username" />
<input type="submit" value="verstuur" name="submit" onKeyPress="return submitenter(this,event)" />
</form>
<?php include 'send.php'; ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 750 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
chat.php
<?php
include 'config.php';
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
send.php
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
if my question is not clear say it please.
And is there a topic/question/post about good spacing? google translated it as "indent".
Thanks
Replace
<form method="post">
With
<form onsubmit="event.preventDefault()" method="post">
You may also use your callback function here like:
<form onsubmit="event.preventDefault();return submitenter(this,event);" method="post">
Working demo: http://jsfiddle.net/usmanhalalit/5RCwF/2/
Add e.preventDefault(); in JS.
Your desired action is to prevent the onSubmit action as the other answers have mentioned. Currently your script isn't quite ready to block submit as you don't have an ajax post method.
You need ajax functionality for the submission side of the application still. For this you can use jQuery post().
You want to create something like
function send() {
$.post(); // Fill in appropriate post() code.
return false;
}
And then call it from your event handlers like onsubmit="return send()" and in place of myfield.form.submit() in your keypress handler.

Categories