building html that use jquery to get data from web API.
In the beginning of my script I did a function that checks the value of dropdown (what is selected) and according to the selected it's fill the global variable.
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
}
after defining the function I calling it immediately to check it and fill the variable.
finally by Clicking on search it should check what selected from dropdown and according to that fill again the variable and start GET function with the modified URL
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Tried to debug it many ways but couldn't find why it's assigning that value.
Please assist as it should be so simple but I must missed something.
Here is the part of the code from the begining:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
Problem: After I start the debug the $selcom always get the value of '192.168.5.37' doesn't matter what I do.
Don't:
if ($("#dropdomain").val('Europa')) {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val("Canada")) {
$seldom = '172.168.0.1';
}
Do:
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === "Canada") {
$seldom = '172.168.0.1';
}
See documentation of jQuery.val():
.val(value)
Description: Set the value of each element in the set of matched
elements.
value argument
Type: String or Number or Array
A string of text, a number, or an array of strings corresponding to the value of each matched element to
set as selected/checked.
So, calling $("#dropdomain").val('some value') writes a value to the $("#dropdomain") element. To read its value, call $("#dropdomain").val().
Try the code below:
var $seldom;
$(document).ready(function () {
function chkdom() {
if ($("#dropdomain").val() === 'Europa') {
$seldom = '192.168.5.37';
}
else if ($("#dropdomain").val() === 'Canada') {
$seldom = '172.16.0.1';
}
}
chkdom();
alert($seldom);
alert($("#dropdomain").val());
$('#search').click(function () {
chkdom();
$.ajax({
url: "http://" + $seldom + "/api/find/" + $("input#user").val(),
type: "GET",
dataType: 'Jsonp',
success: function (result) {....}
This condition $("#dropdomain").val('Europa') is always writing and is being evaluated as true.
So, you need to compare the values:
var drop = $("#dropdomain").val();
if (drop === 'Europa') {
$seldom = '192.168.5.37';
} else if (drop === "Canada") {
$seldom = '172.16.0.1';
}
Related
I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}
While i was searching at stackoverflow, i found the code below :
$(document).ready(function () {
$("#show").click(function () {
getYoutube($("#Search").val());
});
});
function getYoutube(title) {
$.ajax({
type: "GET",
url: yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + title + '&format=5&max-results=1&v=2&alt=jsonc',
dataType: "jsonp",
success: function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_id = data.id;
var video_title = data.title;
var video_viewCount = data.viewCount;
$("#result").html(video_id);
});
} else {
$("#result").html('false');
}
}
});
}
How can i edit the code to keep only the function?
I want to be able to use it like that : getYoutube(my_keywords);
Also, how can i save the function output to variable? something like :
var_name = getYoutube(my_keywords);
would be ok?
Thnx! ;)
yes, you can use it as without $(document).ready. No, function does not return anything
To "return" value from Ajax:
$.ajax({
...
success: function(dataFromServer) {
processServerOutput(dataFromServer);
}
});
function processServerOutput(someString) {
alert(someString);
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have this problem with AJAX. I run the code and the ajaxString is undefined when the code is printed even though the Ajax code is pretty much called before the return statement. When I try to retrieve AJAX after the HTML generation and printing, the AJAX is defined so it makes me think that the return is called before AJAX gets the chance to finish. Any way around this? Here is my current code:
var ajaxHTML;
function runCode(str) {
if (str == 'SubmitB' || str == 'SubmitC' || str == 'SubmitD') {
generateHTML(str);
}
else {
$('#Holder1').html("");
$('#Holder2').html("");
$("#container_demo").fadeOut(500);
setTimeout(function(){$("#menu_container").html(generateHTML(str))},500);
$("#container_demo").fadeIn(500);
}
}
function generateHTML(source){
if (source =='d') {
return makeSchoolComboBox() + "Please Select a Level: <select id='selectedLevel'><option value='level1'>l1</option><option value='level2'>l2</option><option value='level3'>l3</option><option value='level4'>l4</option></select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button><button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>";
}
function makeSchoolComboBox() {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function (data) {
ajaxHTML = data;
}
});
return ajaxHTML;
}
Since AJAX is asynchronous, you can't call it and then return straight after as the call is still taking place. You need to populate the menu container in the success callback, like this...
function runCode(str) {
if (str == 'SubmitB' || str == 'SubmitC' || str == 'SubmitD') {
generateHTML(str);
}
else {
$('#Holder1').html("");
$('#Holder2').html("");
$("#container_demo").fadeOut(500);
makeSchoolComboBox();
}
}
function makeSchoolComboBox() {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function (data) {
$("#menu_container").html(data + "Please Select a Level: " +
"<select id='selectedLevel'>" +
"<option value='level1'>l1</option>" +
"<option value='level2'>l2</option>" +
"<option value='level3'>l3</option>" +
"<option value='level4'>l4</option>" +
"</select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button>" +
"<button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>").fadeIn(500);
}
});
}
ajax query is asynchronous
function makeSchoolComboBox(next) {
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: next
});
}
and run it as
makeSchoolComboBox(function(ajaxHTML){
//manipulations with here
})
Or you can pass async: false in your $.ajax, but all stops while ajax request processed in this case
If you need to keep the structure you're using (I'd make generateHTML and makeSchoolComboBox into a single function to keep it simple) then you can use promises.
Your code would then become:
function generateHTML(source){
if (source =='d') {
makeSchoolComboBox().then(function(data) {
return data + "Please Select a Level: <select id='selectedLevel'><option value='level1'>l1</option><option value='level2'>l2</option><option value='level3'>l3</option><option value='level4'>l4</option></select><br> <button id = 'r' onClick='runCode(this.id)'>Go back</button><button id = 'SubmitD' onClick='runCode(this.id)'>Submit</button>";
});
}
}
function makeSchoolComboBox() {
var d = new $.Deferred();
$.ajax({
type: 'GET',
url: 'phpQueries.php?q=fill_school_list',
success: function(data) {
return d.resolve(data);
}
});
}
I don't know why the selector jquery doesn't accept a variable.
function myfunction()
{
$.ajax({
url: "/file.php", dataType: "json", type: "GET",
success: function(data)
{
var data = data.split("-");
data.forEach(function(entry)
{
if (entry != "")
{
$("#check_status_" + entry).html('text');
}
});
}
});
}
variable entry is not empty, the problem is when I put it into the selector.
Thanks.
[update]
{
var test = "aaa-bbb-ccc";
var data = test.split("-");
data.forEach(function(entry) {
if (entry != ""){
$("#check_status_" + entry).html('!NEW!');
}
});
}
nothing the same
It seems to work fine if you are achieving something like this
data.forEach(function(entry) {
if (entry) {
$("#check_status_" + entry).html('text');
}
});
I got an if-else script:
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
if (isFav(fid)) {
alert("Do you want to remove from favorite?");
}
else {
alert("Add to favorite?");
}
});
calling the isFav script function:
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { return result; }
});
}
which in turn calling my controller action:
public Boolean IsFav(int id)
{
var food = dbEntities.FOODs.Single(f => f.FoodID == id);
if (food.FavFlag == 1)
{
return true;
}
else
{
return false;
}
}
Everything seems works fine, I get a true from firebug, BUT i get the alert message from the else statement. The if statement just never being entered.
I cant get what is wrong here. Any idea?? Please help..
The ajax request in isFav is async and the isFav method will return before it is completed.
This is probably how I would solve it:
function isFav(fid, callback) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { callback(result); }
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid,function(result){
if(result && result.toLowerCase() == "true"){
alert("Do you want to remove from favorite?");
} else {
alert("Add to favorite?");
}
});
});
You want to make sure that the code in the if-block is run after the ajax request is done. In this snippet this is solved by the callback method that is called when the ajax success function is executed.
You're not really returning true from within isFav function. Also ajax is asynchornous, so your code (if statement) actually continues to execute until ajax finishes, so at the moment of execution the result of isFav is undefined. So that's why else is being executed.
You're gonna need some remodeling.
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) {
if(result == 'favorite') alert("Do you want to remove from favorite?");
else alert("Add to favorite?");
}
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid);
});