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.
Related
In my code below I want display $("#searchresults").html(data) this result to other page.
$.ajax({
type: "POST",
url: base_url + 'front/searchresult',
data: data,
success: function(data) {
alert("test");
var val = $("#searchresults").html(data);
window.location.assign("<?php echo base_url()?>front/search/" + val);
}
});
what exactly is in the data variable you receive from your post? is it a json object? is it plain text?
if it is html, I think you should consider placing the result in a div on the current page, and hide items you don't want to see after searching
relocating after ajax requests is not the way to go. Is it an option in your case, to use a form and change the action attribute of the form to your new location?
<form action="front/search/">
<input type="text" name="data">
</form>
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');
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.
<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});
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.