raduenea Posted September 1, 2021 Share Posted September 1, 2021 Hi, Please help me with the following situation. I have a jquery code like this: $('#go').on('click', function () { $.ajax({ type: 'POST', url: 'returnPDO.php', dataType: "json", data: { id: "1", rows: "7" }, success: function (data) { ...CODE.... } }); }); Now, I have another event (keypress) that I would like to execute the same code from on.click above . $( "#searchTbl" ).keypress(function() { $.ajax({ type: 'POST', url: 'returnPDO.php', dataType: "json", data: { id: "1", rows: "7" }, success: function (data) { ...CODE.... } }); }); It's there a way to include the whole $.ajax code only once ? Otherwise if I change something inside on.click I need to change on keypress code as well. Thank you Quote Link to comment https://forums.phpfreaks.com/topic/313644-include-the-script-only-once/ Share on other sites More sharing options...
Solution kicken Posted September 1, 2021 Solution Share Posted September 1, 2021 Make it a named function, then pass the name to your event handlers. function loadData() { $.ajax({ type: 'POST', url: 'returnPDO.php', dataType: "json", data: { id: "1", rows: "7" }, success: function (data) { ...CODE.... } }); } $("#searchTbl").keypress(loadData); $('#go').on('click', loadData); Quote Link to comment https://forums.phpfreaks.com/topic/313644-include-the-script-only-once/#findComment-1589551 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.