Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});
Related
I having multiple forms in a single page submitting via jQuery ajax. All forms use same class names. Also i am using malsup jquery plugin for form submission.
I can successfully pass the data to a php file but the error message is reflecting on all forms div.message. I don't want to have different form ids because i need to have all ids in the jquery then.
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
<form class="myform" method="post" action="process.php">
<input type="text" value="" >
<input type="submit" value="Submit" >
<div class="message"></div>
</form>
jQuery part
<script>
$(document).ready(function() {
$('.myform').on('submit', function(event) {
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
$('div.message').append('<div>'+message+'</span>');
}
}
});
});
});
</script>
How can i append the error message to the submitted form's div.message correctly?
Any help will greatly appreciated.
I think you can get the msg div before post .
$(document).ready(function() {
$('.myform').on('submit', function(event) {
msgDiv=($this).children('div.message');//before post get the msg div first
event.preventDefault();
$(this).ajaxSubmit({
url: 'process.php',
type: 'post',
dataType: 'json',
success: function( response ){
$.each(response, function(){
msgDiv.append('<div>'+message+'</span>');
}
}
});
});
});
</script>
issues are still there...pls help
I am unable to load external file while using AJAX jquery. I want to use Jquery ajax to pop up form then validate, enter data in mysql. but starting from a simple ajax function. kindly let me know where i am going wrong
<link rel="stylesheet" type="text/css" media="all" href="test_style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
});
});
</script>
</head>
<body>
<div id="contact_form">
<form id="ajax-contact-form" name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<INPUT class="button" type="submit" name="submit" value="Send Message">
</fieldset>
</form>
</div>
</body>
</html>
and contact.php file is
<?php
echo "Hello";
?>
You need to return false; to prevent the form from submitting and refreshing the page and check if your $("#div1") is missing.
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax(
{
type: "POST",
url:"contact.php",
data: str,
success:function(result)
{
$("#div1").html(result);
}
});
return false;
});
});
Simple. Since you are posting your form through ajax, you must prevent the default form submit by returning a false inside the submit method. Below is the correct version:
<script>
$(document).ready(function(){
$("#ajax-contact-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url:"contact.php",
data: str,
success:function(result) {
$("#div1").html(result);
}
});
return false;
});
});
</script>
You can use a more simple form of post request as follows:
$.post("url",{var1: value1, var2: value2},function(data,status){
if(status=='success')
alert(data);
});
the second argument you can pass as many using this post request. The first argument url, if ofcourse relative to the document in which this js is loaded or you can give the exact url on the server.
According to your php file, data=='Hello'.
Similar is the procedure for any GET request also.
Make sure you are missing the div1
please use
<div id="div1"><div>
I've been at this for hours, and i'm at a complete loss.... I've tried everything I can but the problem is that i'm not very familiar with Jquery, this is the first time I've ever used it.... Basically, i'm attempting to pass form data to a php script, and then return a variable which will contain the source code of a webpage.
Here is the jquery:
$("button").click(function(){
hi = $("#domain").serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: hi,
//dataType: "text",
success: function(data){
page = data;
document.write(page);
}
});
});
Here is the html it references:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="domain" id="domain_label">Name</label>
<input type="text" name="domain" id="domain" size="30" value="" class="text-input" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
Here is the PHP that process it:
$search = $_POST["domain"];
if(!$fp = fopen($search,"r" )) {
return false;
}
fopen($search,"r" );
$data = "";
while(!feof($fp)) {
$data .= fgets($fp, 1024);
}
fclose($fp);
return $data;
?>
I think the variable $search is blank, but is that because i'm not sending it correctly with jquery or receiving it correctly with php? Thanks!
Well, when you serialize form data using jQuery, you should serialize the <form>, not the <input> field.
So try this:
$("button").click(function() {
var formData = $('form[name="contact"]').serialize();
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: formData,
success: function(data) {
page = data;
document.write(page);
}
});
});
See you have to do several things:
$("form[id='contact_form']").submit(function (e) {//<---instead click submit form
e.preventDefault(); //<----------------you have to stop the submit for ajax
Data = $(this).serialize(); //<----------$(this) is form here to serialize
var page;
$.ajax({
type: "POST",
url: "webcrawler.php",
data: Data,
success: function (data) {
page = data;
document.write(page);
}
});
});
So as in comments:
Submit form instead button click
Stop the form submission otherwise page will get refreshed.
$(this).serialize() is serializing the form here because here $(this) is the form itself.
I'm trying to send post variables to php himself document via jQuery ajax, but after send, the post vars are not set.
the code:
if(isset($_POST['email']) && isset($_POST['pass'])){
do something
}
<form id="form_login_pv">
Email: <input type="text" name="email" id="email"><br>
Password: <input type="password" name="pass" id="pass">
<div class="send_login_button_pv">Login</div>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e){
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
});
</script>
why dont you try to use form submit jquery function.
if(isset($_POST['email']) && isset($_POST['pass']))
{
//do something
}
<form id="form_login_pv" action="<?php echo $_SERVER['PHP_SELF'] ?>">
Email: <input type="text" name="email" id="email">
Password: <input type="password" name="pass" id="pass">
<button type="submit" class="send_login_button_pv">Login</button>
</form>
<script type="text/javascript">
$('.send_login_button_pv').click(function(e)
{
e.preventDefault(); // just to make sure it wont perform other action
$("#form_login_pv").submit(function(){
//afte server response code goes here
});
});
</script>
Make sure form must have action set.
$.ajax({
type: "POST",
url: "index.php",
data:$('#form_login_pv').serialize(),
success: function(response){
alert("mensaje enviado");
}
});
Try this in jQuery ready event:
//you can also use an <input type="submit" value="login" /> instead ofusing a button!
$("#button_id").on("click",function(e){
$("#form_login_pv").submit();
return e.preventDefault();
});
$("#form_login_pv").submit(function(e) {
var email = $('input[name=email]').val();
var pass = $('input[name=pass]').val();
// validate given values here
// if bad value detected, output error and return false;
if(!email.test(YOUR REGEX HERE)) {
$('#error-message').text('Wrong E-Mail Format!');
return false;
}
if(pass.length<6) {
$('#error-message').text('Password to short! At least 6 Characters!');
return false;
}
$.ajax({
type: "POST",
url: "index.php",
data: {
email: email,
pass: pass,
},
success: function(response){
alert("mensaje enviado");
}
});
return e.preventDefault();
});
And don't forget to pervent the form from submitting via HTTP Post!
You can do this by returning false at the end of your button click event.
Or by using a method of your event object e, e.preventDefault();
I suggest to return e.preventDefault(); at the end of your click function!
You also can check if given variables are empty or validate them with javascript, before submitting via ajax!
I've been racking my brains for days looking at examples and trying out different things to try and get my form to submit with Ajax without a page refresh. And Its not even sending the data now.. I don't know what I'm doing wrong..Can someone run through my ajax and form please.
Toid is the users id and newmsg is the text in which the user submits. The two values get sent to the insert.php page.
I would really appreate the help. I'm new to Ajax, and I look at some of it and don't have a clue. If I finally got it working, It may help me realize what I've done wrong. I am looking up tutorials and watching videos..but it can be very time consuming for something that would be simple to someone in the know on here. It maybe that I've got the wrong idea on the ajax and it makes no sense at all, sorry about that.
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
homestatus()
event.preventDefault();
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
});
return false;
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
</div>
</form>
INSERT.PHP
$user1_id=$_SESSION['id'];
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&isset($_POST['toid'])){
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
}else{
rawfeeds_user_core::create_streamitem("3",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
Try using firebug to identify bugs in your code. It's a really good companion for developing javascript. Nearly all of your bugs led to error messages in the firebug console.
You had several errors in your code, here is the corrected version:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){alert('success');}
});
});
});
And here the corrected html:
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
Actually onsubmit event has to be used with form so instead of
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
it could be
<form id="myform" method="POST" class="form_statusinput" onsubmit="homestatus();">
and return the true or false from the function/handler, i.e.
function homestatus()
{
//...
if(condition==true) return true;
else return false;
}
Since you are using jQuery it's better to use as follows
$("form#myform").on('submit', function(event){
event.preventDefault();
var toid = $("#toid").val(); // get value
var content = $("#newmsg").val(); // get value
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + toid + "&newmsg=" + content,
success: function(data){
// do something with data
}
});
});
In this case your form should be as follows
<form id="myform" method="POST" class="form_statusinput">
...
</form>
and input fields should have a valid type and value attribute, Html form and Input.
I think you should read more about jQuery.
Reference : jQuery val and jQuery Ajax.
change the form to this
<form id="myform" ... onsubmit="homestatus(); return false">
you don't need the onsubmit attribute on the submit button, but on the form element instead
homestatus might be out of scope
function homestatus () {
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
}
This isn't tested, but try this (I annotated some stuff using comments)
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
// not sure what this does, so let's take it out of the equation for now, it may be causing errors
//homestatus()
// needed to declare event as a param to the callback function
event.preventDefault();
// I think you want the value of these fields
var toid = $("#toid").val();
var content = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+toid +"&newmsg="+ content,
success: function(){
}
});
return false;
});
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" / >
</div>
</form>
It's a lot easier to let .serialize() do the work of serializing the form data.
The submit handler also needs event as a formal parameter, otherwise an error will be thrown (event will be undefined).
With a few other changes, here is the whole thing:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
homestatus();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: formData,
success: function(data) {
//...
}
});
});
});
</script>
<form id="myform" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" >
</div>
</form>
Unless you are omitting some of your code, the problem is this line:
homestatus()
You never defined this function, so the submit throws an error.
You may want to take a look at jQuery (www.jquery.com) or another js framework.
Such frameworks do most of the stuff you normally have to do by hand.
There are also a bunch of nice helper functions for sending form data or modifying html elements