I want to use ajax to add data in the database but nothing happens
i don't know whats wrong is it in the ajax!or in the php
This is part of my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
$("#commentForm").submit(function(){
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context},
});
});
});//end of document ready function
</script>
this the html form:
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name = "context" class="form-control" id="inputmessage" rows="3" placeholder="Enter your comment here . . "></textarea>
</div>
</div> <!-- End of /.form-group -->
<input type="hidden" value = "$Item['Item_Name']" name="I_name"/>
<input type="hidden" value ="$U_N" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary" ;>Send</button>
</div>
</div>
</form>
and this is a part of the php page for adding to the database
extract($_POST)
if(isset($context))
{
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}
var U_N = $("input#U_N").val();
var I_name = $("#I_name").val();
var context = $("#context").val();
The jQuery selectors are wrong, you're not selecting anything. The # selector stands for id attribute, but you're trying to select by value of name attribute. You should either add/change id attributes of your input fields, or use
var U_N = $("input[name=U_N]").val();
var I_name = $("input[name=I_name]").val();
var context = $("[name=context]").val();
Tip: next time use developer console inside your browser, you can easily test if selectors are correct. You can type in javascript code as you would inside .js file and test if it's working like you expect.
Also, don't do this in your PHP, use prepared statements.
Did you included you Database conection on your Backend script?
extract($_POST)
'if(isset($context)) {
mysql_query("INSERT INTO menu_commnet VALUES('$I_name','$U_N',NULL,NOW(),'$context')");
}'
i think here you should include you database info, 'include_once("database info.php"); , also make sure you ajax will return a result, and echo php errors, just to be sure its an ajax or php error,
I have few comment regarding your issue :
Replace $("document").ready(function(){ with
$(document).ready(function(){
Before extracting in PHP ,
try var_dump($_POST)
Based on your HTML code use:
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
Here is final working example. Just add "ev" argument to submit callback function , then use ev.preventDefault() in it.
$(document).ready(function(){
$("#commentForm").submit(function(ev){
ev.preventDefault();
var U_N = $('input[name="U_N"]').val();
var I_name = $('input[name="I_name"]').val();
var context = $("#inputmessage").val();
$.ajax({
type: "POST",
cache: false,
url : "aAddComm_Menu.php",
data : {U_N:U_N,I_name:I_name,context:context}
});
});
});//end of document ready function
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" role="form" id="commentForm" method="POST" action="">
<div class="form-group">
<label for="inputmessage" class="col-sm-2 control-label">comment</label>
<div class="col-sm-10">
<textarea name="context" class="form-control" id="inputmessage" rows="3"
placeholder="Enter your comment here . . "></textarea>
</div>
</div>
<input type="text" value="" name="I_name"/>
<input type="text" value="" name="U_N"/>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button name="SendC" type="submit" class="btn btn-primary">Send</button>
</div>
</div>
</form>
Related
I have a very simple form that has an input field for first name. I captured the form data and transmitted it via ajax to a PHP page using the standard jQuery posting method. However, I am not able at all get any responses from the PHP page that any data was captured on the server-side. I am not sure what I have done wrong or what is missing.
Here is my code.
Form:
<form action="process.php" method="POST">
<div class="form-group">
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
<div class="d-none" id="firstName_feedback">
<p>Please enter a first name.</p>
</div>
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
Here is my Jquery Ajax call:
<script>
$(document).ready(function() {
$('form').submit(function(event) {
var formData = $("form").serialize();
console.log(formData);
$.ajax({
type: 'POST',
url: 'form.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
And here is my PHP page:
if(isset($_POST['formData']))
$ajaxData = ($_POST['formData']);
echo $ajaxData;
{
}
In your Ajax function, you're passing the contents of formData to the server, though not as formData but as their original input name.
In this case, you have:
<input type="text" class="form-control" name="firstName" id="firstName" placeholder="First name">
The input's name is firstName, so you need to call $_POST['firstName'] instead of $_POST['formData'].
if (isset($_POST['firstName'])) {
$ajaxData = $_POST['firstName'];
echo $ajaxData;
}
The same applies for any other field you would have in your form, so for example, having another input with the name lastName means you'd have to call $_POST['lastName'] to access it.
There were also some misplaced brackets and parentheses in the PHP code which I accommodated above.
I am trying to have my all my text/email input forms have a required attribute before you can "Submit" The email
But since I am using some Ajax to keep the page from refreshing after pressing the button the required attribute will not work.
This is why I am asking for an alternative for required with Javascript or jQuery (trying to prevent email form spam).
HTML (FORM)
<form id="contact">
<div class="form-group">
<label for="name">Voornaam*</label>
<input name="fn" type="text" class="form-control" id="fn" required>
</div>
<div class="form-group">
<label for="name">Achternaam*</label>
<input name="ln" type="text" class="form-control" id="ln" required>
</div>
<div class="form-group">
<label for="email">Email-address*</label>
<input name="email" type="email" class="form-control" id="email" required>
</div>
<div class="form-group">
<label for="message">Bericht*</label>
<textarea name="message" required class="form-control" id="message" rows="6"></textarea>
</div>
<button type="button" onClick="doIets(); this.form.reset();"
name="submit" id="submit" class="btn btn-primary">Verstuur <span id="result"></span></button>
<div id="result2"></div>
</form>
Ajax script
<script type="text/javascript">
function doIets()
{
console.log("doe iets");
var data = {
ck: (new Date()).getTime(),
fn: $("#fn").val(),
ln: $("#ln").val(),
email: $("#email").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "sendmail.php",/*php file path*/
data: data,
beforeSend: function(){
$('#result').html('<img src="loader" style="height:10px;"/>')
},
success: function(data){
$('#result').hide();
$('#result2').html(data);
}
});
}
</script>
You will need to use e.preventDefault() when they click on the submit button and then validate the form and after that submit it using the ajax call you created above.
since you already read out the data, you can check whether your message is long enough for you via
data.message.length
if it is 0 (or lower than a threshold you defined), you can skip the ajax call and return some info to the user.
You might also want to trim the message first in order to be sure there aren't only whitespace in there.
Here is part from my code, where I bind the submit event to my form and check by looping if any required field is empty or if I want to do any such thing.
This way may help you--
$('.form .contact-form').submit(function(e) {
e.preventDefault();
$('.form .message').eq(0).html("<i>Sending... Please Wait...</i>");
var form = $(this);
var validated = true;
$('input[type="text"]',this).each(function(){
if($(this).val().length < 1){
$(this).addClass('error').focus();
validated = false;
return false;
}
});
if(validated === true){
$.post(__asyn.ajaxurl, $('.form form').eq(0).serialize(), function(data, textStatus, xhr) {
console.log(data);
});
}
});
Just pass the event object to your handler onClick="doIets(event);
and then add
function doIets(event) {
event.preventDefault();
...
}
I am working as junior web master maybe that's why I have come with a simple question here. I have designed a single page application for client which has contact form at the end of page, validation is done using bootstrap but to send form data to mail id only method I know is using php with action directing different page. since my website is single page application i would like a popup on successful submission to mail id
Below is the HTML code for the contact form
<form class="form-inline" data-toggle="validator" role="form" method="post" id="enquiry" action="index.php">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail3">Name</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail3" placeholder="Name" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Mobile Number</label>
<input type="text" class="form-control" id="exampleInputPassword3" name="mobile" placeholder="Mobile Number" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword3">Email Id</label>
<input type="email" class="form-control col-lg-12" id="exampleInputPassword3" name="email" placeholder="Email Id" required>
</div>
<br/> <br/>
<div class=" col-lg-12 form-group">
<textarea cols="80" placeholder="Enter query Here" class="form-control" name="query" id="address" data-error ="Please Enter Your Query" required></textarea><br/><br/>
</div>
<button style="background-color:#f15a24; color:#FFF;" name="submit" id="submit" type="submit">Submit</button>
</form>
Can use php to send form data and still get a pop up in same page?
Or do I need to use jquery to send data and pop-up?
It would be great if somebody helps me out with code, thanks in advance
Updated
below(index.php page) i have added the code what you have given,
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.easing.min.js"></script>
<script src="js/jquery.fittext.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/creative.js"></script>
<script src="js/validator.js"></script>
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success"){ alert("Success"); }else{ alert("Failed"); }
//Failure message if ret is false
});
}
});
});
</script>
Add this js to your script
<script>
$(document).ready(function(){
$("#enquiry").on("submit",function(e){
e.preventDefault();
var dataString = $('#enquiry').serialize();
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(ret) {
if(ret === "Success")
{
alert("Success");
} else {
alert("Failed");
}
}
});
}
);
});
submit.php contains the code to send and exit it with the success (true) or failure (false) message. That will be caught in ret variable.
Edited
This will be more detailed answer I was looking for, I thought it be would be helpful for somebody so I have answered my own question as an alternative solution, check out the links below.
Show submitted form response on the same page. (No Reload)
http://www.9lessons.info/2009/04/submit-form-jquery-and-ajax.html
I'd like to use the autocomplete widget to make a search bar that will go through a userlist which is stored in a database. I'm using MySQL.
I tried the autocomplete with a local source (a JS array), and it works. But with my PHP script, it doesn't.
Why ?
Here's my HTML code :
<form method="get" action="" class="form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="InputSearch">Search Engine</label>
<input type="email" class="form-control" id="InputSearch" placeholder="Search a member...">
<button type="submit" class="btn btn-success">Search</button>
</div>
</form>
Here's my jQuery code :
$(document).ready(function() {
$(function() {
$( "#InputSearch" ).autocomplete({
source: "search.php",
dataType: 'json'
});
});
});
And here's my search.php code :
$term = trim(strip_tags($_GET['term']));
$sQuery = "SELECT `name` FROM `user` WHERE `name` LIKE '%$term%'";
$aUsers = DBOperation::queryGetMulti($sQuery);
echo json_encode($aUsers);
DBOperation is a class I use for Database queries, in this case it will simply return an array containing every line it reads in subarrays. It has been used in many other cases and works fine.
Thanks.
I'm working on phonegap, basically its like making mobileapps crossplatform by using HTML, JS and CSS. On the device i currently have the JS and the HTML (form) in same document.
What I'm trying to do is to pass email and password to my server, and then process it there through a login. I've tested the login script on the server and it works with hardcoded data. So I'm guessing somewhere when sending the data from the device its failing.. I'm fairly new to JS too.
I tried to hardcode the data in the AJAX but it doesnt seem to work. Preferebly I would like to use something like var pdata = $('#form').serialize(); or something else if its better.
Any ideas?
EDIT: Forgot to say that the PHP on the server auto submits by using JS when $_POST is set (isset)
The form
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="email" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-primary">Logg inn</button>
</form>
The javascript
<script>
function dologin() {
//var pdata = $('#form').serialize();
//alert(pdata);
$.ajax({
type: 'POST',
data: {email:"test#test.no",password:"test"},
url: 'LINK',
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
};
</script>
The PHP
<form id="form" method="post">
<!-- {{ Form::label('email', 'Email Address') }} -->
<div class="form-group">
<input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST['email'];?>">
</div>
<div class="form-group">
<!-- {{ Form::label('password', 'Password') }} -->
<input type="text" name="password" value="<?php if(isset($_POST["password"])) echo $_POST['password'];?>">
</div>
</form>
Are you able to hit your server via through phonegap?
If no then please check your config.xml for white list urls - change access control property to
access origin = "*"
Hopeful you will be able to hit your server with data.
You can use weinre to debug your app. That way you will be able to see if the request was placed from the app or not.
http://people.apache.org/~pmuellr/weinre/docs/latest/Home.html