We have answer of your question!

100% solved queries, no empty question

Question: Fire ajax multiple times


0

Advertisement


How do I get this ajax function to fire for each input field? Currently It only fires for the first field and no others without the page being refreshed.

html:

<input id='item_name_1' value='item_name' onclick='test("1",  "item_name");'/>
<input id='item_value_2' value='item_value' onclick='test("2", "item_value");'/>

Jquery:

   function test(id, field_name){

    $('#'+field_name+'_'+id).keyup(function(){
        $.ajax({
            type: "POST",
            url: "/admin/shop/update_harmonized_details",
            data:{
                id: id,
                field_name: field_name,
                field_value: $('#'+field_name+'_'+id).val()
            },
            success: function(resp){
                if(resp.msg == 'Success'){
                    alert('Value Updated');
                }
            }
        })
    });
}
Question author Kisaragi | Source

Answer


1


Advertisement


<input id='item_name_1' value='item_name' class="listenToMe" />
<input id='item_value_2' value='item_value' class="listenToMe" />

 $('.listenToMe').keyup(function(){
     var value = $(this).val();
     var fieldID = $(this).attr('id').split('_');
     var id = fieldID[2];
     var name = fieldID[0] + '_' + fieldID[1];
     console.log('Value: value');
     console.log('ID:'+ id);
     console.log('Name:'+name);
 });

https://jsfiddle.net/vyeL9xu1/

If you wanted to avoid parsing the id attribute you could just use data attributes and reference the values with $(selector).data('attributename'). So like you could add data-fieldname to the input and reference it with $(this).data('fieldname').

Additionally it looks like you are updating data based on 'keyup'. AJAX calls are asynchronous and won't necessarily reach, process, or finish when you expect. You could potentially run into problems here. If someone typed in 'John' it would be sent to the server in that order, but o or h could get there last and then it wouldn't save it correctly. It would be best to either provide a save button or only fire a new event after the previous is complete, something like that.

Answer author Leeish

Advertisement


Tickanswer.com is providing the only single recommended solution of the question Fire ajax multiple times under the categories i.e jquery , html , . Our team of experts filter the best solution for you.

Related Search Queries:

how to stop multiple ajax requests , call ajax multiple times , jquery click event firing multiple times ,

You may also add your answer!