I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.
Related
I'm developing discussion board and I want to make a reply system on each comment using jquery.
I created certain div inside a loop with different values in each iteration.
Now I'm working on submitting the reply form and I have a problem. It works only on the first comment. When I reply to the first comment only It works but when replying to any other comment It doesn't work and give me my error message the textbox is empty Then I realized that it reads data from the first form only through the loop.
Here is the code.
<div class="comment_form">
<textarea class="span10" id="replyC" name="replyC" placeholder="Reply comment" rows="6">
</textarea><br>
<input id="commentId" name="commentId" type="hidden" value="<?php echo $CommentID;?>">
<input id="userId" name="userId" type="hidden" value="<?php echo $uId;?>">
<input id="articleId" name="articleId" type="hidden" value="<?php echo $ArticleID; ?>">
<input class="btn btn-lg btn-default replyForm" id="<?php echo $CommentID; ?>" name="replyForm" type="submit" value="Reply">
</div>
The button with class name "replyForm" I get it by
$(".replyForm").click(function()
and here is the javascript and Ajax code.
$(".replyForm").click(function(){
//$(this).parents().next('.replyForm').click(function(){
var user_reply = $("#replyC").val();
var userId = $("#userId").val();
var comment_id = $("#commentId").val();
var articleId = $("#articleId").val();
$.ajax({
url:'articleReply.php',
data:{replyC:user_reply,userId:userId,commentId:comment_id,articleId:articleId},
type:'POST',
success:function(data){
$("#resultReply").html(data);
$('#replyC').val('');
}
});
});
The problem Now .. It doesn't work on all comments retrieved from the loop but works only on the first comment while trying reply on other comments I get my empty message appears under the first comment.
So it get data from the first comment only not from the rest.
Any help ??
Here it works:
Here is the problem:
Hay I'm new to php and I have made php code like this :
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
</div>
<br/><br/>
<?php
echo $myValue;
?>
</form>
When I want to show the echo message, I need to hit enter on my keyboard first in order to get the value of $_POST['nama_tamu'];. My question is can I get the value of nama_tamu input without pressing enter, or maybe without using POST or GET and then assign it to $myvalue?
You will need to use Javascript. You can use the Jquery events :
<script>
$( "#nama_tamu" ).keyup(function() {
alert( $this.val() );// alerting the value of the input field
});
</script>
Web development is all about communication. In this case, communication between two (2) parties, over the HTTP protocol:
The Server - This party is responsible for serving pages.
The Client - This party requests pages from the Server, and displays them to the user. In most cases, the client is a web browser.
Each side's programming, refers to code which runs at the specific machine, the server's or the client's.
You cannot get values without submitting for the user has not entered any yet. PHP is a server side language. To get values before submit and do certain actions with them you will need javascript (a client side programming language).
The simplest method to get a value is using the getElementById().
var something = document.getElementById('someid');
<input type="text" name="something" id="someid">
You can also use jQuery:
var something = $('#someid').val();
Conclusion
The simple answer to your question is: This is not possible.
Why not? I hear you asking. Because PHP doesn't know the values of your form before you send the form to your webserver.
Use keyup().
function check(id)
{
document.getElementById("result").innerHTML = id;
}
<input type="text" name="test" id="test" onkeyup="check(this.value);">
Your value: <span id="result"> </span>
$(document).ready(function() {
$("#check").keyup(function(){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="check" >
For this purpose you should use .keyup function/event. Following are the snippet :
$(document).ready(function () {
$("#nama_tamu").keyup(function(){
$("#enterdata").html($("#nama_tamu").val());
$.ajax({
type: 'POST',
url: "getdata.php",
data: "nama_tamu="+$("#nama_tamu").val(),
success: function(res)
{
$("#outputdata").html(res);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
<br> You press following character:<div id="enterdata"> </div>
</div>
<br/><br/>
<div id="outputdata"></div>
<?php
echo $myValue;
?>
</form>
Also create one file for the required output.
Now in getdata.php file
echo $nama_tamu=$_POST['nama_tamu'];
Im sorry for my bad english.
Im begineer with PHP and all coding method.
I've been searching this for a days and still cannot find what I need lack to my understanding especially with php, java or ajax.
I have an emailmeform form and I have my own form on 1 php file which I want when client submit the send button, it will save the data entered previously by client to my internal database and send it to emailmeform in the same time but I cannot make this happen.
The solution I think will work is maybe ajax or javascript, but since lack of my knowledge with those codes I cannot solve this issue by my self.
Here's my code (all in 1 php script page):
<?php
session_start();
include "connection/database.php";
$sql = mysql_query("SELECT * from tb_config");
$config = mysql_fetch_array($sql);
if (isset($_POST['send'])) {
$username = $_POST['element_1'];
$password = $_POST['element_2'];
$referral = $_POST['referral'];
$a = mysql_num_rows(mysql_query("SELECT * from tb_member where username='$username'"));
if (empty($username) || empty($password)) {
echo "<script> alert('Please fill all the required form!!'); </script>";
} else if (strlen($_POST['element_2']) < 6) {
echo "<script> alert('Password at least 6 digit!!!'); </script>";
} else {
$save = mysql_query("insert into tb_member(username,password) values ('$username','$password')");
exit;
}
}
?>
<!-- this is emailmeform scipt -->
<form id="emf-form" target="_parent" class="leftLabel" enctype="multipart/form-data" method="post" action="http://www.emailmeform.com/builder/emf/to/ref">
<div id="emf-form-description"><h2>Form Register</h2></div>
</div>
<ul>
<li id="emf-li-0" class="emf-li-field emf-field-text data_container ">
<label class="emf-label-desc" for="element_0">Your Name</label>
<div class="emf-div-field"><input id="element_0" name="element_0" value="" size="30" type="text"
class="validate[optional]"/><div class="emf-div-instruction">Please fill your name</div></div>
<div class="emf-clear"></div>
</li><li id="emf-li-1" class="emf-li-field emf-field-text data_container ">
<label class="emf-label-desc" for="element_1">Username <span>*</span></label>
<div class="emf-div-field"><input id="username" name="element_1" value="<?php if (isset($_POST['element_1'])) { echo $_POST['element_1']; } ?>" size="30" type="text"
class="validate[required,length[6,15]]"/><div class="emf-div-instruction">At least 6 characters</div></div>
<div class="emf-clear"></div>
</li><li id="emf-li-2" class="emf-li-field emf-field-text data_container ">
<label class="emf-label-desc" for="element_2">Password <span>*</span></label>
<div class="emf-div-field"><input id="element_2" name="element_2" value="" size="30" type="text"
emf_mask_input="true"
class="validate[required,length[6,]]"/><div class="emf-div-instruction">At least 6 characters</div></div>
<li id="emf-li-post-button" class="middle">
<input value="Send" type="submit" name="send" onmouseover="return true;"/>
</li>
</ul>
<input name="element_counts" value="14" type="hidden" />
<input name="embed" value="forms" type="hidden" />
</form>
This script works and send to emailmeform, but wont submit any data to my internal database, BUT IF I change the action button to
<form method="post" action="">, this will submit to my internal database but not send to emailmeform. I want this work together, submit to my database and send it also to emailmeform.
I have struggling with this and still not found the answer.
Kindly please help.
Any help will be appreciated
Thanks
Refer this, it will demostrate how to insert data in database
I am creating an application that utilizes JQuery Mobile and PHP, nothing crazy here. I am trying to update a $_POST[''] variable on the page I am currently viewing.
The user clicks on an "Issue_Title" to add "Issue_Txt" to that particular list. So I need a way to know which issue_title the user clicks on so I can add it to the right place. To solve that when I retrieve the issue_title from mySQL table I format like so (testTitle is just a placeholder for debugging...I want $row['issue_title'] there so I can distinguish which title was clicked):
echo "<li data-role='fieldcontain'>"."".$row['issue_title']."</li>";
So onclick it will run the below JS function:
function NewIssueTxt(issue_title)
{
var combined = {'issue_title' : issue_title};
combined = $('#HiddenIssueTxtForm').serialize() + '&' + $.param(combined);
$.ajax({type:'POST', url: 'NewRoundDetails.php', data: combined, success: function(response){ }});
return false;
};
I can see via Javascript Console that this is POSTing as expected when I click the listview link. This should give me a $_POST['issue_title'] that I can use to submit along with the issue_txt which is all captured in the below form...which is a popup form that also appears when the user clicks the Issue_Title href.
<div data-role="popup" id="popupNewIssueTxt" data-history='false' data-theme="a" class="ui-corner-all">
<form id="NewIssueTxtForm" action="/NewRoundDetails.php" onsubmit="return submit_popupNewIssueTxt();" method="post">
<div style="padding:10px 20px;">
<h3>Issue Text:</h3>
<label for="issue_txt" class="ui-hidden-accessible">Issue Text:</label>
<input type="text" name="issue_txt" id="issue_txt" value="" />
<label for="issue_title" class="ui-hidden-accessible">Issue Title</label>
<input type="hidden" name="issue_title" id="issue_title" value="<?php echo $_POST['issue_title']; ?>"/>
<label for="date" class="ui-hidden-accessible">Date:</label>
<input type="hidden" name="date" id="date" value="<?php echo $_POST['date']; ?>"/>
<label for="dept_name" class="ui-hidden-accessible">Department Name:</label>
<input type="hidden" name="dept_name" id="dept_name" value="<?php echo $_POST['dept_name']; ?>"/>
<label for="participants" class="ui-hidden-accessible">Participants:</label>
<input type="hidden" name="participants" id="participants" value="<?php echo $_POST['participants']; ?>"/>
<label for="issue_category" class="ui-hidden-accessible">Issue Category:</label>
<input type="hidden" name="issue_category" id="issue_category" value="Work Environment"/>
<button id="NewIssueTxtButton" form="NewIssueTxtForm" type="submit" data-theme="b">Add</button>
</div>
</form>
As mentioned I confirmed the JS function is working...except I still have no value for $_POST['issue_title']. What am I doing wrong? Is the JS function not submitted fast enough...so I click the Issue_title but my form is opened before the POST happens? If that's the case how else can I get the href clicked into a usable variable?
To reiterate: I'm populating a listview with data from a mySQL DB. I need a way of knowing which link or listview is clicked so I can POST it along with other form data.
I have a sign up dialog box, which has a login form in it.
I have done some basic form validation in the same file as the form, if errors exist then appropriate messages are echo'd out underneath the fields when the form is submit.
However when the form is submit, the page is refreshed and the dialog box closes, it has to be opened again for the user to see the errors. This is not very appropriate and I want to somehow keep the dialog box open on refresh, only IF errors exist in the form validation.
There must be a way around this but I don't quite know how to implement this.
Here is my code (index.php):
// PHP validation
$fornameErr = $surnameErr ="";
$forname = $surname="";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["forename"])) {
$fornameErr = "Missing";
}
else {
$forename= $_POST["forename"];
}
if (empty($_POST["surname"])) {
$surnameErr= "Missing";
}
else {
$surname= $_POST["surname"];
}
}
// Link which opens up the dialog box by calling the 'check_domain_input()' function
<div id="clickable" onclick="check_domain_input()">Or sign up</div>
// The form in the dialog box
<div id="dialog" title="Sign up" style="display:none">
<center>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div align="center">
<br/>
<input type="text" class="input" name="forename" size="20" maxlength="40" placeholder="Forename" value="<?php echo htmlspecialchars($forename);?>"/>
<span class="error"><?php echo $fornameErr ;?></span>
<br/>
<input type="text" class="input" name="surname" size="20" maxlength="40" placeholder="Surname" value="<?php echo htmlspecialchars($surname);?>"/>
<span class="error"><?php echo $surnameErr ;?></span>
<br/>
<input type="submit" value ="Sign up" class="submit"/>
<br/>
<br/>
</div>
</form>
</center>
</div>
<!-- Dialog box function -->
<script>
function check_domain_input()
{
$( "#dialog" ).dialog({modal: true});
var domain_val = document.getElementsByName('domain');
if (domain_val[0].value.length > 0)
{
return true;
}
$( "#dialog" ).dialog({modal: true});
return false;
}
</script>
You could call your check_domain_input method as the page loads if you've got an error to show, like this:
<script>
function check_domain_input()
{
...
}
<?php if (!empty($fornameErr) || !empty($surnameErr)) : ?>
$(function() {
check_domain_input();
});
<?php endif; ?>
</script>
You can use onsubmit="return validateFunction()" as shown at this link.
You can have PHP set a JavaScript variable that your jQuery onload function reads and reacts to.
You can use AJAX instead of form submissions. With AJAX, you can simply use the AJAX call's error function to react to bad validation.