i am calling a ajax function to check if the inputted data
already exists in the database.
my ajax code is like this.
$(document).on('change','.lawregno',function(){
/// Your validation logic
var regno = $(this).val();
if(regno)
{
var data = 'regno='+ regno; // this where i add multiple data using ' & '
$.ajax({
type: 'POST',
dataType: "json",
data: data,
url: "{{ URL::to('admin/check_regno_exit') }}",
success: function (response) {
if(response=="1")
{
alert('LawRegNo Already Exists');
return false;
}
}
});
}
else
{
return false;
}
});
how should i make the data reset after alert message is shown.
Based on your comment above:
i want to set $(this).val() to null after ajax call is made
First, capture a reference to this since it will no longer be in the same scope. Any variable will do:
var data = 'regno='+ regno;
var element = this;
$.ajax({
//...
});
Then you can use that element variable in your callback function to set the value of that element:
success: function (response) {
if(response=="1")
{
alert('LawRegNo Already Exists');
$(element).val('');
}
}
you can do it inside the success handler . First you have to set a variable with the reference of $(this) like below
var elm = $(this);
Then you can refer it in the success callback.
success: function (response) {
if(response=="1")
{
alert('LawRegNo Already Exists');
elm.val('');
return false;
}
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a button that when I click on it , it will get data from my database , and display it on my text area based on the id.
JQuery
$('#verifyBtn').on("click", function() {
var exeOutput = checkOutput();
$("outputArea").html(exeOutput);
});
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
function getOutput(dataStr, flag) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
return data;
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
Through my servlet for getting from my database.
Servlet
exercisesModel outputModel = null;
try {
DBConnection db = new DBConnection();
outputModel = db.getExerciseById(request.getParameter("exNo"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().append(outputModel.getExpOutput());
EDIT: Upon clicking, i think there is data but my text area is not displaying it.
Since you're making an Asynchronous call you can't return an immediate response using return data;, but instead you could pass the selector then assign the result to your output element when the success callback is called:
<script>
$('#verifyBtn').on("click", function() {
checkOutput("outputArea");
});
function checkOutput(output_selector){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true, output_selector);
}
function getOutput(dataStr, flag, output_selector) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
$(output_selector).html( data );
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
</script>
NOTE : The passed flag parameter isn't used.
Hope this helps.
This block here:
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
try adding a return to the getOutput line
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
return getOutput(dataString, true);
}
By value i guess you mean the result of the call. You can find that in the parameter of the success handler.
success: function (data) {
//This is your result from server.
console.log(data);
return data;
}
Take a look at your JS console to see the results.
I need to execute 3 ajax requests. I know that they happen to be asynchronous by default (And making them synchronous messes up the VM, so I don't want to go that way.) The way I do it is by calling a function three times passing variables.
result = '';
parse(var1);
parse(var2);
parse(var3);
view();
function parse(variable) {
//ajax request here
$.ajax({
type: 'POST',
url: 'script.php',
data: {variable: variable},
success: function (data) {
//result stored in a global variable
result += data;
}
});
}
function view() {
//do something with result
}
But right now, the view() is triggered right away when the result isn't done cooking. How do I set them up to happen one after the other? I read about callbacks but they are very confusing since I don't have 3 distinct functions but just one taking different variables.
You could store your variables in an array and use a function to make your ajax call:
var variables = [var1, var2, var3];
function callParse() {
if(variables.length) {
var currentVar = variables.shift();
parse(currentVar);
}
else {
view();
}
}
function parse(variable){
//ajax request here
$.ajax({
type:"POST",
url:'script.php',
data:{variable:variable},
success:function(data)
{
result+=data;
callParse();
}
});
}
function view(){
//do something with result
}
Try chained promises - from: https://css-tricks.com/multiple-simultaneous-ajax-requests-one-callback-jquery/
$.when(
// Get the HTML
$.get("/feature/", function(html) {
globalStore.html = html;
}),
// Get the CSS
$.get("/assets/feature.css", function(css) {
globalStore.css = css;
}),
// Get the JS
$.getScript("/assets/feature.js")
).then(function() {
// All is ready now, so...
// Add CSS to page
$("<style />").html(globalStore.css).appendTo("head");
// Add HTML to page
$("body").append(globalStore.html);
});
You could try doing it this way:
parseAndView([var1, var2, var3]);
function parseAndView(vars, index) {
index = index || 0; //initialize index if not passed
//execute the AJAX call only if there are more variables to parse
if (index < vars.length)
//ajax request here
$.ajax({
type: "POST",
url: 'script.php',
data: {variable: vars[index]},
success: function (data) {
// result stored in a global variable
result += data;
// recursive call to parse another variable
parseAndView(vars, index++);
}
});
else
view();
}
function view() {
//do something with result
}
I am trying to create a block of text that will update itself when the text changes from a Json string.
Basically I started with:
function streamSong(index) {
if (!isUndefined(myPlaylist[index].title))
return myPlaylist[index].title;
else return '';
}
then modified it to look like this:
function streamSong(index) {
var currentSongName = 'here';
if (!isUndefined(myPlaylist[index].title)) {
var intervalFunc = function(){
var jsonData = null;
$.ajax({
url: 'http://www.thesite.com/pullJson.php?stream=rapstation',
dataType: "json",
data: { get_param: 'employees' },
success: function (data) {
currentSongName = 'now here';
},
error: function (data) {
currentSongName = 'not working';
}
});
};
setInterval (intervalFunc, 60000);
setTimeout (intervalFunc, 1);
return currentSongName;
}
else return 'no title';
}
The first function fired off fine and returned my Stream Title.
The second function fires off, but I never am able to modify the value of currentSongName.
I am still a bit new to Javascript and ajax so excuse my ignorance, but I obviously want to ultimately set the value of currentSongName to the Json value I retrieve, but for now I would just like it to be able to change values on a timer.
Am I going about this all wrong?
The variable is modified just fine, but too late. The AJAX call is asynchronous, so the variable is used to return the value before the value is assigned to it.
You would use a callback to handle the result. With the original code it would look like this:
function streamSong(index, callback) {
if (!isUndefined(myPlaylist[index].title)) {
callback(myPlaylist[index].title);
} else {
callback('');
}
}
Usage:
streamSong(42, function(title) {
// do what you want with the title
});
For the AJAX call the callback would be used like this:
function streamSong(index, callback) {
var currentSongName = 'here';
if (!isUndefined(myPlaylist[index].title)) {
var intervalFunc = function(){
var jsonData = null;
$.ajax({
url: 'http://www.thesite.com/pullJson.php?stream=rapstation',
dataType: "json",
data: { get_param: 'employees' },
success: function (data) {
callback('now here');
},
error: function (data) {
callback('not working');
}
});
};
setInterval (intervalFunc, 60000);
setTimeout (intervalFunc, 1);
} else {
callback('no title');
}
}
New to jQuery and having simple yet confusing problem. ha2.
I am writing this normal javascript function with jQuery function reading xml file. How do I assigned value to the prodPrice variable declared on the top? the script keep returning 0 value, but if I alert the value within the jQuery function, I managed to get the value that I wanted.
Thank you guys.
function getPrice(valprodID)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
return false;
}
});
}
})
return prodPrice;
}
That's because $.ajax is performed asynchronously.
And it is a great chance for you to learn how to work with $.Deferred
function getPrice(valprodID)
{
var prodPrice=0;
return jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml"
}).pipe(function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
return jQuery(this).find('prodPrice').text();
}
});
});
}
Now you call your getPrice() function in this way:
getPrice(someid).done(function(prodPrice) {
// do what you need with prodPrice
});
Here is an example on jsfiddle: http://jsfiddle.net/zerkms/9MgsX/1/
you can do asynchronous as reported by #xdazz, as #zerkms indicated with Deferred, or anonymous functions:
function getPrice(valprodID, fn)
{
var prodPrice=0;
jQuery.ajax({
type: "GET",
url: "products.xml",
dataType : "xml",
success : function(xml)
{
jQuery(xml).find('prod').each(function(){
var prodID = jQuery(this).find('prodID').text();
if(prodID == valprodID)
{
prodPrice = jQuery(this).find('prodPrice').text();
fn(prodPrice);
}
});
}
})
}
getPrice(1, function(prodPrice) {
/* your code */
})
You need to set the async option to false, or you should do your work in the callback function.
I want to create a separate function to get specific data from Facebook graph JSON.
For example, I have the load() and called getNextFeed() function.
The getNextFeed works correctly. Except that returning value of aString is not successful.
When I pop alert(thisUrl). It said undefined.
Note: I am new to Javascript and Jquery. Please give me more information where I did wrong. Thank you.
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
var thisUrl = getNextFeed(url);
alert(thisUrl); // return undefined
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
return aString;
}
});
}
The problem is that $.ajax() is an ansynchronous function, means, when called, it returns in the same instance, but an ajax call is done in a separate thread. So your return vaule of $.ajax() is always undefined.
You have to use the ajax callback function to do whatever you need to do: Basically you already did it correctly, just that return aString does not return to your original caller function. So what you can do is to call a function within the callback (success()), or implement the logic directly within the success() function.
Example:
function load()
{
$(document).ready(function() {
var token = "AccessToken";
var url = "https://graph.facebook.com/me/home?access_token=" + token;
getNextFeed(url);
alert('Please wait, loading...');
});
function getNextFeed(aUrl)
{
$.ajax({
type: "POST",
url: aUrl,
dataType: "jsonp",
success: function(msg) {
alert(msg.paging.next); // return correctly
var aString = msg.paging.next;
alert(aString); // return correctly
do_something_with(aString);
}
});
}