jQuery get values from current form - javascript

Hello everyone I'm working on a project and I'm pretty sure I've made a rather large mistake. Basically I have some PHP code that retrieves some values from a database, and each row gets its own in a table. Then each one has a button that deletes it, which shows a small dropdown form asking for some details along with a submit button. However, I for some reason wasn't thinking that there would be multiple forms, and have each input an id, resulting in multiple elements having the same id.
So, in JavaScript, an AJAX request is made when a user submits deleting a row, and the values from the form (values are found by the ID of the input) are sent as POST variables to a PHP script. Since I'm doing this, the AJAX request only works if they're deleting the first row, but not any under that.
So, this HTML is output by PHP to add a dropdown form to each row:
<td class='dropdown'><a class='dropdown-toggle' href='#' data-toggle='dropdown'><button class='btn btn-warning'>Kick</button></a>
<div class='dropdown-menu' style='padding:15px; width:340px'>
<div class='form-group'>
<form id='delete-form'>
<label for='delete-reason'>Reason: </label>
<input class='form-control' id='delete-reason' name='delete-reason'>
<input type='hidden' id='delete-id' name='delete-id' value='". $value['Name'] ."''>
</div>
<br>
<input type='submit' id='delete-submit' name='delete-submit' value='Delete ". $value['Name'] ."' class='btn btn-default'>
</form>
</div>
</div>
Then I use this JavaScript to submit the form to send the data from the form to a PHP script by an AJAX request.
$("#delete-form").submit(function(e){
e.preventDefault() // stop form from submitting
var reason = $("#delete-reason").val();
var id = $("#delete-id").val()
$.ajax({
type: 'POST',
url: 'php/ajax.php',
data: {
deletereason: player,
deleteid: id
},
success: function(response){
$("#delete-result").append(response);
$("#delete-result").fadeIn(500);
}
})
})
So, like I said, it only works on the first row because on the others, it just gets the values of the first found input with that id. And when I do it on any row besides the first, it adds the values as a query string, which doesn't do anything because well, it's not supposed to.
However I don't really know how to make it where it would get the values from the current form, not the others, and that's why I'm here.
I understand this is all pretty confusing and if you need me to clarify anything or explain more I'd be happy to.
Any suggestions?

You need to have unique id for each form and input element and then follow the answer provided by #ArunPJohny. But if you cannot have unique id for each element then follow below code
$(".form-group form").submit(function (e) {
e.preventDefault() // stop form from submitting
var reason = $(this).find("input[name='delete-reason']").val();
var id = $(this).find("input[name='delete-id']").val();
$.ajax({
type: 'POST',
url: 'php/ajax.php',
data: {
deletereason: player,
deleteid: id
},
success: function (response) {
$("#delete-result").append(response);
$("#delete-result").fadeIn(500);
}
});
});

Related

Page change using Ajax, still save data entered

I am writing a practice website using jQuery's ajax.
Currently I have 3 buttons, each of which, when clicked, shows different contents with forms using ajax call. The contents are stored in different files. Let's say you enter "AAA" in the form in the content shown after clicking the first button. Then you click on the second button, which will replace the first content with the new second one. And you enter "BBB" in the form on there. What I want to achieve is, when you do this, I don't want the page to forget what you typed in the first page (or before you changed the page using ajax call), and at the end, you press SUBMIT button, which is common in all buttons' content. Then, I want the webpage to submit both "AAA" and "BBB" for more computation.
Is this ever possible?
This is kind of like a pizza website. Assume that there are 2 tabs on the website, one for pizza dough option, and the other for topping option. Also assume the pagenation of the tabs happens using ajax by asynchronously displaying the contents. When you choose options in pizza dough tab, and you change the tab to select topping options. Then you finally place the order, which reflects customers' option for both dough and topping.
How could you possibly implement this? Any advice would be greatly appreciated.
Do I need a database using SQL? Since this is a simple practice website, it does not have to remember the customer's options once you submit the form and they close the page.
Here is some portion of my code since I cannot write them all. I also omitted some unimportant parts.
php file1:
<script>
$(document).ready(function(){
$(".dough, .topping").click(function(){
$.ajax({
url: /*URL is either dough.php or topping.php*/
success: function(data){
$(".result").html(data);
},
error: function(data){
alert("error");
}
});
});
});
</script>
<button class="dough">Dough</button>
<button class="topping">Toppings</button>
<div class="result"></div> <!--Here I want to show the content with ajax-->
php file2 (=dough.php) and file3(=topping.php): /*This is the form-containing files and both have the same structure */
<form action="confirm.php" method="POST">
<!--Pizza's dough and topping photos, price and name etc-->
<input type="text" name="******"> <!--This is the input form-->
</form>
In this case, I feel like I should have the final "submit" button outside the form tag because the submit button is common and should stay at the bottom of the page during the course of pagenation.
<form action="confirm.php" method="POST">
<!--Pizza's dough and topping photos, price and name etc-->
<input type="text" class='myValue' name="******">
<!-- this button is for saving the input entered above; for topping form give 'toppings' class-->
<input class='option-button pizza-dough' type='button' value='select'/>
</form>
Add event handler for the above form(s)
$('.result').on('click','.pizza-dough,.toppings',function(e){
//using on() because forms are dynamically added
var myValue = $(this).siblings('.myValue').val();
if(this).hasClass('.pizza-dough') {
localStorage.setItem('pizza-dough', myValue);//store the value in localStorage
}else{
localStorage.setItem('toppings', myValue);//store the value in localStorage
}
});
Now, suppose you have following common submit button
<input type='button' value='submit' class='submit-values'/>
Add event handler for this button to submit the values
$('.submit-values').click(function(e){
var dataToSend = {'pizza-dough':localStorage.getItem('pizza-dough'),'topppings':localStorage.getItem('toppings')};
$.ajax({
url: /*submit url*/,
method: "POST",
data: dataToSend,
success: function(data){
//handle success
},
error: function(data){
//handle error
}
});
});
Adding validation for localStorage values is left for you.
Read more about localStorage and sessionStorage to choose what best suits you.

Getting data from HTML form, and from Javascript array upon form submission

I'm stuck.
I have a regular HTML form that submits to itself.
<form action="<?php print $phpSelf;?>" method="post" id="PO">
<input>...</>
<input>...</>
<input>...</>
<input type="submit" id="btnCreate" name="btnCreate" value="Create" tabindex="900" class="button">
</form>
And I have an array in Javascript, I'll call it
var jArray;
I need to get the information from the form, and the information from the Javascript array. I can get each of them separately, but I don't know how to get them at the same time.
For the Javascript, this is the method I am using.
function submitPO(){
$.ajax({
type:"post",
url: "jsTo.php", //Send the variable to this page
data:{partsToAdd: jArray}, //{variable name (POST), data to be passed}
cache:false,
success: function(html){ //Function to execute when successful
console.log("Success in the function");
$('p#msg').html(html);
}
});
return false
}; //End of SubmitPO
<p id = "msg"></p>
<form>
<input type="submit" value = "submit" onclick = "return submitPO();">
</form>
When I press the button, it sends the array to jsTo.php where I can get it.
$selectedParts = $_POST['partsToAdd'];
That works fine. I use a similar method for getting the information from the HTML form.
$To = htmlentities($_POST["To"], ENT_QUOTES, "UTF-8");
So, like I mentioned above, I can get either the data from the javascript array, or the data from the form, but not both. Anyone able to help me figure this out? I've looked all over SO, and have found tons of resources on how to submit multiple forms with one button, how to post from JS to PHP, etc., but nothing that has touched on this issue.
You can get the data from the form with .serialize then you can add it to the array data with $.param
data:$.param({partsToAdd: jArray})+'&'+$('#PO').serialize(),
You can just serialized your form.
in your ajax data, just do
data: $('form').serialize()

How to convert a GET request to POST

I don't know if it is possible or not. I referred some site, but I didn't get exact answer.
I am using
click
When I send this request to server in the response page easily I can see "id=4" in address bar, obviously which is not secure, But in post request we cant see this.
So can we convert a get request to post or ant other way is there to hide this from address bar.
Thanks in advance.
Firstly, to convert GET to POST, simply change the link to a form:
<form id="myForm" action="xyz" method="post">
<input type"hidden" name="id" value="4"/>
</form>
This form will not be visible and you can easily auto-submit it using JavaScript in your link:
click
Secondly and more importantly, both GET and POST are equally not secure over HTTP. To secure them, use HTTPS and they will be both equally secure, so no need to change if GET is working for you.
click
Dynamically create a from and post it.
function postForm() {
var form = $('<form method="POST" action="xyz"></form>');
$(document.body).append(form);
form.append('<input type="hidden" name="id" value="4"/>');
form.submit();
}
As Racil suggested in comments, you can also do the following
click
and then
$('#postLink').click(function(e){
e.preventDefault();
//create form and post
});
Call a java script function on onclick which will make the form submission using post method or you can use ajax call to post the data and get your desired results.Use id as a parameter in function.
<a href="#" onclick="postData(4)">
/// Javascript function for ajax call
function postData(id){
var param = { "Id": id};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "xyz.aspx",
data: JSON.stringify(param),
success: function (data) {
/// Recive data here or do your stuff here
}
}
Make a form having single input type hidden and onclick set value of that input type hidden element and submit form using jquery.
<form id="target" action="destination.html">
<input type="hidden" id="hiddenValue">
</form>
/// Javascript function for setting value of hidden element and form submission using jquery
function postData(id){
$("#hiddenValue").val(id);
$("#target").submit();
}
Hopefully this will solve your problem.

How to handle php loop through elements with jquery

I have an HTML form that will return as HTML format with JQuery Ajax after the insertion query is successful.
comment.php
$post_id=$_POST['id'];
mysql_query("INSERT INTO comment(comment,post_id,)VALUES('$comment','$post_id')");
if(!mysql_errno()){
?>
<p><?php echo $comment; ?></p>
This is my JQuery code that will send the request and values and return the HTML form after the insertion query succeeds.
index.php
// on post comment click
$('.bt-add-com').click(function(){
var theCom=$(this).siblings('.the-new-com');
if(!theCom.val()){
alert('You need to write a comment!');
}else{
var post_id=$(this).parents(".post_id").attr("id");
$.ajax({
type: "POST",
url: "comment.php",
data: "act=add-com&comment="+theCom.val()+"&id="+post_id,
success: function(html){
theCom.val('');
$('.the-new-com').hide('fast', function(){
$('.new-comment-line').show('fast');
$('.new-comment-line').after(html);
});
}
});
}
});
This my form. It's running within a loop of posts submitted by the user every time.
<form action="" method="POST" class="post_id" id="<?php echo $post_id; ?>">
<span>Write a comment ...</span>
</div>
<div class="new-comment-line"></div><----here is a line before the comment initiates..--->
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
</form>
And now my question is that my all code works very well except last few lines of JQuery code.
$('.new-comment-line').after(html);
The line of code when my form returns the HTML form from comment.php after the Ajax request has the problem. The form prints every time, in every post, that the user submitted the status.
How should I handle the form? I want my comments to print every time only in the specific post submitted by the user.
Obviously $('.new-comment-line') is a class selector and you are selecting all elements in this class. As you start your function by clicking on a button, I suggest the selection of correct element relative to the clicked button. So immediately after clicking a button, select the correct element:
var correctElement=$(this).siblings('.new-comment-line');
and then add the html to it when needed:
correctElement.after(html);

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

Categories

Resources