Jquery - selecting items within forms and posting them - php

I have a simple html page below calling a global.js file the global.js file calls a php file that gets a location for a name if it is in a database. (could have put it all on the one page but was following a tutorial).
<!doctype html>
<html
<head>
<title>AJAX Database</title>
</head>
<body>
Name: <input type = "text" id="name">
<br />
<input type="submit" id="submit" value="Get Loc">
<div id="output"></div>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="js/global.js"></script>
</body>
</html>
global.js is :
$('#submit').on('click',function() {
var name = $('#name').val();
if($.trim(name) != ''){
$.post('ajax/name.php', {name: name}, function(data) {
$('div#output').text(data);
});
}
});
it works fine as is, but if I put in tags as shown below, it won't work. I also want to use a fieldset, but I can't even get it to work with form tags.
I have used other selectors but it won't work.
The problem seems to be the submit button, as it works if that is out of the form..
any ideas? I think using the submit within the form is getting the $.post function to send more than I want it too.
<!doctype html>
<html
<head>
<title>AJAX Database</title>
</head>
<body>
<form>
Name: <input type = "text" id="name">
<br />
<input type="submit" id="submit" value="Get Loc">
</form>
<div id="output"></div>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="js/global.js"></script>
</body>
</html>
the php file is:
if(isset($_POST['name']) === true && empty($_POST['name']) === false) {
require '../db/connect.php';
$query = mysql_query("
SELECT `names`.`location`
FROM `names`
WHERE `names`.`name` = '" . mysql_real_escape_string(trim($_POST['name'])) . "'
");
echo (mysql_num_rows($query) !== 0) ? mysql_result($query,0,'location') : 'Name not found';
}
Is my problem not using the right selectors, or is there some rule about using selectors for submit buttons within forms ?

You need to prevent the default action of the form. Either by using event.preventDefault() or adding return false at the end of the function.
$('form').on('submit', function(e) {
e.preventDefault();
var name = $('#name').val();
if ($.trim(name) != '') {
$.post('ajax/name.php', {
name: name
}, function(data) {
$('div#output').text(data);
});
}
});​

I strongly advise not to use the click of the button but instead I suggest this
<!doctype html>
<html
<head>
<title>AJAX Database</title>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="js/global.js"></script>
</head>
<body>
<form id="form1">
Name: <input type="text" id="name"><br />
<input type="submit" id="submit" value="Get Loc">
</form>
<div id="output"></div>
</body>
</html>
Where the script is
$('#form1').on('submit', function(e) {
e.preventDefault();
var name = $('#name').val();
if ($.trim(name) != '') {
$.post('ajax/name.php', {
name: name
}, function(data) {
$('div#output').text(data);
});
}
else {
alert('Please enter name');
$('#name').focus();
}
});​

Related

PHP submit form without refreshing

When the user submits the form, the result should be displayed without page refreshing. The PHP script is also in the same HTML page.
What is wrong withe $.post jQuery?
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btn").click(function(event) {
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $("#testform").serialize()
);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform">
<!-- $_SERVER['PHP_SELF'] array -->
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
You need to use event.preventDefault in your javascript
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $( "#testform" ).serialize()
);
});
Yes, you need e.preventDefault. Also, I think these var myname and myage variables are unnecessary since you're serializing the entire form in $.post.
Try this:
$(document).ready(function() {
$("#btn").click(function(e) {
e.preventDefault();
$.post(
"23.php", $("#testform").serialize()
);
});
});
Hope this helps.
Peace! xD
This is my finalized complete code after following your all suggestions. But it is still refreshing when getting results. Let's see if I have made any further error in the code. Thanks for your all helps.
UPDATE! - All these HTML and PHP scripts resides in the same file called 23.php
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform"> <!-- $_SERVER['PHP_SELF'] array -->
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
<input type="submit" name="submit" id="btn"/>
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { //was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>

Submit without refresh with 2 buttons

Hello so I have 2 submit buttons with different names (btn1, btn2) in my html form and what I am trying to do is to submit to another page without refreshing page. So what I wanted to do is if I click btn1 submit it will do something and if I click btn2 it will do another thing. My code in the html page is this
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'update.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1"> <input type="submit" name="btn2">
</form>
</body>
</html>
And the code in my update.php page
<?php
if(isset($_POST['btn1'])) {
//insert query
} else if(isset($_POST['btn2'])) {
//another insert query
}
?>
I actually got it working if I only have 1 submit button and no if(isset()) thing in the update.php page. What can I do to use 2 submits and with issets in another page without refreshing the main page?
$(this).serialize();
The above code statement doesn't include name of the submit button as a key value pair.
So, as people have suggested before me, you should use button instead of submit button. Something like this.
HTML and JS
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#btn1, #btn2').on('click',function(e) {
var datastr = $(this).serialize() + "&button_id="+$(this).attr('id');
$.ajax({
url:'update.php',
data:datastr,
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm" action="update.php">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<button id="btn1">Button1</button><button id="btn2">Button2</button>
</form>
</body>
</html>
AND PHP would be:
<?php
if($_POST['button_id'] == 'btn1') {
//do something
} else if($_POST['button_id'] == 'btn2') {
//do something else;
}
?>
Use this, may useful for you
try
$('#myForm').on('submit',function(e) {
e.preventDefault();
});
OR
<button type="button">
Use on click event on the button and add the value attribute to the submit button, the value of the click button will be pased to the php file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="submit"]').on('click',function(e) {
e.preventDefault();
$.ajax({
url:'update.php',
data:{'txt_amount':$('input[name="txt_amount"]').val(),'btn': $('input[type="submit"]').val()}
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1" value="btn1"> <input type="submit" name="btn2" value="btn2">
</form>
</body>
</html>
php:
<?php
if($_POST['btn'] == 'btn1') {
//do something
} else if($_POST['btn'] == 'btn2') {
//do something else;
}
?>

Can't see the expected result in a jQuery lab

The html code:
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript"
src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(msg) {
alert(msg);
$("#info1").html(data.msg);
}, "json");
});
});
</script>
</head>
<body>
<div id="info1">
Put the textbox input value into this block.
</div>
<br />
<form id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit"
id="submit" value="Submit Form" />
</form>
</body>
</html>
The php code:
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo json_encode($result);;
When I entered the text, it cannot display the same text above the input box. Maybe there have some wrong code, but I cannot find it, please help><
Reframed your code. Checkout,
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script>
$(function(){
$("form[id='form1']").on('submit', function(ev){
ev.preventDefault();
var th = $(this);
var data = th.serialize();
var action = th.attr('action');
$.post(action, data).done(function(response){
$("#info1").html(response.msg);
});
});
});
</script>
</head>
<body>
<div id="info1">
<!--Put the textbox input value into this block.-->
</div>
<br />
<form action="ex2_5.php" id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit" id="submit" value="Submit Form" />
</form>
</body>
</html>
ex2_5.php
<?php
$result = array();
if (!empty($_POST['form1']))
$result['msg'] = "<h1>".$_POST['form1']."</h1> is added";
else
$result['msg'] = "<h1>Field is empty!!</h1>";
header('Content-type: application/json');
echo json_encode($result);
Bugs:
1) ;; double semicolon
2) $_POST['form1'] in your PHP file
3) Wrong index using in JS while returning
Debugging:
Open console (Right click -> Inspect element -> Console tab) and checkout for errors
Solution 1:
Specify content type for ajax response as application/json. Otherwise the response will be a string not as json.
// Specify content type header as application/json
header('Content-type: application/json');
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo #json_encode($result);
Solution 2:
If header is not application/json then parse string into object using JSON.parse function.
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(data) {
var data = JSON.parse(data);
$("#info1").html(data.msg);
}, "json");
});
});
</script>

JS - submitting through javascript does not pass post variables

I am using Pure JS to first prevent the form from submitting then I have some validation code and finally automatic submission but the data is not passing from client side to server script.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Chat Room</title>
<link type="text/css" href="main.css" rel="stylesheet" />
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="container" class="add-nick">
<h3>Enter Your Name</h3>
<form action="chat.php" method="post" id="add-nicki">
<input type="text" placeholder="At least 6 alphabets e.g. Jackson" class="text" name="name" />
<input type="submit" value="Submit" class="submit" name="btnsubmit" />
</form>
</div>
</body>
</html>
The JS:
window.onload = function() {
document.forms[0].onsubmit = function(e) {
e.preventDefault();
var regexp = new RegExp("^[A-Za-z]+$"),
elem = this.elements[0],
value = elem.value;
if(regexp.test(value) && typeof value != "null" && value.length > 5) {
elem.className = "text correct";
var formElem = this;
setTimeout(function() { formElem.submit(); }, 0);
}
else elem.className = "text wrong";
};
};
The PHP file:
<?php
session_start();
if(isset($_POST['btnsubmit'])) {
$_SESSION['name'] = $_POST['name'];
echo $_SESSION['name'];
}
else {
if(!isset($_SESSION['name']))
echo "Header";
else
echo $_SESSION['name'];
}
?>
Is there something wrong or JS submit function is not functioning properly ?
The request parameter corresponding to a submit button is only passed if the form is submitted as a result of clicking that button. That's not the case here since you suppress the original form submit (the one triggered by the button), then later call formElem.submit() from JavaScript; no button click means no request parameter, and therefore isset($_POST['btnsubmit']) in your PHP script won't ever return true.
One solution might be to add the btnsubmit parameter to the form's action before submitting it:
formElem.action += (formElem.action.indexOf('?') == -1 ? '?btnsubmit=Submit' : '&btnsubmit=Submit');

form fields not getting posted to php file when using jquery

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/

Categories