I am trying to learn jQuery ajax the function seems to be working properly so says browser web developer tools but the values aren't pulled through to the php file(url) that I have here's my simple code.
This is the HTML anf jQuery File
<!Doctype HTML>
<html>
<head>
<title>Working with PHP and jQuery</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/jquery-1.11.3.min.js"></script>
</head>
<body>
<form id="#myForm">
<p>
<label>Enter your name</label>
<input type="text" name="Name">
</p>
<p>
<label>Are you male
<input type="checkbox" name="IsMale">
</label>
</p>
<p>
<label>Enter your email address</label>
<input type="email" name="Email">
</p>
<p>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</p>
</form>
<div id="loadResult"></div>
<script>
$(function() {
$('#submitButton').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'php/form1.php',
type: 'POST',
data: $('#myForm').serialize(),
success: function(result) {
console.log(result); $('#loadResult').html(result);
},
error: function(badresult){ alert("ajax error function hit"); console.log(badresult); }
});
});
});
</script>
</body>
</html>
And here's the php file
<?php
$name = $_POST['Name'];
$isMale = $_POST['IsMale'];
$email = $_POST['Email'];
echo "Name is $name, are you a male? $isMale. Your email address is $email";
?>
I am using the jquery serialize function but don't know where I am going wrong
Most likely what you're getting is this line blowing up
$isMale = $_POST['IsMale'];
And in your HTML we see
<input type="checkbox" name="IsMale">
Checkboxes, when they are not checked, are not successful, meaning they won't show up in $_POST. From the jQuery serialize manual
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. snip
Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked
So you need to check that it was submitted
$isMale = (isset($_POST['IsMale'])) ? 'Yes' : 'No';
Related
I am using Ajax with form in Ajax I have used a if condition for validation if my form is empty it should display a message that all fields are required and if fields are fill it should add data in dB and display a success message although everything is working perfectly except one thing which is that my output only display for a second and then automatically disappears can anyone help me in this regard:
`
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1>PHP & Ajax Seralize Form</h1>
<form id="form-data" method="post">
Name<br><input type="text" name="name" id="name" value=""><br><br>
Age<br><input type="number" name="number" id="age" value=""><br><br>
Gender<br>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Fe-male<br><br>
<select name="country">
<option value="Kashmir">Kashmir</option>
<option value="Egypt">Egypt</option>
<option value="Norway">Norway</option>
<option value="Iceland">Iceland</option>
</select><br>
<br><input type="submit" id="submit" value="Save">
</form>
<div id="response">
</div>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var name = $('#name').val();
var age = $('#age').val();
if( name== "" || age== ""){
$('#response').fadeIn();
$('#response').removeClass('success-msg').addClass('error-msg').html("All fields are required");
}else{
$.ajax({
url: 'save-form.php',
type: 'POST',
data: $('#form-data').serialize(),
success: function(result){
$('#response').fadeIn();
$('#response').removeClass('error-msg').addClass('success-msg').html(result);
}
});
}
});
});
</script>
</body>
</html>
`
probably your page is refreshed, try to use preventDefault to prevent the refresh
$('#submit').click(function(event){
//your code here
event.preventDefault();
}
You have a button with type "submit".
<input type="submit" id="submit" value="Save">
As the click-event occurs on this button, your form will be send to the server. You have no action attribute defined on your form, so it redirects after submit to the same URL.
As Sterko stated, you could use a event-handler to prevent the submission of your form due to the submit button.
i write sample code to ajax post javaxcript varible to php in 2 page, test.php and validate.php.
test.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.min.js" ></script>
</head>
<body>
<form>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit" onclick="post();">
</form>
<div id="result" ></div>
<script type="text/javascript">
function post()
{
var name=$('#name').val();
var age=$('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data)
{
if (data=="1")
{
$('#result').html('you are over 18 !');
}
if (data=="0")
{
$('#result').html('you are under 18 !');
}
});
}
</script>
</body>
</html>
validate.php
<?php
$name=$_POST['postname'];
$age=$_POST['postage'];
if ($age>=18)
{
echo "1";
}
else
{
echo "0";
}
?>
how can i write/change above code in same page ?? and validate.php insert in test.php ??
added after first answer :
"but i dont have/use any button or in my page.
and where can i insert validate.php code in test.php. please help by insert complete correct code."
Try adding a submit() method to your <form> rather than attaching the event to the submit button.
$(document).on('submit', 'form', function(){
post();
return false;
});
At the moment I think your form is submitted no matter what, you have to either return false on submit or preventDefaults()
A good idea is also to add an ID to your form in case you have more than one on your page and use the relevant selector in the .on event handler such as
$(document).on('submit', $('#form-id'), function(){ ... });
ajax is use for exchanging data with a server. If you want write code in same page so reload page and write validate.php code above of test.php like this
<?php
//validate.php code
?>
<form action=test.php type=POST>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit">
</form>
I have an HTML file that has a form with two fields. These fields' value should be posted to a PHP and this PHP should be fetched from the HTML using JQuery. This is what I implemented.
My HTML file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#first").load("result_jquery.php");
});
});
</script>
</head>
<body>
<div id="first"></div>
<div>
<form method="POST" id="myForm">
Name: <input type="text" name="name"/><br/>
Number: <input type="text" name="number"/><br/>
<button>submit</button>
</form>
</div>
</body>
This is my result_jquery.php
<?php
$n = $_POST["name"];
echo "hello ".$n;
?>
When I click the submit button, the hello is getting printed. But the name is not getting printed. Can you please help me with this. I don't know where I am going wrong.
I think that the use of the button element is the worry and the code that i will put now it is working properly as you need so try this and tell me the result :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
var n = $('[name="namee"]').val();
var nb = $('[name="number"]').val();
$("#first").load("result_jquery.php",{'namee':n,'number':nb},function(data){});
});
});
</script>
</head>
<body>
<div id="first"></div>
<div>
<form method="POST" id="myForm">
Name: <input type="text" name="namee"/><br/>
Number: <input type="text" name="number"/><br/>
<input type="button" value="Submit" id="button" />
</form>
</div>
</body>
</html>
copy this code:
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
$.ajax({
type: "POST",
data : "name="+$( '#name' ).val(),
url: "result_jquery.php",
success: function(msg) {
$('#first').html(msg);
}
});
});
});
</script>
change this in form
<form method="POST" id="myForm">
Name: <input type="text" id="name" name="name"/><br/>
Number: <input type="text" id="number" name="number"/><br/>
<input type="button" id="send" value="Submit">
</form>
just try that and tell me the result :)
var n = $('[name="name"]').val();
var nb = $('[name="number"]').val();
$('#error').load("result_jquery.php", {'name':n,'number':nb},function(data){});
Note try to change the element name for the name field from "name" to "namee" and apply changes as needed look like this :
var n = $('[name="namee"]').val();
var nb = $('[name="number"]').val();
$('#error').load("result_jquery.php", {'namee':n,'number':nb},function(data){});
and the result_jquery.php file :
<?php
$n = $_POST["name"];
echo "hello ".$n;
?>
From the jQuery documentation on load:
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data. This means that most uses of the
method can be quite simple:
You are performing a HTTP GET with that method, and not a POST.
My suggestion would be if you want to send an AJAX request to your server with information in it, get used to using the long form jQuery AJAX:
$.ajax({
data: 'url=encoded&query=string&of=data&or=object',
url: 'path/to/server/script.php',
success: function( output ) {
// Handle response here
}
});
For more info, see jQuery documentation: http://api.jquery.com/jQuery.ajax/
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'];
I have a form that calls a php script on submit to insert data into a MySQL database. I would like the output of the php script return to a greybox. I haven't been able to make it work so I appreciate any help you guys can provide.
I have the greybox call on the form definition see below but is not doing the trick.
Here is a subset of the code:
<script type="text/javascript" src="greybox/AJS.js"></script>
<script type="text/javascript" src="greybox/AJX_fx.js"></script>
<script type="text/javascript" src="greybox/gb_scripts.js"></script>
<div id="content">
<form id="contact_us" name="contact_us" action="contact-greybox.php" method="POST" onSubmit="return GB_showCenter('Testing', this.action, 500, 500)">
<fieldset>
<label for="employee_id">Employee ID:</label>
<input id="employee_id" name="employee_id" type="number" size="10" /><P />
<label for="employee_name">Employee Name:<strong><br /> (as it should appear on
email) </strong></label>
<input id="employee_name" name="employee_name" type="text" /><P />
</fieldlist>
<p class="submit"><input type="image" name="submit" value="Submit Form" src="icons/ambas_submit.jpg" boder="0">
</form>
</div>
The php is a simple insert statement into MySQL.
Appreciate any help
greybox doesn't support POST submits, but the general pattern is to use ajax to submit the form- otherwise your page will refresh.
You need to set an onclick( $.submit ) to the form input then return false at the end of your ajax call:
$('#contact_us').submit(function(){
//get your inputs here
var e_id = $.('#employee_id').val();
//...etc....
$.post( ...
//set your data/input fields here:
data: { id: e_id },
success: function(response){
//display the response: this is what you get back from: contact-greybox.php
}
})
return false;
});
fancybox is an overlay box that supports being called with pure html as a parameter, so that you can just put this in your success function:
$.fancybox(response);
...or
$.fancybox(response.html)... etc.