I'm generating tables of buttons with php
echo ' <td">
<form action="test.php" method="POST">
<input type="hidden" id="node" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" id="service" name="service" value="'.$flavor.'">
<input type="hidden" id="running" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
I want to send the values without reloading via jquery ajax and I'm using this code for it:
$(".button").click(function() {
$('.error').hide();
var dataString = 'node='+ document.getElementById('node').value + '&service=' + document.getElementById('service').value + '&running=' + document.getElementById('running').value;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success");
}
});
return false;
});
Code works so far - it just always sends the data from the first form. What is the best way to distinguish between all the buttons. I could use a counter in the form, but how would I exactly write the js "ifs".
Is there a more elegant way to do this. Number of forms is dynamic.
You can grab the parent form of the button clicked easily enough, but youll also probably want to have a unique ID on the form for other things. Also you need to either remove the ids on the inputs or make them unique.
echo ' <td">
<form action="test.php" method="POST" id="form_node_' . $fnode->{'name'} . '>
<input type="hidden" name="node" value="'.$fnode->{'name'}.'">
<input type="hidden" name="service" value="'.$flavor.'">
<input type="hidden" name="running" value="false">
<input type="submit" value="OFF" class="button">
</form>
</td>';
$(".button").click(function(e) {
e.preventDefault();
$('.error').hide();
var $form = $(this).closest('form'), // the closest parent form
dataString = $form.closest('form').serialize(); // serialize the values instead of manually encoding
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function() {
alert ("Success submitting form ID " + $form.attr('id'));
// you can now modify the form you submitted
}
});
return false;
});
The best way is to use unique IDs for form elements. Another way is to set classes to multiple elements with the same name.
However, the following approach is much preferable:
$("form").on("submit", function() {
$.ajax({
type: "POST",
url: "test.php",
data: $(this).serialize(),
success: function() {
alert ("Success");
}
});
return false;
});
(But anyway don't forget to remove duplicating id attributes from the form elements.)
You can give each submit buttons an id:
<input id="button-1" type="submit" value="OFF" class="button">
and then trigger the event on click of a specific button:
$("#button-1").click(function() { ... });
Related
I am struggling to have multiple AJAX submitted forms on the same php page. I can get it to work with one, but when I add more, it just uses the first form all the time.
I have tried to make it unique but not sure exactly how to do this.
My code is below, if someone could please assist that would be fantastic.
I have looked at similar questions and answers on this site but can't seem to fathom how to make it work for mine.
The form should submit when the checkbox is checked or unchecked.
Thanks very much in advance for all your help.
Martyn.
HTML form
<form id="search_form" method="post">
<input readonly type="text" name="id" value=<?php echo $row1[0];?>>
<input readonly type="text" name="student" value=<?php echo $row1[1];?>>
<input readonly type="text" name="addedby" value=<?php echo $_SESSION['username'];?>>
<input readonly type="text" name="register" value="monday_morning">
<input <?php if($row1[4] == "Yes"){echo "checked";}?> type="checkbox" name="box" value="Yes">
</form>
Script
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function () {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $("#search_form").serialize(),
success: function (data) {
}
});
return false;
});
</script>
Try this
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function (event) {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $($(event.target).parent()).serialize(),
success: function (data) {
}
});
return false;
});
</script>
event.target returns the clicked checkbox.
parent() function returns the form you need to submit. This way you don't need to have unique form id.
HTML
<input type="checkbox" name=options[cid]" value='1'
onChange="chkdeptCount(this.value)" class="test">
<input type="checkbox" name=options[cid]" value='2'
onChange="chkdeptCount(this.value)" class="test">
jquery:
function chkdeptCount(val){
$.ajax({ url: '../ajax/AjaxCall.php',
data: {Action:'IMPLODEARRAY',arrVal: val},
type: 'post',
success: function(output) {
alert(output);
$('.result').html(output);
}
});
}
PHP:
if($_POST['Action']=='IMPLODEARRAY'){
$arr_val[] = $_POST['arrVal'];
print_r($arr_val);
}
When I run this code does not return array value. It returns a single value WHY?
Note that, you are missing the quote here name=options[cid]".
And you are using onChange="chkdeptCount(this.value)" event with current value this, this will only return one value at once.
This is very basic Example:
HTML:
<form method="post" id="formID" action="">
<input type="hidden" name="Action" value="IMPLODEARRAY">
<input type="checkbox" name="options[cid]" value='1' class="test">
<input type="checkbox" name="options[cid]" value='2' class="test">
<input type="submit" name="submit" value="Submit" id="SubmitButton">
</form>
AJAX:
<script type="text/javascript">
$(document).ready(function(){
$("#SubmitButton").click(function(){ // when submit button press
var data = $("#formID").serialize(); // get all form input in serialize()
$.ajax({
url: YourURL, // add your url here
type: "POST", // your method
data: data, // your form data
dataType: "json", // you can use json/html type
success: function(response) {
console.log(response); // your response
},
beforeSend: function()
{
// if you want to display any loading message
}
}); // JQUERY Native Ajax End
return false;
});
});
</script>
PHP:
<?php
if(count($_POST) > 0){ // if you have some value in AJAX request
if($_POST['Action'] == 'IMPLODEARRAY'){ // your condition
print_r($_POST['options']); // get all checkbox value.
}
}
?>
Few more example will help you to understand, you can you use: Submitting HTML form using Jquery AJAX |
jQuery AJAX submit form
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();
}
});
});
});
I am extracting sql data to a another php table used for a site. For each row in the table I have a button to delete or edit that specific row. The edit button works fine but I have been having issues with the delete button. As of now the delete button only deletes the first row of the table and not the row that has been selected for deletion.
Here is a sample of the table:
while($row = mysqli_fetch_array($result)){
<tr>
<td>'.($row['some_data']).'</td>
<td>
<form action="meeting_update_milestone.php" method="POST">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="submit" value="EDIT" />
</form>
</td>
<td>
<form id="meeting_delete_item">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="button" onclick="delete_meeting_item()" value="DELETE" />
</form>
</td>
</tr>';
}
This data is being sent to an ajax call:
function delete_meeting_item(){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: $('#meeting_delete_item').serialize(),
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
As you can tell I loop through the rows creating multiple forms with the same id. I think this is creating the issue here? If so how can I fix it by keeping the same formatting. I believe the forms have to have a unique name, but I am not sure how to implement this into the ajax data string.
I can't comment on the validity of your php code, but as you say, the id values have to be unique. In this instance, I don't believe the ID really makes much difference to what you are trying to achieve.
Remove the id and the inline onclick event:
while($row = mysqli_fetch_array($result)){
<tr>
<td>'.($row['some_data']).'</td>
<td>
<form action="meeting_update_milestone.php" method="POST">
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="submit" value="EDIT" />
</form>
</td>
<td>
<form>
<input type="hidden" name="mile_id" value="'.$row['id'].'" />
<input type="button" class="delete" value="DELETE" />
</form>
</td>
</tr>';
}
And bind it using jQuery. I added a class to be able to get a selector to the delete button.
$(document).ready(function(){
$('.delete').click(function(){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: $(this).closest(form).serialize(),
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
}
On click of the delete button, we get the nearest form and serialize the data for that form.
Your problem is here
$('#meeting_delete_item').serialize()
You should use something else to determine that the current line is.
HTML FORM PART FOR DELETE
<form id="meeting_delete_item">
<input type="button" onclick="delete_meeting_item('.$row['id'].')" value="DELETE" />
</form>
JS
function delete_meeting_item(deleteId){
var x = confirm("Are you sure you want to permanetly delete this item?");
if (x){
$.ajax({
type: "POST",
url: "meeting_delete_item.php",
data: {mile_id: deleteId},
cache: false,
success: function(result){
alert(result);
}
})//end ajax
}
else{
return false;
}
}
Outside of your loop, you can keep a counter: $x = 0 and use that when generating the form: <form id="meeting_delete_item"'.$x.'>. At the end of the loop, increment the counter for the next iteration ++$x. In your javascript, you will probably retrieve the id according to the button that is pressed.
Sample Forms:
<form id="myForm1">
<button>Click me!</button>
</form>
<form id="myForm2">
<button>Click me!</button>
</form>
Sample JavaScript:
$('form button').click(function(e) {
var $form = $(this).closest('form');
console.log($form.attr('id'));
return false; //stop form submission
});
Live demo (click).
Also, inline js (like onclick in your html) has never been good practice. Instead, follow the example in my sample code and bind the click function with javascript. For more on this subject, read some of these results: https://www.google.com/search?q=Why+is+inline+js+bad%3F
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