I have some code to clone the input field directly preceding the clone 'button' renaming the id and name of the field as it goes (shown below): -
$(".clone").live('click', function () {
var doppleganger = $(this).prev(); // Neater referencing.
$(doppleganger).clone().insertAfter(doppleganger);
$(this).prev().attr("id", "input" + increment).attr("name", "input" + increment);
increment++;
return false;
});
.
The form (#adv_magic) data is loaded on the fly with the jquery ajax event and submitted thusly: -
$("#adv_magic").live('submit', function() {
$("#editor_button, #date_select, #search").hide();
$(".loader").show();
$.ajax({
type: "POST",
url: "./scripts/aquire_template.php",
data: $("#adv_magic").serialize(),
success: function(html){
$("#right_container").empty();
$(".loader").fadeOut(350);
$("#right_container").html(html);
}
});
return false;
});
However my cloned input fields are not being processed when the form is posted to my script. I've seen a few tutorials about creating the input fields as an array but i'd rather not mess around with that at this stage if there is anything else I can do.
I'm wondering also if it's to with the way I am serializing the form? I can't post the full code or a link on this occasion unfortunately as the application is not available from the web. Any thoughts on this would be really appreciated! I'm stumped!
Update Sat 10th 20:31 GMT >
I got the following report from the console > post tab in firebug: -
input1 meeting
input2 select date
input3 enter text
input5 NUMBER MISSING
input6 enter text
input7 test
switch 1
Source
input1=meeting&input2=select+date&input3=enter+text&input6=enter+text&input7=test&input5=NUMBER+MISSING&switch=1
Inputs 5/6/7 are cloned elements so presumably they are being passed to the script?
Update Sat 10th 21:06 GMT >
Echoing the string variable before it is being processed by the script shows non of the cloned input fields.
This one worked for me.
<form id="myForm">
<fieldset>
<input type="text" id="input1" name="input1"/><input type="button" value="clone" class="clone"/>
</fieldset>
<input type="submit" value="submit" id="sbmt"/>
</form>
$(".clone").live("click", function(e) {
var count = $("#myForm fieldset").length + 1;
$(this).parent().clone().insertBefore("#sbmt").find("input[type=text]").attr({
"id": "input" + count,
"name": "input" + count
}).val("");
});
$("#myForm").submit(
function(e) {
e = e || window.event;
e.preventDefault();
$.ajax({
type: "GET",
url: "/",
data: $("#myForm").serialize(),
success:function(data){
}
});
return false;
});
demo: http://jsfiddle.net/wFzx5/2/
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 am trying to send some dynamically created input field values to PHP to validate them and make some checks in the database in the background. I don't want to use submit form but just check the fields after click a button.
Html:
<input name="clockpick" class="input-mini timeinputfrom" data-format="hh:mm" type="text"></input>
<input name="clockpick" class="input-mini timeinputfrom" data-format="hh:mm" type="text"></input>
<button id="check" class="btn btn-primary">check</button></div>
The input boxes can be dynamically created depending how many are necessary. I get the values into jquery but don't find any possibility to send them via post to php.
Jquery:
$('#submit').on('click', function() {
var inputfield = $('input[name="clockpick"]');
$('input[name="clockpick1"]').each(function( index, element ) {
console.log( "Wert" + index + ": " + $( element ).val() );
});
$.ajax({
type: "POST",
url: "productiontimevalidate.php",
data: ????
});
How can I send the values / array to PHP?
Another way would be to add the values to an array, and convert it to json for sending.
var allClockPicks = [];
$('input[name="clockpick1"]').each(function( index, element ) {
allClockPicks.push($(element).val());
});
Then, the ajax can send data as
data: {cp: JSON.stringify(allClockPicks)}
On the php side, you can json_decode them as below:
$cpArray = json_decode($_POST['cp'], true);
If your elements are inside <form class="my-form"> [elements...] </form>
You can use this short version:
<script>
$.post('/my/path/app.php', $('.my-form').serialize(), function(r) {
console.log(r);
},'json'); // parse response as JSON
</script>
app.php
<?php
echo json_encode(array('success' => true, 'post', $_POST));
?>
I have a form on a page that accepts an 'ID', user inputs ID eg; 1026
The form submits to the same page ajax grabs the ID checks it against another site. I need to be able to let the form post if the response is NOT a 404 error and $_GET is true.
Heres what I have
<script>
$(document).ready(function(){
$('form#getid').submit(function(){
var theid = $('input#id').val();
var dataString = "id=" + theid;
$.ajax({
type: "POST",
data: dataString,
success: function(response, status, xhr){
if(status=="success") {
$("#err-404").html(response);
}
else { alert(status+ ' - '+ xhr.status); }
}
}
});
});
return false;
});
</script>
My form
<form id="getid" action="">
<input type="text" name="id" />
<input type="submit" class="button" value="Go">
<div class="error" id="err-404"></div>
I think im on the right track, just not sure how to put it all together.
Firstly, if you don't have to use a string for your data, don't. You can use an array like so:
$.ajax({
type: "POST",
data: {'id': theid },
Which is cleaner and more maintainable.
As for your question, your code is a little unclear, but what you probably should do is return false at the end of the submit() event to prevent the form from submitting, and then in the AJAX event, if it's cleared for submission, do a $('#getid').submit(). You may have to set some kind of flag (a hidden input or a data attribute) that you check on to avoid the AJAX-triggered submit from checking again, resulting in an infinite loop.
A note here: 404s should cause the error() callback in the AJAX handler to fire, so a 404 won't trigger the success callback you have set up.
JQUERY:
$(document).ready(function(){
$('form').submit(function(){
var content = $(this).serialize();
//alert(content);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/test/generate',
timeout: 15000,
data:{ content: content },
success: function(data){
$('.box').html(data).fadeIn(1000);
},
error: function(){
$('.box').html('error').fadeIn(1000);
}
});
return false;
});
});
HTML:
<form>
<input type="checkbox" value="first" name="opts[]">
<input type="checkbox" value="second" name="opts[]">
<input type="checkbox" value="third" name="opts[]">
<input type="submit">
</form>
How do i process (or read) multiple checked checkbox's value in PHP? I tried doing $_POST['content'] to grab the serialized data but no luck.
Replace:
data:{ content: content } // <!-- you are prefixing with content which is wrong
with:
data: content
Now in your PHP script you can use $_POST['opts'] which normally should return an array.
Try
echo $_POST['opts'][0]. "<br />";
echo $_POST['opts'][1]. "<br />";
echo $_POST['opts'][2]. "<br />";
You post an array to the Server and it is available in the post variable 'opts'. Remember: Unchecked boxes dont get posted.
The chosen answer still didn't work for me, but here is what did:
var checkedBoxesArr = new Array();
$("input[name='checkedBoxes']:checked").each(function() {
checkedBoxesArr.push($(this).val());
});
var checkedBoxesStr = checkedBoxesArr.toString();
var dataString = $("#" + formID).serialize() +
'&checkedBoxesStr=' + checkedBoxesStr;
[The above code goes in your javascript, before serializing the form data]
First, cycle through the checked boxes and put them into an array.
Next, convert the array to a string.
Last, append them to the serialized form data manually - this way you can reference the string in your PHP alongside the rest of the serialized data.
This answer came partly from this post: Send multiple checkbox data to PHP via jQuery ajax()
there are an Error in your code :
The url should be url: 'http://localhost/test/generate.php' with the extension name
This is a very simple form that I have found on the web (as I am a jQuery beginner).
<!-- this is my jquery -->
<script>
$(document).ready(function(){
$("form#submit_wall").submit(function() {
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
</script>
<!-- this is my HTML+PHP -->
some PHP ...
while($row_pilt = mysql_fetch_assoc($select_pilt)){
print
<form id="submit_wall">
<label for="message_wall">Share your message on the Wall</label>
<input type="text" id="message_wall" />
<input type="hidden" id="id" value="'.(int)$row_pilt['id'].'">
<button type="submit">Post to wall</button>
</form>
and down below is my PHP script that
writes to mySQL.
It is a pretty straight forward script. However, it is getting little complicated when I submit it. Since I have more than one form on my page (per WHILE PHP LOOP), thus when I submit - only the FIRST form gets submitted. Furthermore, any other subsequent forms that I submit - data is being copied from the first form.
Is there any jQuery functions that clear the data? - or is there a better solution.
Thanks,
Nick
It's because you're giving each form the same id, and thus it is submitting the first element it finds with that id, i.e. the first form. What you should do is assign a unique id to each form, and then give each form an AJAX submit function that submits the form-specific data. You can use jQuery's $.each() function to loop through all the forms and $(this).attr('id') within the submit function to retrieve the form-specific id.
UPDATE: As revealed by the comment on this answer, you actually don't need the each() function because jQuery applies it to every form element anyway.
Here would be an example script:
$(document).ready(function(){
$("form").submit(function() {
var message_wall = $(this).children('input[type="text"]').attr('value');
var id = $(this).children('input[type="hidden"]').attr('value');
$.ajax({
type: "POST",
url: "index.php?leht=pildid",
data:"message_wall="+ message_wall + "&id="+ id,
cache: false,
success: function(){
$("ul#wall").prepend(""+message_wall+"", ""+id+"");
$("ul#wall li:first").fadeIn();
alert("Thank you for your comment!");
}
});
return false;
});
});
Because we can't see all of your forms, I'm not entirely sure, but given your question I'm going to assume that the other forms all share the same id (form#submit_wall), which is invalid an id must be unique within the document.
Given that you're going to change the id of the other forms (I'd suggest using a class name of, probably, 'submit_wall', but the specifics are up to you), the jQuery needs to be changed, too. From:
$("form#submit_wall").submit(function() {
To:
$("form.submit_wall").submit(function() { // using the class-name instead of the id.
Now, of course, you run into the same problems of duplicate ids.
So I'd suggest, again, changing the id to a class and changing:
var message_wall = $('#message_wall').attr('value');
var id = $('#id').attr('value');
to:
var message_wall = $(this).find('.#message_wall').attr('value');
var id = $(this).find('.id').attr('value');
Given the mess that you've posted, above, I find it hard to believe that this is all you need. It would definitely be worth posting the full page (or a demo at JS Fiddle or JS Bin) that fully reproduces your code.