I have a variable $form in PHP and want it to be called or displayed whenever I hover a button.
I am a novice in ajax and don't know how to call the variable on hovering the button.
The code is:
Javascript
<script type="text/javascript">
$(document).ready(function() {
$("#login_button").hover(function() {
$("login-form").slideDown(400);
});
$("#login_button").hover(function() {
$("login-form").css('visibility','visible');
});
$("#login_button").dblclick(function() {
$("login-form").slideUp(1200);
});
$("#login-form").mouseleave(function() {
$("login-form").slideUp(1000);
});
});
</script>
PHP
<?php
$form = "<form action='?' method='post' id='login-form' name='login-form'><!-- class='form-horizontal well' -->
<strong><legend>Login</legend></strong>
<fieldset id='inputs'>
<input type='text' placeholder='Username' name='name' class='input-large' id='username'>
<input type='password' placeholder='Password' name='password' class='input-large' id='password'>
</fieldset>
<fieldset id='actions'>
<input type='submit' id='submit' class='btn btn-primary' value='Sign in'>
<div class='forgot'>
<strong><a href='?forget=1' id='forget'>Forgot Password?</a></strong>
</div>
</fieldset>
";
?>
You can using jquery post to get value and send it to your url :
$("#yourID").hover(function(){
$("fomr").css({visible:visible});
var url = "your-url-here";
var username = $("#input-for-username").val();
var password = $("#input-password").val();
//init ajax post
$.post(url,{username:username,password:password}.function(data){
//any thing here
});
});
No AJAX required;
$(document).ready(function() {
var php_var = '<?php echo json_encode($form); ?>';
});
Use it like:
$('#element').hover(function() {
$('#form_container').html(php_var);
}, function() {
$('#form_container').html('');
});
php is server-side and javascript (like html) is client-side.
What you have to do is display the content of $form in your page inside a hidden container, then use a trigger to display it:
<div id="login-form" style="display:none"><?php echo $form; ?></div>
For the js part, I simplify your example:
$("#login_button").hover(function(e) {
$("#login-form").slideDown(400);
},
function(e) {
$("#login-form").slideUp(1200);
});
jquery.hover doc
Notice the current version of jquery use this syntax:
$(document).on("hover", "#login_button", function(e){
// your commands here
});
Related
Actually, i making a form and have many buttons in the form so I want to know that how it can be done whether when I click the button during form submission it will store that button value and after click to the final submit button a mail will send all input field values including button values that I have clicked.
<script type="text/javascript">
$(document).ready(function() {
$('#frmemail').submit(function(event) {
$.ajax({
type: 'POST',
url: '',
data: $('#frmemail').serialize(),
success: function() {
$('.success').fadeIn(1000)
}
});
});
});
</script>
<?php
if (isset($_POST['garden']))
{
$but= $_POST['garden'];
}
?>
<?php
$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];
$garden = $_POST['garden'];
$to = "admin#rsfcrm.com";
$subject = "RIA Emails";
$body = "Name: ".$name."\nEmail: ".$email."\nGarden".$but."\nMessage:".$message;
$headers = "From: ". $email;
if (mail($to,$subject,$body,$headers))
{echo "<script>window.alert('Successfull!');
</script>";
}else
{echo "<script>window.alert('Fialed');
</script>";
}?>
<div class="container">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<form enctype="multipart/form-data" id="frmemail" method="post" action="test2">
<fieldset class="margin-b">
<legend>Contact Me</legend>
<label for="form_name">Name:<input name="form_name" type="text" value="" required autofocus ></label>
<label for="form_email">Email:<input name="form_email" type="email" value=""></label>
<label for="form_msg">Message:<textarea name="form_msg" rows="5"></textarea></label>
</fieldset>
<button type="submit" id="garage" name="garden" value="gardening">button</button>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</section>
</div> </body>`
You can use jquery and hidden variable functionality.
like on first button click store value in hidden field and on second button click submit form. if you want code then i can paste here
<input type='hidden' name='garage_val' id='garage_val' value='' />
<script>
$("#garage").click(function(){
$("#garage_val").val($(this).val());
});
</script>
In your form add this input field
<input type='hidden' name='gardening' value='gardening' />
In your Php code
<?php
$gardening= $_POST['gardening'];
echo $gardening;
?>
Jquery
$('#frmemail').submit(function(event) {
$.ajax({
type: 'POST',
url: 'yourphpfilename.php',
data: $('#frmemail').serialize(),
success: function() {
alert(data)
}
});
});
No jquery click functions are required to do this,this value will be passed along with the form,hope this helps
(Or)
If you wish the value to be passed only on button click use this
Html
<input type='hidden' name='gardening' class="hidden"/>
Jquery
$("#garage").click(function(e)
{
e.preventDefault();
$('.hidden').val('gardening');
});
This code almost works, it inserts into the db and it is giving feedback on the page to say it has updated. However I am getting undefined index between lines 5-8 in the insert_message.php and my database is filling with blank entries (except the date).
Apologies for being new to jquery and AJAX. Need some help.
form
<form enctype='multipart/form-data' action='insert_message.php' method='POST' id='contact_form'>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='email'>Email:</label>
<input class='form-control' type='email' id='email' name='email' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6">
<div class='form-group'>
<label for='subject'>Subject:</label>
<input class='form-control' type='text' id='subject' name='subject' required='required' maxlength='35'/>
</div>
</div>
</div>
<div class="form-group">
<label for='message'>Message:</label>
<textarea class="form-control" placeholder="Message" id='message' required="required"></textarea>
</div>
<input type="hidden" name="reciever" id='receiver' value="Admin">
<input class='btn btn-primary' id='submit' type='submit' value='submit' >
</form>
<span id="result"></span>
jquery
<script>
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
var message1 = $('message').val();
var sender1 = $('sender').val();
var receiver1 = $('receiver').val();
var subject1 = $('subject').val();
$.post("insert_message.php", {message:message1, sender:sender1, receiver:receiver1, subject:subject1}, function(info) { $("#result").html(info);
});
clearInput();
});
$("#contact_form").submit( function() {
return false;
});
function clearInput() {
$("#contact_form :input").each( function() {
$(this).val('');
});
}
});
</script>
insert_message.php
<?php
include("connections/conn.php");
$getsubject = mysqli_escape_string($conn,$_POST["subject1"]);
$getmessage = mysqli_escape_string($conn,$_POST["message1"]);
$getsender = mysqli_escape_string($conn,$_POST["sender1"]);
$getreceiver = mysqli_escape_string($conn,$_POST["receiver1"]);
$date = date("Y-m-d");
$insertmessage = "INSERT INTO messages (id,subject,message,date,sender,receiver) VALUES (NULL,'$getsubject','$getmessage','$date','$getsender','$getreceiver')";
$insert = mysqli_query($conn, $insertmessage) ;
if($insert){
echo "Message Sent";
}else{
echo "Message did not send";
}
UPDATE
attempted alternative way but I still get the undefined index in the inser_message.php
$(document).ready(function(){
$("#submit").click( function(e) {
e.preventDefault();
$.ajax({
url: "insert_message.php",
type: "POST",
data: $("#contact_form").serialize(),
success: function(result){
$("#result").html(result);
}
});
});
});
You have several problems in both JS and PHP.
Adjust typo in input hidden where actually name="reciever" instead of name="receiver";
In your $("#submit").click() function you're trying to selecting elements with an invalid selector (e.g. $('message').val() instead of $("#message").val());
Adjust $_POST keys by removing 1 at end. If you have any doubt, print the whole array print_r($_POST);
This is not an error but a suggestion. Since you require conn.php to do your job, I would use require instead of include.
Remove the $conn and the 1's from your 'get' block and, for example:
$getsubject = mysqli_escape_string($_POST["subject"]);
$getmessage = mysqli_escape_string($_POST["message"]);
$getsender = mysqli_escape_string($_POST["sender"]);
$getreceiver = mysqli_escape_string($_POST["receiver"]);
I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});
I am having a trouble while sending a value from an input element to Codeigniter controller by using ajax.
Since I have to use WYSIWYG editor (summernote), thus I can just receive the input inside a <script>. However when I press the submit button, it just reloads the current page rather than the one in the controller.
Here is my code:
PHP view
<section id="mainContent">
<form method="post">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit" onclick="myFunction()">
</form>
</section>
<script type="text/javascript">
function myFunction() {
var markupStr = $('#textbox').summernote('code');
alert(markupStr);
$.ajax({
type : 'POST',
url : "<?= site_url().'cintern/save'; ?>",
async : false,
data : {'iDes': markupStr},
success : function(data){
alert("Success!");
}
});
return false;
};
</script>
PHP controller
public function save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $this->input->post('iDes');
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}
Please help! Thank you in advance.
You should use onsubmit of <form> tag instead.
<section id="mainContent">
<form method="post" onsubmit="myFunction()">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
The reason is, if you handle the onclick of your <input type="submit">, you can't intercept request of <form> tag after submit data.
I hope this can help you.
Since you are using JQuery for the ajax I suggest you use it to capture the submit also.
Remove the inline onclick assignment. Give the form an id attribute.
<section id="mainContent">
<form method="post" id="target">
<input type="text" id="textbox" class="editor" name="textbox">
<input id="submit_btn" type="button" name="sutmit" value="submit">
</form>
</section>
Turn myfunction() into a 'submit' event handler
<script type="text/javascript">
$("#target").submit(function (event) {
var markupStr = $('#textbox').summernote('code');
//stop the normal submit from happening
event.preventDefault();
$.ajax({
type: 'POST',
url: "<?= site_url().'cintern/save'; ?>",
async: false,
data: {'iDes': markupStr},
success: function (data) {
//do stuff with data then redirect to 'after_save'
console.log(data.results, data.otherstuff);
window.location.href = "http://example.com/cintern/after_save";
}
});
});
</script>
Controller:
public function save()
{
$data = $this->input->post(NULL, TRUE);
// $data is now a semi-sanitized version of $_POST
$_SESSION['iDes'] = $data['iDes'];
//do other stuff with $data
echo json_encode(['results' => "success", 'otherstuff' => $foo]);
}
public function after_save()
{
$session_data = $this->session->userdata('logged_in');
$data['id'] = $session_data['idlogin'];
$data['role'] = $session_data['role'];
$data['pageTitle'] = 'Success';
$data['iDes'] = $session_data['iDes'];
$this->load->view('templates/header', $data);
$this->load->view('internship/success', $data);
$this->load->view('templates/footer');
}
I am trying to create a login test application using jquery post, php ..
It is reading the value but not sending the data to server.php and returning the data.
HTML CODE
<div class="contact-form pad-25">
<div class="subpage-title">
<h5>Please Login</h5>
</div>
<div>
<div class="row">
<div class="col-md-4">
<input class="form-control" placeholder="Name" type="text" id="fname" name="firstname">
<input class="form-control" type="password" placeholder="Pass" type="text" id="pass" name="password" style="display:none">
</div>
</div>
<a class="btn btn-flat flat-color btn-rounded" id="next_name">NEXT</a>
<button class="btn btn-flat flat-color btn-rounded" type="submit" id="submit" style="display:none">Submit</button>
<div>
<!-- row-fluid -->
</div>
//SCRIPT
<script type="text/javascript">
$(document).ready(function(){
$("#next_name").click(function(){
$("#fname").hide('slow');
$("#pass").show('fast');
$("#next_name").hide();
$("#submit").show();
$("#submit").click(function(){
var r=confirm("Login Confirmaition!!")
if(r==true)
{
//alert("asd");
var pass=$("#pass").val();
var fname=$("#fname").val();
alert(pass);
alert(fname);
$.post('server.php', {fname:fname, pass:pass, type:'passwordcheck'}, function(msg){
alert(msg);
});
}
});
});
});
</script>
SERVER SIDE CODE
I tried to dump the data but the application is not reaching the server.php at all
<?php
//echo "asdasd";
$type=$_POST['type'];
$fname=$_POST['fname'];
$pass=$_POST['pass'];
//var_dump($fname);
$data = '{"name":"Pramit", "password":"Pramit123"}';
if($type=='passwordcheck'){
$phpdata = json_decode($data);
if($phpdata->name == $fname && $phpdata->password == $pass)
{
echo "success";
}
else
{
echo "fail";
}
}
?>
In your script, you have an error.
<script type="text/javascript">
$(document).ready(function(){
$("#next_name").click(function(){
$("#fname").hide('slow');
$("#pass").show('fast');
$("#next_name").hide();
$("#submit").show();
$("#submit").click(function(){
var r=confirm("Login Confirmaition!!")
if(r==true)
{
pass=$("#pass").val();
fname=$("#fname").val();
//$.post('/server.php', {fname:fname, pass:pass, type:'passwordcheck'}, function(msg){
$.post('http://localhost/server.php', {fname:$fname, pass:$pass, type:'passwordcheck'}, function(msg){
alert(msg);
});
}
});
});
});
</script>
If you are in the same server where are you doing the request, you haven't got to insert the server, but if you put the server, i recommend you to put at least the protocol, because that request is doing on http://localhost/localhost/server.php, thats why you can't see the receive in the server part.
Remember too that in Javascript, variables are written like that:
var variable1;
variable = variable1;
Never put the variables like PHP, using the $ symbol
Tell me if that is useful to you :D
You are calling wrong url you must add http:// in your post url like,
$.post('http://localhost/server.php'...