I have the following script :
<script type="text/javascript" >
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val();
var first_lastname = $(".first_lastname", this).val();
var second_firstname = $(".second_firstname", this).val();
var second_lastname = $(".second_lastname", this).val();
var TeamName = $(".TeamName", this).val();
var dataString = 'first_firstname='+ first_firstname + '&first_lastname=' + first_lastname +
'&second_firstname=' + second_firstname + '&second_lastname=' + second_lastname + '&TeamName=' + TeamName;
$.ajax({
type: "POST",
url: "data.php",
data: dataString,
success: function(){
window.setTimeout(function(data)
{
$('#propspectDiv').html('Team Name Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
});
</script>
And the following php that generates a number of forms on a page using mysql database
<?php
echo '<table class="greensmalltbl" cellspacing="10px" cellpadding="5px"><div id="propspectDiv"></div>';
for ($i=1, $o=$totalEntrants; $i<=$half; $i++, $o=$o-1) {
$formid = $i;
echo "<div style='border:3px;'><form action='' method='post'>
<tr><td><input type='text' name='first_firstname' id='first_firstname' value='$firstName[$i]' />
<input type='text' name='first_lastname' id='first_lastname' value='$lastName[$i]' />
Skill Level : ".$skill[$i]."</td></tr>";
echo "<tr><td>WITH</td></tr>";
echo "<tr><td><input type='text' name='second_firstname' id='second_firstname' value='$firstName[$o]' />
<input type='text' name='second_lastname' id='second_lastname' value='$lastName[$o]' /> Skill Level ".$skill[$o]."</td></tr>";
echo "<tr><td>Enter Team Name : <input type='text' name='TeamName' id='TeamName' value='' />
<input type='submit' name='submit' value='Submit'></form></td></tr>";
}
echo '</table>';
?>
I want to update the db table with the TEAM NAME in each form
The problem is only the first forms input is passed all other forms do nothing
I have tried a number of variations to the ajax code but none have worked.
Can anyone find the problem here
This line will not return the form.
var parent = $(this).parent('form');
because your submit button is wrapped inside tr and td tags. Either get rid of those tags (they are invallid anyway, because your are not using them in a table), or update your code to:
var parent = $(this).closest('form');
closest() searches its way up to all the ancestors of an element, and will return the first match of the selector.
Check out the documentation here: http://api.jquery.com/closest/
Or, if you only have a single form in your page, you could just go:
var parent = $('form');
:: EDIT ::
OK. Forget all of the above. Seems like you are not even using the parent variable later in the code.
A more important problem is that even though you are catching the Click event on the form submit button, what you probably really want to do is catch the submit-event of the form.
So change your first line of code to this:
$('form').on('submit', function() {
Also, in your HTML, your code is invalid.
<form action'' method='post' id='$formid'>
action'' should be action = ''
Chances are this doesn't really fix your problem, because there might be more errors. Next time, try to validate your code before posting a question.
:: EDIT ::
Last edit, I promise. I quickly went trough your code again, and it seems you will have multiple forms. this means, that you will get elements in different forms with the same id's. An id should be unique for troughout the page. So when you try to get a value like this $("#second_firstname").val(); that won't work. because jQuery doesn't know what element you mean, so all elements that can appear multiple times in a page need to have a class and CAN NOT have an id.
You could then loop trough your forms by changing things to:
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val(); // . instead of # and use 'this' as context
// and so on..
// the rest of your code here.
}
});
table with forms can be seen here
Related
I am trying to write a code that 'stores items for later' - a button that has url of the item as hidden input, on submit it calls a php script that does the storage in a db. I am more into php, very little knowledge of anything object-oriented, but I need to use jquery to call the php script without moving over there
The problem is how to assign the x and y variables when I have multiple forms on one page
I was only able to write the following
$("form").bind('submit',function(e){
e.preventDefault();
var x = $("input[type=hidden][name=hidden_url]").val();
var y = $("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php?url='+x+'&tit='+y,
success: function() {
alert( "Stored!");
location.reload();
}
});
});
It works fine if you have something like...
<form method="post" action="#">
<input type="hidden" id="hidden_url" name="hidden_url" value="<?php echo $sch_link; ?>"/>
<input type="hidden" id="hidden_title" name="hidden_title" value="<?php echo $sch_tit; ?>"/>
<input type="submit" id="send-btn" class="store" value="Store" />
</form>
..once on the page, I've got about 50 of them.
These are generated via for-loop I suppose I could use $i as an identifier then but how do I tell jquery to assign the vars only of the form/submit that was actually clicked?
You'll have to scope finding the hidden fields to look within the current form only. In an event handler, this will refer to the form that was being submitted. This will only find inputs matching the given selector within that form.
$("form").bind('submit',function(e){
e.preventDefault();
var x = $(this).find("input[type=hidden][name=hidden_url]").val();
var y = $(this).find("input[type=hidden][name=hidden_title]").val();
$.ajax({
url: 'save_storage.php',
data: {
url: x,
tit: y
},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
As #Musa said, it's also better to supply a data key to the $.ajax call to pass your field values.
Inside your form submit handler, you have access to the form element through the this variable. You can use this to give your selector some context when searching for the appropriate inputs to pass through to your AJAX data.
This is how:
$("form").bind('submit',function(e) {
e.preventDefault();
// good practice to store your $(this) object
var $this = $(this);
// you don't need to make your selector any more specific than it needs to be
var x = $this.find('input[name=hidden_url]').val();
var y = $this.find('input[name=hidden_title]').val();
$.ajax({
url: 'save_storage.php',
data: {url:x, tit: y},
success: function() {
alert( "Stored!");
location.reload();
}
});
});
Also, IDs need to be unique per page so remove your id attribute from your inputs.
I have a PHP script that calls the Twitter 1.1 API, and returns 50 ID numbers. Then I am using a Foreach argument to print the results individualy on to the page. I want to store each different ID number inside a button as a hidden value, and then use JQuery Ajax to post that value to a different PHP page for further processing without leaving or refreshing the page of 50 ID numbers.
If I use this Foreach argument, the 50 ID numbers are ALL the first result in the array, rather than being 50 individual ID numbers which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='RT' onsubmit='return submitForm();'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>
");
}
But, If I remove this section from the Foreach argument, 50 individual ID numbers are printed into into hidden values of the forms:
onsubmit='return submitForm();'
The problem is my JQuery script is listening for submitForm and without that line above the JQuery will not run. Here is my JQuery script:
<script>
function submitForm() {
$.ajax({type: 'POST', url: 'results.php', data: $('#RT').serialize()});
return false;
}
</script>
I know that removing onsubmit='return submitForm();' gives me 50 unique ID numbers from the Foreach, because this code will print 50 buttons which will each contain individual values. But because there is no JQuery script listening for submitForm I have to add method='post' action='results.php in order to POST the value of the button but this means the page results.php loads which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='form' method='post' action='results.php'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>");
}
So, I want the foreach to print 50 unique ID numbers, while also letting me use the JQuery Ajax script. I hope this is clear, I don't know how else to describe what I want to do :D
Okay, now I understand what you're trying to do. I would do it like this.
PHP:
<?php
foreach ($results as $arrResult) {
$tweetId = $arrResult['id_str'];
print('<button type="button" class="mark-tweet" data-tweet-id="' . $tweetId . '"><br/><br/>');
}
JavaScript:
$(function() {
$('.mark-tweet').click(function() {
var id = $(this).attr('data-tweet-id');
$.ajax({
type: 'POST',
url: 'results.php',
data: {tweetId : id}
});
})
.done(function() {
alert('The tweet has been deleted');
})
.fail(function() {
alert('Oops, something went wrong! Please try again.');
});
});
NOTE: I am not capitalizing the 'r' in $Results as you did. Only class names should start in capital letters (class as in OOP, not CSS)
OK, we've got you now. You're on the right track to use an ID, and this is straight-forward.
What you need to render are 50 buttons with onclick that will call your markTweet() JS function & pass it the ID -- and that can do the AJAX post. No form required.
Alternatively, you can render 50 forms with separate IDs ('form'.$tweetId), each with a hidden input & submit button (or just a <button>, since the BUTTON element can have a name & value distinct from its content), and an onclick that calls `postTweetForm('form${tweetId})' -- thus passing the ID of the selected form to your JS function.
Really, since you're doing it in JS, keeping the UI simple & letting JS do the work is easiest. Here's an example to get started. PHP:
foreach ($Results as $arrResult) {
$tweetId = $arrResult['id_str'];
print("<button type='button' onclick='markTweet('".$tweetId."');'><br>\n");
}
Javascript:
function markTweet (tweetId) {
$.post({
url: 'results.php',
data: {'tweetId': tweetId}
);
}
You should also put in a success handler into your AJAX post.. fade in a little green tick or something so the user knows it's worked, because it doesn't always. (I'll let you play with that.)
Try that.. and keep the question up. It's much improved now & may be able to help someone else.
I was wondering how it would be possible to attach an HTML form's text box value to a link. For instance, I have 3 links and each link goes to a different PHP file, however, I need to pass a variable. Because of the design of my page, I cannot use buttons. So, I created a form with a text field. How do I send that Text Fields value with the links?
EG:
<form>
<input type="text" name="test1" id="test1"></input></form>
Link 1
Link 2
Link 3
I hope this makes sense as to what I am trying to do.
EDIT:
I tried to do this dynamically, but:
OK, I made a function like this:
<script>
function awardcode()
{ var awamount = document.getElementById("awardamount");
document.write('<?php $awardvar = ' + awamount.value + '; ?>');
};
</script>
Then, I made the link via PHP that looks like this:
echo '<a id=awlink3 name=awlink3 href="index.php?siteid=gmaward&type=xp&post=' . $posts_row['posts_id'] . '&handle=' . $posts_row['handle'] . '&varamount=' . $awardvar . '">Award XP</a>';
However, that didn't work. This is my input box code:
<form><input type=text name='awardamount' id='awardamount' onchange='awardcode()' style:'width:10px;'></form>
When I put the number and then tab, it loads an empty page.
How can I adjust that?
You'll need to dynamically change the link using JavaScript. Here's one approach:
$('a').on('click',function(e) {
e.preventDefault();
var url = $(this).attr('href').split('$')[0];
window.location = url + $('#test1').val();
});
But it might be better to add an onchange event to the textbox itself, so that the HREF changes instantly and the user can see the intended destination on mouseover:
$('#test1').on('change', function () {
var val = $(this).val();
$('a[href*=\\?id\\=]').each(function (i, el) {
$(el).attr('href', function (j, str) {
return str.split('?')[0] + "?id=" + val;
});
});
});
I am creating a popup dialog box where I need to put a set of values in hidden format, but when I am getting the value in AJAX post, I am getting only last value.
this is the PHP part:
$plan_ids=array();
foreach($test_plan as $plan)
{
$plan_ids[]=$plan['plan_id'];
}
?>
<?php
foreach($plan_ids as $id)
{
echo "<input type='hidden' id='plan_id' value='$id'>";
}
//var_dump($plan_ids);
// echo $plan['plan_id'];
?>
In the AJAX part I am doing:
$("#save").click(function () {
var name = $('#name').val();
var id = $('#release_id').val();
var plan_id = $('#plan_id').val();
//alert('hello');
$.ajax({
type: 'POST',
url: '/api/api.php?action=put_iteration&name=' + name + '&id=' + id + '&plan_id=' + plan_id,
data: "name=" + name + "&id=" + id + "&plan_id=" + plan_id,
success: function () {
$('#save').hide(function () {
$('div.success').fadeIn();
});
}
});
});
I'm clueless about HTML hidden fields.
Not a PHP guy, But some thoughts . Forgive me for syntax errors.
In the loop You are creating hidden element with the same ID. That is not good. Change the code sot hat the Id's will be ( SHOULD BE ALWAYS ) Unique.
<div>
foreach($plan_ids as $id)
{
echo "<input type='hidden' id='plan-$id' value='$id' class='myHidden'>";
}
Now in your script, use jQuery selectors based on the hidden item
var hiddenItems=$("input[type='hidden']");
may be now you can loop thru this
var items
$.each(hiddenItems,function(item,index){
items+= hiddenItems[index];
});
Or you can map function like this so that it will give a list of values of hidden fields comma seperated.
var itemsJoined=$("input[type='hidden']").map(function () {
return this.value;
}).get().join(',');
you can name all your hidden fields like an array name="plan_id[]"
And instead of passing it as a string you can have a wrapping FORM around hidden fields and then use jquery serialize function to POST it
Now you will get all the plan_id in the form of an array in the POST variable
Adding an example
<?php
echo '<form name="planidform" id="planidform">';
foreach($plan_ids as $id)
{
echo "<input type='hidden' name="plan_id[]" value='$id'>";
}
echo '</form>';
?>
After than in jQuery do it in following manner:
data: "name=" + name + "&id=" + id + "&"+$("#planidform").serialize(),
I think you want to change id='plan_id' to name='plan_id[]' for a start.... you are only allowed to have one element with a given id (i.e. id is required to be unique across elements in a given page).
you should put diffrent names / ids to the hidden fields.
if u want to submit them all at once u can store them in an array.
for example:
$i=0;
foreach($plan_ids as $id){
$i++;
echo "<input type='hidden' id='plan_id_$i' value='$id'>";}
then u can address or group them in JS.
I recently learned that when using onclick, for a button, the field name and button id have to each be unique. While thats not a problem, depending on how many rows my script outputs, this could be a lot of waste.
For example, i have a while loop, it does this for each person on my server (minecraft), so it could be 10, it could be 50.
this is the code to create the js objects
$kickbtn .= " $('#kick_btn$k').click(function(event) {
var player_name$k = jQuery('input[name=\"player$k\"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name$k} );
alert('Successfully kicked');
});\n\n";
this is the form data
<form name=\"$pdata[name]\" action=\"\">
<input type=\"hidden\" name=\"player$k\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn$k\" value=\"Kick Player\">
</form>
$k++;
Is there an easier way to accomplish this without creating all this excess code?
The output is nice in the html, and it does work, just hoping theres something a little more dynamic i can do, and not so messy in the code. Below is from the parsed code and works and looks good.
$('#kick_btn14').click(function(event) {
var player_name14 = jQuery('input[name="player14"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name14} );
alert('Successfully kicked');
});
Only one delegated event handler is needed, which means attaching it to a parent/container element, unless you want 50+ click handlers in your document which will unnecessarily slow things down:
// bind to all elements starting with 'kick_btn' within #container
// (could even be 'body')
$("#container").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name + num
});
alert('Successfully kicked');
});
Reference:
http://api.jquery.com/attribute-starts-with-selector/
http://api.jquery.com/delegate/