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.
Related
i am trying to use toggle buttons to save response in db as yes or no. for some reason the only response i am getting is 'on'. even when i switch off the button. i tried searching for problem and got a match but the problem was asked for android platform.now i am stuck with no answer there where similar questions but none of them is useful for me at this moment. sharing the code down below.Thanks in advance for those who are going to suggest or provide a solution.i am using class handicap to save data into variable inside JQUERY and then send that variable to AJAX page to perform db operation.i am not sharing CSS for toggle as i don't think that is required right now. if u need any additional info, do inform me.this input is inside a form with method POST. i am using a submit button with id that is calling this JQUERY.
html part
<div class="switch">
<input id="cmn-toggle-4" class="cmn-toggle cmn-toggle-round-flat handicap" type="checkbox" name="handicap">
<label for="cmn-toggle-4"></label>
</div>
jquery
$("#save-medical-1").click(function () {
var m11 = $(".handicap").val();
alert(m11);
$.ajax({
url: "ajexupdate.php",
type: "POST",
data: {smsgs11: m11},
dataType: 'text',
cache: false,
success: function (e) {
// alert(e);
$("#user_medical_form").html(e);
$("#medidetail").modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
}
});
return false;
});
You can get value using ":checked" using jquery.
eg.
if($("#cmn-toggle-4").is(":checked")){
m11="yes";
}
else{
m11="no";
}
and send it through ajax.
By writing a php command you are setting the initial value of that input into m11. You have to catch the client side value of input instead:
your code:
var m11 = '<?php echo $_POST['handicap']; ?>'; // always returns the initial value
Correct clien-side code:
var m11 = $(this).val();
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 series of Form Elements each with different names, I'll post one as an example. I cannot hard code the name into Jquery because unless I inspect the element, I won't know the name.
With that aside heres the element:
<label class="checkbox">
<input type="checkbox"
name="aisis_options[package_Aisis-Related-Posts-Package-master]"
value="package_Aisis-Related-Posts-Package-master" checked="" />
Aisis-Related-Posts-Package-master
(Disable)
</label>
The catch is to do this:
Grab the name of this element - upon clicking disable - and do two things, one - if the element is checked, which in this case it's not, unchecked it, two pass the name to a php variable, which then can do processing.
How would I do this? Jquery is not my strong area.
Here is a example without knowing more of your code:
$(function () {
$('input:checkbox').click(function () {
$(this).prop('disabled', true);
var iName = this.name;
$.ajax({
url: "file.php",
data: {
'inputname': iName
},
success: function (data) {
alert(data.returned_val);
}
})
})
})
Demo here
If you want to reach the input via name directly you need to use double backslasshes to escape the square brackets and reach that input via name. Use:
$('input[name=aisis_options\\[package_Aisis-Related-Posts-Package-master\\]]')
You can add an onchange with checkbox
onchange="f(this);"
in js f() function you can use this.name to get the name, this.value to get value etc and do whatever you want.
To check/unckeck, you can use $element.prop('checked', true/false); like this (fiddle):
HTML
<input
type="checkbox"
name="aisis_options[package_Aisis-Related-Posts-Package-master]"
value="...."
checked="checked"
/> Aisis-Related-Posts-Package-master
(Disable)
JS
$('.trigger').click (function () {
closest_checkbox = $(this).siblings('input[type=checkbox]');
closest_checkbox.prop('checked', !closest_checkbox.prop('checked'));
});
JS part 2: AJAX
You can build an object with all your name:value combinations using the jQuery plugin serializeObject, your form submission event handler would be something like:
$('form').submit( function (e) {
// Prevent the form from being sent normally since we want it ajaxified
e.preventDefault();
// Send request to php page
$.ajax({
type: "POST",
url: "some.php",
data: $('form').serializeObject() // <== Magic happens here
});
});
PS. Don't forget to include the serializeObject plugin and give a unique id to the form, $('#unique_id') is way better than $('form') which will match all the forms in the page.
To grab the value of name attribute, you can use:
$(this).attr('name');
Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!
Hi everyone I have been working on this particular problem for ages by now,plz help.
I have looked at jQuery: Refresh div after another jquery action?
and it does exactly what I want but only once! I have a table generated from db and when I click on delete it deletes the row and refreshes the div but after which none of my jquery functions will work.
$('#docs td.delete').click(function() {
$("#docs tr.itemDetail").hide();
var i = $(this).parent().attr('id');
$.ajax({
url: "<?php echo site_url('kt_docs/deleteDoc'); ?>",
type: 'POST',
data: 'id=' + i,
success: function(data) {
$("#docs tr.itemDetail").hide();
$("#f1").html(data); // wont work twice
//$("#docs").load(location.href+" #docs>*"); //works once as well
}
});
});
in my body I have
<fieldset class='step' id='f1'>
<?php $this->load->view('profile/docs_table'); ?>
</fieldset>
profile/docs reads data from db. <table id='docs'>....</table>
and my controller:
function deleteDoc() {
$id = $_POST['id'];
$this->load->model('documents_model');
$del = $this->documents_model->deleteDocument($id);
return $this->load->view('docs_table');
}
Thanks in advance!
Are you removing any expressions matching $('#docs td.delete') anywhere? If so, consider using $.live(), which will attach your function to ALL matching elements regardless of current or in the future; e.g.
$('#docs td.delete').live('click', function() {
// Do stuff.
});
http://api.jquery.com/live/
Try using bind() instead of click(). The click() method won't work on dynamically added elements to the DOM, which is probably why it only works the first time and not after you re-populate it with your updated content.
You should just have to replace
$('#docs td.delete').click(function() {
with
$('#docs td.delete').bind('click', function() {
Are you replacing the html elements that have the events on them with the data your getting through ajax? If you end up replacing the td.delete elements, then the new ones won't automatically get the binding.