Jquery and form with same name issue - php

Well i'm working on a small php script and in the admin panel i've added a page to manage comments. Following is the html markup for comment:
<form name="form" action="">
<tr>
<td>COMMENT ID</td><td><button value="0" name="choice">Delete</button><button value="1" name="choice">Accept</button></td>
</form>
For every comment i'm posting this info to a file comment.php using the following jquery code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").submit(function(){
$.get("response.php", $(this).serialize(), function(a){
$("#info").html(a)
});
return false
})
});
</script>
My issue is i can't get the choice Value using this code $_REQUEST['choice'] because both <button>s have the same name and this is the same thing for forms. How can i fix this ?

The are some mistakes on your code:
1) You forgot to put the id attribute that your JS is calling
<form name="form" action="">
Change it to this:
<form name="form" action="" id="form">
Since it has the same name, use the .click() event instead.
Complete Code:
<form name="form" action="" id="form">
<table>
<tr>
<td>COMMENT ID</td>
<td>
<button value="0" name="choice">Delete</button>
<button value="1" name="choice">Accept</button>
<input type="hidden" name="id" value="100">
</td>
</tr>
</table>
</form>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button[name='choice']").click(function(e){
var form_data = {};
form_data.choice = $(this).val();
form_data.id = $(this).siblings('input[name="id"]').val();
e.preventDefault(); // stops the normal submission
$.post("index.php", form_data, function(a){
console.log(a); // check the values on browser console
});
});
});
</script>
On your PHP:
if(isset($_POST['choice'])) {
$action = $_POST['choice'];
$data = $_POST;
// its inside $_POST['id'];
echo json_encode($data);
exit;
}
Sample Output

You can do this by binding the ajax request to the button.click() instead of form.submit()
$(function(){ // $(document).ready() shorthand
$("button[name=choice]").click(function(){
var data = 'choice='+ $(this).val() + '&' + $(this).closest('form').serialize();
$.get("response.php", data, function(a){
$("#info").html(a)
});
return false
})
});

Related

how to send data onClick() to another php for processing using post or get?

I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>

Submit form after form load is blank

I make index.php like this:
<script src="js/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$("#sload").load('save1.php',function(forma){
$(".csave").click(function(){
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
})
return false;
});
});
});
</script>
SAVE
<div id="sload"></div>
save1.php like this :
<table>
<form method="post" name="form1" id="form1" action="input1.php">
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</form>
and input1.php
<? session_start();
include "db.php";
$date=$_POST['date'];
$location=$_POST['location'];
mysql_query("insert into hal (date,location) values ('$date','$location')");
?>
after I click SAVE not an error, but the database is stored in an empty field. Submit form after form load is blank
Thanks.
You need to separate the logic of loading and saving like this:
Here's an example (based on your code) as a single page script test.php:
<?php
// Load Form
if (isset($_GET['loadForm']))
{
exit('<form method="post" name="form1" id="form1" action="test.php">
<table>
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</table>
</form>');
}
// Handle Form Save
if (count($_POST) > 0)
{
// TODO
exit('got form data: '. print_r($_POST, true));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Load Form
$('#sload').load('test.php?loadForm');
// Handle Save Click
$('.csave').click(function()
{
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
});
});
});
</script>
SAVE
<div id="sload"></div>
When I click save, this is what the output is:
To complete this code, add the db row inserting code where it says TODO. Hope this helps.
Update
Here's the split version:
index.php
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Load Form
$('#sload').load('save1.php');
// Handle Save Click
$('.csave').click(function()
{
$.ajax({
type: 'POST',
url: $('#form1').attr('action'),
data: $('#form1').serialize(),
success: function(data) {
alert(data);
}
});
});
});
</script>
SAVE
<div id="sload"></div>
save1.php
<form method="post" name="form1" id="form1" action="input1.php">
<table>
<tr>
<td>Date</td><td>:</td><td><input name="date" id="date"/></td>
</tr>
<tr>
<td>Location</td><td>:</td><td><input name="location" id="location" /></td>
</tr>
</table>
</form>
input1.php
<?php
session_start(); // what's this for? you aren't using session on this file
// this is not safe! use mysqli or pdo and escape post values!!!
include "db.php";
$date=$_POST['date'];
$location=$_POST['location'];
mysql_query("insert into hal (date,location) values ('$date','$location')");
?>

How to send $file value/path to PHP file using input field and onClick button?

I have a form where I use a GET/IMPORT button to get values from other document and into the current form as shown below. Previously I had set fix value: $file = '/user/doc.xml'; inside meta.php so when I pressed the GET/IMPORT button it got the results from the /user/doc.xml file.
Now I have added <input name="file" value="" /> to this form and want to send path to $file using this filed. I know when I press GET/IMPORT button then meta.php file is called.
So my question is: How can I send $file value/path to meta.php using this input field.
Here is my script and the $file input field:
<form id=file method="POST" >
<input name="file" value="" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.button').click(function() {
$.get('meta.php', function(data) {
result = $.parseJSON(data);
$("input[name='nick_name']").val(result.avaname);
$("#age").val(result.tavaage).attr("selected","selected");
});
});
});
</script>
<input class="button" type="button" value="GET/IMPORT" />
</form>
Thank you for all help.
Just get the value from the input field and add it to the querystring of the url. Then in meta.php you can read the filename from the request parameters and load that file.
Don't forget to validate the filename.
<input name="file" type="text" id="file">
<script type="text/javascript">
$(document).ready(function() {
$('.button').click(function() {
var val = $('#file').val();
$.get('meta.php', {file: val}, function(data) {
var result = $.parseJSON(data);
$('input[name="nick_name"]').val(result.avaname);
$('#age').val(result.tavaage).attr('selected', 'selected');
});
});
});
</script>
<input type="button" class="button" value="GET/IMPORT">
Then in your meta.php you can get the the filename with $_GET['file'].
Hope it helps
You can use the $.get method with "data" like this :
$(document).ready(function() {
$('.button').click(function() {
$.get('meta.php', {file: $('input[name="file"]').val()}; function(data) {
result = $.parseJSON(data);
$("input[name='nick_name']").val(result.avaname);
$("#age").val(result.tavaage).attr("selected","selected");
});
});
});

Submitting forms thru in PHP on jQuery

I have a registration form that is currently in a popup modal window coded in jQuery. I have a PHP submit button on the bottom and I have added jQuery code that stops the button from submitting. This is because it will stop my modal window from closing when I submit the page. My issue now is that submitting the form would be impossible. Is there a way to submit my form over all this crowded pop-ups and jQuery? Say is it possible to use AJAX or jQuery to submit the form and allow my PHP to handle it.
Since I am writing in PHP, there is quite a bit of server side validation going on, so the point of this is to allow my viewers to fix their validation mistakes before the modal window closes.
Here is my jQuery, I didnt bother to mess with that anymore as it does what I need.
$(document).ready(function() {
$('a.modal-window').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
$(loginBox).fadeIn(300);
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
Here is the code I used to stop the form from submitting:
$(function () {
$(':submit').click(function (event) {
event.preventDefault();
// submit the form dynamically
});
});
and below is my form, it might not matter although its there for the viewing.
<form method="post" id="loginform" action="<?php echo $_SERVER['PHP_SELF']?>">
<table style="color: white;">
<tr><th style="float:left;">Register a new account with us.</th></tr>
<tr><td>Username</td><td><input type="text" name="txtUser"/></td></tr>
<tr><td>Password</td><td><input type="text" name="txtPass"/></td></tr>
<tr><td>Email</td><td><input type="text" name="txtEmail"/></td></tr>
<tr><td>Confirm Email</td><td><input type="text" name="txtEmail2"/></td></tr>
<tr><td>First Name</td><td><input type="text" name="txtFname"/></td></tr>
<tr><td>Last Name</td><td><input type="text" name="txtLname"/></td></tr>
<tr><td>Address</td><td><input type="text" name="txtAddress"/></td></tr>
<tr><td>City</td><td><input type="text" name="txtCity"/></td></tr>
<tr><td>Postal Code</td><td><input type="text" name="txtPostal"/></td></tr>
<tr><td>Birth Year</td><td><input type="text" name="txtBirth"/></td></tr>
<tr><td>Gender</td><td><input type="radio" id="radio-1-1" name="radicalSex" class="regular-radio" value="m" selected="true" /><label for="radio-1-1"></label> Male</td></tr>
<tr><td></td><td><input type="radio" id="radio-1-2" name="radicalSex" class="regular-radio" value="f"/><label for="radio-1-2"></label> Female</td></tr>
<tr><td colspan='2' style="color: #FF6600;float:left;font-size:70%;"><?php echo $Error;?></td></tr>
<tr><td colspan="2"><input type="submit" name="btnRegister" ID="btnBlueTemp" value="Submit Registration" /></td></tr>
<tr><td colspan='2' style="float:left; font-size:70%;">Address information is optional</td></tr>
</table>
</form>
Let me give you an example of how you can do that .
<html>
<head>
<title></title>
<script src="js/jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
function validate(name, addr){
if(name=="") {
alert('Name is Blank');
return false;
} else if(addr=="") {
alert('Address is Blank');
return false;
} else {
return true;
}
}
$("#save").click(function(event){
event.preventDefault();
var name = $("#name").val();
var addr = $("#addr").val();
if(validate(name,addr)){
$.ajax({
type:'POST',
data:'name='+name+'&addr='+addr,
url:'test2.php',
success:function(data) {
alert(data);
}
})
}
});
});
</script>
</head>
<body>
<form name="frm" method="POST" action="">
<input type="text" name="name" id="name" value=""/><br>
<input type="text" name="addr" id="addr" value="" /><br>
<input type="submit" name="save" id="save" value="Save"/>
</form>
</body>
</html>
Now in test2.php You can do your php codes
<?php
if(isset($_POST['name'])) {
echo $_POST['name'];
}
?>
Hope this gives you an Idea.
You need to serialize the form data before posting it to PHP.
<script type="text/javascript">
var frm = $('#loginform');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('submitted');
}
});
return false;//stop actual form submit
});
</script>
Then, submit your form via ajax
Jquery AJAX
On AJAX URL on which the request is sent, you can write necessary codes for validation and return accordingly. For eg. if some one the form element doesn't meet the validation, you can throw the flag accordingly as json value.
Its possible, why not.
Once you have done all the input validation at client side, just submit the form...
$("#loginform").submit();
Then you will have your server do the rest of the validation.
If you want to stay in the page and show the validation output from server, the. You should submit using Ajax.
It will send your form data to server, then you can do server validation, and output any errors. You will get this in your Ajax complete handler, which you can use to show error messages to user.
To stop the form from reloading the page you needn't call any prevent methods as a simple script request would do the trick.
For instance,
$('#loginForm').submit(function() {
// Do the relevant tasks needed here, form is already prevented from being submitted
});
Check out this demo for more information on what I am referring to

How to send a form after a click

I have this code :
<script type="text/javascript">
$(document).ready(function() {
$('a[name=linkArtist]').click(function(e) {
e.preventDefault();
$('#changeArtist').val($(this).attr('title'));
});
});
</script>
<form action="index.php?explore=browse" method="post">
<input type="hidden" id="changeArtist" name="artist" value="<?=$artist?>" />
<a name="linkArtist" title="a" href="#">A</a> -
<a name="linkArtist" title="b" href="#">B</a> -
<a name="linkArtist" title="c" href="#">C</a>
</form>
When I click on the button, I set the link value (as 'title') to the hidden field, and after I'd like to send that form! How can I do it? And what do you think about this code? Can I better it?
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('a[name=linkArtist]').click(function(e) {
e.preventDefault();
$('#changeArtist').val($(this).attr('title'));
$('#myForm').submit();
});
});
</script>
The form:
<form action="index.php?explore=browse" method="post" id="myForm">
Note the form id and the change to the click handler to access it.
I don't think you need to use preventDefault() at all. The form should not submit until the function has returned.

Categories