call ajax in separate javascript function - javascript

I am new in jquery, ajax but I want to call ajax in separate javascript function because that JSP file is dynamically created and button id in JSP file is also created using for loop.
I sharing my code and is there is a solution for this to pass button id to jquery function and pass that id to ajax calling through Jquery.
Here is code for .js file to call ajax through jquery :
function insertData(idvalue)
{
var forsplit = idvalue.id.split("_");
var qtsrl = forsplit[2];
var qtno = forsplit[3];
var queryid=idvalue.id;
var qtsrl_id = document.getElementById("qstn_srl_"+qtsrl+"_"+qtno).value;
var qstn_no_id = document.getElementById("qstn_no_"+qtsrl+"_"+qtno).value;
$.ajax(
{
type: "GET",
url: "aftermarksave.jsp",
data:{setvalues : qtsrl_id},
contentType: "application/json",
async: false,
success: function (data)
{
alert("Data passed");
},
error: function(data)
{
alert('Not passed Data: '+qtsrl_id);
}
});
}
Here I want to pass"qtsrl_id" to "aftermarksave.jsp" through Jquery:Ajax
And here is my dynamically generated .JSP file that "this" is passed to javascript function and extract current id from "this" object
fw1.write("<td><lable for='marksimilar'>"+getmarkentry+"</lable>");
fw1.write("<input type='hidden' id='markentry_"+getmarkentry+"' value="+getmarkentry+">");
fw1.write("<br>");
fw1.write("<label>Serial No</label>");
fw1.write("<br>");
fw1.write("<input type='text' size='10' id='qstn_srl_"+queserial+"_"+queno+"' onBlur='makecapital();doOnBlur(this)'>");
fw1.write("<br>");
fw1.write("<label>Question No</label>");
fw1.write("<br>");
fw1.write("<input type='text' size='10' id='qstn_no_"+queserial+"_"+queno+"' onBlur='doOnBlur(this)'>");
fw1.write("<br>");
fw1.write("<input type='button' id='btn_mark_"+queserial+"_"+queno+"' onClick=**'insertData(this)'** value='Mark'>");
fw1.write("<br>");
if(getmarkentry.equals(""))
{
fw1.write("<input type='button' id='btn_delete' onClick='mark_same()' value='UnMark' disabled='disabled'></td>");
}
else
{
fw1.write("<input type='button' id='btn_delete' onClick='mark_same()' value='UnMark'></td>");
}
fw1.write("</tr>");
fw1.write("<tr>");
In above code "insertData(this)" is called when clicked on button and I want on that click that ajax is called through jquery. how we achieve this in javascript function.

You can use something like this the following:
Put your Ajax script in a function:
function functionWithAjaxScript(qtsrl_id){
$.ajax(
{
type: "GET",
url: "aftermarksave.jsp",
data:{setvalues : qtsrl_id},
contentType: "application/json",
async: false,
success: function (data)
{
alert("Data passed");
},
error: function(data)
{
alert('Not passed Data: '+qtsrl_id);
}
});
}
trigger the function with .on() when your button is clicked:
$(function() {
$("#mybuttonid").on("click",function(){
functionWithAjaxScript(param);
});
})
I hope this helps.

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

Passing parameters between html pages using jquery

I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')

jQuery is not getting applied

I am working on notification system and loading html notification body from database to views which populate as follows:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and applying jQuery function which I already defined on same page is like this:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
});
So when user click on button it's not work even not showing alert.
But things gets more interesting when I inject above jquery function from chrome console while view is loaded and button start working fine and shows alert too!
I am not getting the point which not letting things work!
It's because your acceptingRequest function is visible only inside anonymous jQuery(document).ready callback.
So when you click the button acceptingRequest is not visible.
Solutions keeping jQuery(document).ready(function() {})
To solve this bind the handler inside the callback using $('button.acceptinvite').on('click',acceptingRequest)
or use an anonymous callback (something like this):
$('button.acceptinvite').on('click',function(){
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
});
In both cases remove onclick="acceptingRequest();" since it's no longer needed.
Another option is to make acceptingRequest visible outside using a global variable (it's not a good practice anyway):
acceptingRequest = function () {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
Now acceptingRequest is visible outside jQuery().ready and you can do onclick="acceptingRequest();"
Solutions without jQuery(document).ready(function() {})
If you don't need the DOM to be completely loaded (like in this case) you can remove
jQuery(document).ready(function() {}) and just write your function from in head, so they are visible to the button.
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
</script>
Let me know if this was useful.
I think you are defining the function acceptingRequest() on document ready, but you are not really calling it. Try adding:
acceptingRequest();
just after the definition of the acceptingRequest() function. The result would be:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
acceptingRequest();
});
It is because this string
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
will be proceded by the browser earlier than the definition of your acceptingRequest function. 'acceptingRequest' in your code will be defined asynchronously when document ready fired. So browser can't assign it with the click listener. Try to put your script exactly before </body>(and after jQuery script) and without jQuery(document).ready
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
</script>
</body>
Function defined in ready state can be used in it's own scope.So you can use acceptingRequest() method in ready state.
in my view below code is bestpractice in event binding:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" id="acceptInviteButton" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and in ready state:
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
$("#acceptInviteButton").on("click",acceptingRequest);
});

onclick function doesn't work in an Ajax loaded button

So, I have a website which after selecting day loads some forms with Ajax request. In this loaded website (I just add its content to a modal), I have a button
<button class="btn btn-success" type="button" onclick="addInput()" name="add">
Dodaj kolejny przedziaƂ.
</button>
Which should call the function addInput(), which is defined in the "master" html file
<script type="text/javascript">
$(document).ready(function() {
fields = 0;
function addInput() {
alert("dodajemy");
if (fields != 24) {
document.getElementById('text').innerHTML += "test<br>";
// document.getElementById('text').innerHTML += "Poczatek: <input type='text' value='' />Koniec: <input type='text' value='' /><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "No wiecej ci nie potrzeba<br>";
}
};
$.ajaxSetup({ cache: false, type: 'POST',
headers: { "cache-control": "no-cache" } });
$("#wybierz_pokoj").submit(function() {
var url = "/testowa/wybierz_pokoj" // the script where you handle the form input.
document.getElementById("modal").innerHTML = "Czekamy"
$.ajax({
type: "POST",
url: url,
evalJS: true,
data: $("#wybierz_pokoj").serialize(), // serializes the form's elements.
cache: false,
success: function(data)
{
document.getElementById("modal").innerHTML = data;
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
And after clicking the button, I'm getting "Uncaught ReferenceError: addInput is not defined" error.
What am I doing wrong?
The best solution is not to write inline JS and use jQuery the way it was intended to be used.
Remove the onclick from your HTML and bind the event with jQuery.
$(document).ready(function() {
$('button[name="add"]').on('click', function(){
addInput();
});
fields = 0;
function addInput() { // etc etc
You don't really need the function within the scope of that dom.ready either.
Demo
You've defined the function inside the document.ready call - try defining it outside like so:
<script type="text/javascript">
function addInput() {
alert("dodajemy");
if (fields != 24) {
document.getElementById('text').innerHTML += "test<br>";
// document.getElementById('text').innerHTML += "Poczatek: <input type='text' value='' />Koniec: <input type='text' value='' /><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "No wiecej ci nie potrzeba<br>";
}
};
$(document).ready(function() {
fields = 0;
$.ajaxSetup({ cache: false, type: 'POST', headers: { "cache-control": "no-cache" } });
$("#wybierz_pokoj").submit(function() {
var url = "/testowa/wybierz_pokoj"; // the script where you handle the form input.
document.getElementById("modal").innerHTML = "Czekamy";
$.ajax({
type: "POST",
url: url,
evalJS: true,
data: $("#wybierz_pokoj").serialize(), // serializes the form's elements.
cache: false,
success: function(data)
{
document.getElementById("modal").innerHTML = data;
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
I'm not sure what you're doing with the "fields" variable, but if you need it ay any point, make sure it's also declared outside the document.ready function as well.
The problem is scope. The addInput function is inside the the document.ready() anonymous function, so it's not visible outside that scope. Javascript in onXXX attributes is executed in the global scope, so it can't access addInput.
The simplest solution is to move the definition of addInput outside the anonymous function, or change it to:
window.addInput = function() {
...
};
Or instead of using inline Javascript, you could use event delegation. See Event binding on dynamically created elements?

Can AJAX update a button argument?

Using AJAX, I'm able to extract a data value from a button click, but is it possible to ensure this value is passed on to an argument within another button on the same page?
test.html:
Activate
Fader
test.js:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
}
});
}
The php file connects to the database and extracts the most recent image number - it works fine and the alert box displays the correct value. So what would be the next step to ensure the "image_number" argument is updated with this 'data' value?
Cheers.
make a global variable like
windows.image_number = 0;
for AJAX function.
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
//update the global variable
windows.image_number = data;
}
});
}
Assuming that the image_number variable that you are passing to the function is a globally defined variable, you simply need to set the variable in your success callback:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
// Assuming data holds the image number you want to use for next click
image_number = data;
}
});
}

Categories