I need to use the same if..else to deal with every AJAX data in my code.
$.ajax({
url: "api/aall.json",
dataType:'json',
type: 'GET',
data: "data",
cache: false,
ifModified: true,
success: function getData(data){
console.log(data);
for(var i=0;i<7;i++){
// if...else
}
});
There are several AJAX get differnt:
$.ajax({...});
$.ajax({...});
$.ajax({...});
$.ajax({...});
if...else code:
if(MainClass_Code=="PD" || MainClass_Code=="CD"){
newsKindRepalce = "aipl";//news
}else if(MainClass_Code=="PF" || MainClass_Code=="JF"){
newsKindRepalce = "aopl";//international
}else if(MainClass_Code=="CU"){
newsKindRepalce = "acul";//culture
}else{
newsKindRepalce = "acn";//artist
}
It's would be very heavy when I use if...else in my all AJAX to deal with data, how can I do to simplify this?
change your if else to this:
const code = { PD: "aipl", CD: "aipl", PF: "aopl", JF: "aopl", CU: "acul" };
newsKindRepalce = code.hasOwnProperty(MainClass_Code)
? code[MainClass_Code]
: "acn";
Related
I'm having a loop, inside the loop there is an AJAX call. For each loop AJAX returns a value. I want sequential loop one after another only when AJAX request is completed. I've done this using async:false but this method hangs my other code.
I want to do with $.Deferred()
This is my code:
function CheckAvailability(Display) {
var Status = "";
$.ajax({
type: "POST",
url: "myurl",
dataType: "json",
data: { "Display": Display },
async: false,
success: function (result) {
Status = result[0].Availability;
}
});
return Status;
}
$(DisplayData).each(function (index, Display) {
var Availability = CheckAvailability(Display) === 'Yes' ? '' : '<span style="margin-left:10px"><i class="fa fa-exclamation text-danger"></i></span>';
var Name = Display.Name + Availability;
console.debug(Name);
});
I want output like:
Display1 Yes
Display2 No
Display3 No
Display4 Yes
I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have an ajax call and I want to use result of this ajax on another page.
//This is main.js file
function myFun(){
var my_user = "Stas";
var itemsUrl = "myxmlwithusers";
var user_found = false;
$.ajax({
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
cache: false,
async: false,
dataType: "text",
success: function(data){
var jsonObject = JSON.parse(data);
results = jsonObject.d.results;
$(results).each(function(){
if($(this)[0].user == my_user){
user_found = true;
}
});
},
error:function () {
console.log("Error");
}
}
);
}
// This is execute.js file
myFun();
if (user_found == true){cool}
I need true or false for // user_found. Let say I will put in the file execute.js my function myFun() and in main.js my user is fetch with "$(this)[0].user" and I need to receive "true" in execute.js
Thanks!
The problem is that $.ajax call is asynchronous, a.k.a you check for value of user_found before it is set. try this approach
function myFun(callback){
var my_user = "Stas";
var itemsUrl = "myxmlwithusers";
var user_found = false;
$.ajax({
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
cache: false,
async: false,
dataType: "text",
success: function(data){
var jsonObject = JSON.parse(data);
results = jsonObject.d.results;
$(results).each(function(){
if($(this)[0].user == my_user){
user_found = true;
}
});
if(typeof callback === "function"){
callback(user_found);
}
},
error:function () {
console.log("Error");
}
}
);
}
Then you can use it like
myFun(function(result){
if (result == true){
//cool
}
});
1st: simply in html before including any js files
<head>
<script>
var user_found = true; // or false if you like
</script>
// include main.js and execute.js
</head>
now you can call user_found anywhere in js files without var .. even it change in any js files functions it will change in others
Simple Example
2nd: If you include main.js before execute.js you can use it like
var user_found = false;
function myFun(){
var my_user = "Stas";
var itemsUrl = "myxmlwithusers";
$.ajax({
url: itemsUrl,
....................
Simple Example
Consider using HTML5 Local Storage. Stored values should be accessible by every page served on your domain.
// Store
localStorage.setItem("user_found", "true");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("user_found");
Allow me to elaborate.
I have this Ajax script which is fetching for one thing. The refresh_on.
What does it do? It either returns 0 OR 1.
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: {task: "reload"},
success: function(data) {
$.each(data, function(i, attr){
if (attr.refresh_on == 0) {
//this doesn't work
/*Write/return this in JavaScript:*/ line[1]="Offline.";
} else {
//this doesn't work
/*Write/return this in JavaScript:*/ line[1]="Online.";
};
})
}
});
}
If the ajax returns with refresh_on == 0 OR refresh_on == 1 - I want it to print its respective array item. It must be an array item.
</head>
<body>
<script type="text/javascript">
var line=new Array()
startRefresh();
//output either "line[1]=\"Offline.\""; or "line[1]=\"Online.\"";
</script>
</body>
This is the PHP file:
if (isset($_POST['task']) && $_POST['task'] == "reload") {
$stmt = $connection->prepare("SELECT refresh_on FROM refresh");
$stmt->execute();
$result = $stmt->get_result();
$encode = Array();
while ($row = $result->fetch_assoc()) {
$encode[] = $row;
}
echo json_encode($encode);
}
If it matters - this is the JSON response:
[{"refresh_on":1}]
Is there a way to insert/output/print the array item using the function?
Any help would be appreciated.
So there's a couple things that might be going on here, but to begin, you're wrapping your variable in a quote, so all that is happening is a string is being made and immediately being dropped to the floor. Let's start off by doing something like the following:
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: {task: "reload"},
success: function(data) {
$.each(data, function(i, attr){
if (attr.refresh_on == 0) {
//this doesn't work
line[1] = "Offline.";
} else {
//this doesn't work
line[1]= "Online.";
};
})
}
});
}
Now, if I recall correctly, the ajax function is going to be calling your success callback, which is going to take over your local scope. I don't believe line is going to be accessible to that callback, so we should/could actually move that callback to its own function within a closure:
<script type="text/javascript">
(function() {
var line = [];
startRefresh();
function startRefresh() {
setTimeout(startRefresh, 60000);
$.ajax({
url: 'refresh.php',
type: 'POST',
dataType: 'JSON',
data: { task: "reload" },
success: refreshResponse
});
}
function refreshResponse(data) {
$.each(data, function(i, attr) {
if (attr.refresh_on == 0) {
line[1] = "Offline.";
} else {
line[1] = "Online.";
}
});
}
})();
</script>
We've wrapped that in a self executing function to give us some nice encapsulation to work with, and because line is in a function which refreshResponse is found, that variable should be accessible to it.
But we're not done yet!
For one, we could easily make that variable assignment a little easier, like so:
line[1] = (attr.refresh_on == 0) ? "Offline." : "Online.";
...and we're also going to want to triple up on that equality statement, just to avoid variable coercion:
line[1] = (attr.refresh_on === 0) ? "Offline." : "Online.";
Give that a shot and let's see where we're at.
Not sure what you are expecting "line[1]=\"Offline.\""; to do, but it's not going to do anything. Perhaps you mean: line[1]= "Offline";? Try putting this line of code there instead to test that it's working: console.log('Offline');
If the line is getting executed and you see the output in your console, you would just have to target some HTML element that you want to put the "Offline" string into, for instance:
<div id="status"></div>
<script>
....
var status = document.getElementById("status");
if (attr.refresh_on == 0) {
status.textContent = "Offline";
} else {
status.textContent = "Online";
};
....
</script>