Print the value in loop in Jquery ready function - php

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.
Here is my code:
$(document).ready(function() {
var link = $('a[id]').size();
//alert(link);
var i=1;
while (i<=link)
{
$('#payment_'+i).click(function(){
//alert($("#pro_path_"+i).val());
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
//alert(data);
$("#container").html(data);
});
});
i++;
}
});
Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.
I think onready event it should have parsed the document and the values inside the loop
I’m not sure where I went wrong. Please help me to get my intended result.
Thanks, all

I would suggest using the startsWith attribute filter and getting rid of the while loop:
$(document).ready(function() {
$('a[id^=payment_]').each(function() {
//extract the number from the current id
var num = $(this).attr('id').split('_')[1];
$(this).click(function(){
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){
$("#container").html(data);
});
});
});
});

You have to use a local copy of i:
$('#payment_'+i).click(function(){
var i = i; // copies global i to local i
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
$("#container").html(data);
});
});
Otherwise the callback function will use the global i.

Here is a note on multiple/concurrent Asynchronous Requests:
Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.
So it is only natural that you get only the response from the last request.

What if you added a class to each of the links and do something like this
$(function() {
$('.paymentbutton').click(function(e) {
$.post("<?php echo $base; ?>form/setpropath/",
{pro_path: $(this).val()},
function(data) {
$("#container").html(data);
});
});
});
});
Note the use of $(this) to get the link that was clicked.

Related

Dynamic element ID in jQuery script on click event

I'me trying to implement an on/off button on a php loop but I can't make it work because of the id of jQuery event. How can I get the correct id on click and pass it to the rest of the script?
The problem is in the $('#myonoffswitch')...
<script type="text/javascript">
$(document).ready(function(){
$('#myonoffswitch').click(function(){
var myonoffswitch=$('#myonoffswitch').val();
var wnfID=$('#wnfID').val();
if ($("#myonoffswitch:checked").length == 0) {
var a="2";
var b=wnfID;
} else {
var a="3";
var b=wnfID;
}
$.ajax({
type: "POST",
url: "ajax_wnf_status.php",
data: "statusWnf="+a+"&wnfID="+b,
success: function(html) {
$("#display").html(html).show();
}
});
});
});
</script>
I'm generating different id's for the loop rows (ex: id="#myonoffswitch1" ; id="#myonoffswitch2"; etc).
I'm not certain I fully understand the question, but .val() will not get the ID of an element. You should use .attr('id') instead.
Also, it looks like you're trying to format data for a GET request, not a POST.
If I understand the question correctly, I think you're looking for
event.target.id
where 'event' is passed in to your handler:
('#myonoffswitch').click(function(event){
id = event.target.id
. . .
Though at that point, you might not need the id, since you can just use event.target directly.

How to REF a PHP Codeigniter controller function inside of jQuery? (Populate a dropdown menu based on current selection))

The issue is how do I POST the value of the first dropdown selected to my Codeigniter controller using jQuery/AJAX. Here is an example of what I need to do http://css-tricks.com/examples/DynamicDropdown/
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val());
});
In the .load() I want to be able to pass the value of #first-choice to my controller.
How can I do that? Thanks!
$("#first-choice").change(function() {
var str = '';
$.ajax({
url: 'getter.php',
type:'GET',
dataType:'json',
data:'choice='+ $("#first-choice").val(),
success:function(data){ //you must return your data as id and value for the selectbox
$.each(data as function(v){
str+='<option value="'+v.yourid+'">'+v.yourvalue+'</option>';
});
$("#second-choice").html(str);
}
});
});
try this
$("#second-choice").load("getter.php",{choice:$("#first-choice").val()},function(){
//do something here
});
this will POST the additional parameters to the server and a callback that is executed when the server is finished responding.
Try this:
$("#first-choice").change(function() {
$("#second-choice").load("<?php echo site_url('controller-name/method-name'); ?>/" + $("#first-choice").val());
});
NOTE: I have used forward trailing slash to pass your dropdown value as a parameter to your method but this is not necessary you can also pass using get or post method

Reverting selectbox option back if

So i've a situation where I have a selectbox that makes a jquery .post call to another script on a .change event.
I was wondering if there is anyway i can revert the selectedoption back to the original default should something occurs or that my .post event fail?
Hi ppl, I'm sorry.
Here's the javascript code. I've made some amendments to it. I'm trying to get the second line to work as this code is not working now due to some errors(due to don't know what on the second line). My selectbox is part of a list so i'm not able to make it a unique id to it and to remember the box the user selects, i need to use $(this).
$('.order_stateselect').click(function(){
var val=$(this).find(":selected").val();
$(this).change(function(){
if(confirm('Confirm Order Status Change?')){
var conduct_status_chge=$.post('/seller/helpers/order_status_change.php',{order_item_id:$(this).parent('td').siblings('.order_item_id').text(),order_item_status:$(this).find(':selected').val()},function(data){
alert(data);
})
.error(function() { alert("error"); })
}
});
});
Difficult to tell without code, but I'll try
$("#selectbox").data('origValue', $("#selectbox").val());
$("#selectbox").on('change', function () {
$.post(...).done(function () {
// other stuff
$("#selectbox").data('origValue', $("#selectbox").val());
}).fail(function () {
$("#selectbox").val($("#selectbox").data('origValue'));
});
});
Use something like this
var value=$("#selectbox").val();
$.ajax({
type:post,
url:"something.com",
success:function(){
},error:function(){
$("#selectbox").val(value);
}
})
$('select').val('defaultvalhere');
You could use this to select first option not regarding default value:
$('#selectId option:eq(0)').attr('selected',true);
you can simply use a global variable to save the option selected previously. Once save you can just use that on your error Its something like this
<script type="text/javascript">
this.previousVal = 0;
function changeHandler(selectBox)
{
$.ajax({
type:post,
url:"URL",
success:function(){
//ur code
this.previousVal=selectBox.selectedIndex;
},error:function(){
//use previousVal and set the value back to the previous value
}
})
}
</script>
<select id="changeLang" name="changeLang" onchange="changeHandler(this)"></select>

How to check whether a div is updated?

I have got site with dynamic refreshing divs.
Source:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$('#loaddiv').fadeOut('slow').load('boo.php').fadeIn("slow");
$('#loaddiv2').fadeOut('slow').load('boo2.php').fadeIn("slow");
}, 1000);
</script>
But I want fadeout and fadein only if boo.php return different(updated) value than actuall div. How compare new and actuall value and do this?
P.s Sorry for bad English but I'm Polish
You'll need to write a callback function that inspects the returned data and compares it to what's stored within the div already. Additionally, the functions that show/reveal the div will probably need to be moved to the callback function as well.
Documentation is available here.
You'd have to write an Ajax function to boo.php and compare the result with the div's value
$.ajax(
{
url: "boo.php",
success: function(result)
{
if($("#loaddiv").html() != result)
{
$("#loaddiv").fadeOut("slow")
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
}
}
});
You need to check the result you are getting from the ajax call and compare it with the current content. Assuming you have an element with ID MsgCount in your Ajax response and current Div Markup and you are using the value of that to compare, the below code will work
$(function() {
var auto_refresh = setInterval(function(){
var currentMsgCount= $('#MsgCount').text();
$.get("boo.php",function(data){
var resultData=$(data);
var newMsgCount= resultData.filter('#MsgCount').text();
if(newMsgCount!=currentMsgCount)
{
//content is different. Let's show it
$('#loaddiv').fadeOut('slow',function(){
$('#loaddiv').html(data).fadeIn("slow");
});
}
});
}, 1000);
});

What is the correct way to bind events in jQuery?

For example in php I have a list of clients:
foreach($clients as $client)
echo '<li id="client_'.$client->id.'">' . $client->name . '</li>';
What is the correct way to bind a click event to each list item w/o using
onclick="my_function(the_elements_id)"
right in the list item.
assuming you have a ul with id="client_list"
$("#client_list li").click(function()
{
var myid = $(this).attr("id"); // the clicked on items id
// do your thing here.
}):
And very cool "live" way of binding for all current and future matched elements. This comes in handy if you use Ajax, and have to re-bind event to let's say image that you fetch via ajax.
More info # http://docs.jquery.com/Events/live#typefn
$("p").live("click", function(){
alert( $(this).text() );
});
You can also use .bind
E.g.
$('#item').bind("click", function() { do something; });
$(document).ready(function(){
$("li).click(function(){
var id = $(this).attr("id");
your_function(id); //The function you want to run with the object's ID as a parameter.
});
});

Categories