How to check if a value exists in AJAX success response - javascript

I have an AJAX.
var id = "some_text";
$.ajax({
type : "GET",
dataType : "json",
url : "<?php echo site_url('con_atk/get_outlet'); ?>",
async : false,
success : function(outlet){
$.map(outlet, function (v) {
if(v.NamaOutlet == id){
window.location.href = "page_a.php";
}
else{
window.location.href = "page_b.php";
}
})
}
})
I'd like to check if the value of id is exist in the AJAX success call (JSON object type). If it exists, redirect to page A and if not redirect to page B. When I use alert on v.NamaOutlet the value is exist. But why am I not redirected to page_a.php?
edit
when I use alert(JSON.stringify(outlet));
[{"KodeOutlet_iBSM":"ACG","NamaOutlet":"Accounting"},{"KodeOutlet_iBSM":"BBG","NamaOutlet":"Business Banking"},{"KodeOutlet_iBSM":"CB I","NamaOutlet":"Corporate Banking I"},{"KodeOutlet_iBSM":"CB II","NamaOutlet":"Corporate Banking II"},{"KodeOutlet_iBSM":"CBT","NamaOutlet":"Corporate & Branch Transformation"},{"KodeOutlet_iBSM":"CCG","NamaOutlet":"Culture & Customer Care"},{"KodeOutlet_iBSM":"CHG","NamaOutlet":"Consumer Finance & Hajj"},{"KodeOutlet_iBSM":"CMG","NamaOutlet":"Commercial Banking"}

Setting window.location.href doesn't immediately terminate the current script - I'm not sure how reliable this is cross browser, but in my testing in Chrome if you set window.location.href more than once in the same script the browser navigates to the last value set before the JS function ends.
So in your case it would navigate to the result of testing the last item in your array, because your $.map() loop runs the if/else for every item in the array.
You could instead use your loop to set a flag to indicate whether the item was found anywhere in the array:
success : function(outlet){
var idFound = false;
$.each(outlet, function (v) {
if(v.NamaOutlet == id){
idFound = true;
}
});
window.location.href = idFound ? "page_a.php" : "page_b.php";
}
Note that I've used $.each(), because although $.map() would achieve the same result it doesn't really make sense because you're not really doing any mapping.
You can tidy this up and remove the need for a flag variable by using the array .some() method rather than $.each():
success : function(outlet){
if (outlet.some(function(v) { return v.NamaOutlet == id; })) {
window.location.href = "page_a.php";
else {
window.location.href = "page_b.php";
}
}

The only possible reason I could find here is that you might be using Internet Explorer and internet explorer does not really accept relative URLs as mentioned in one of the answers here
window.location.href not working on IE
Rest all seems good. Hope this helps.

if else condition is not suitable for your situation , let your id is Commercial Banking ,the last array value of your given json response .So mapping json will be check first index with id ,so if not equal it redirected to page_b .But you have id that exist in json response so that condition is not true for your condition . You wanna check id is exist in outlet so that map json array and if it found redirected page , if not found write the redirect other page in next execute line....
var id = "Commercial Banking"; // eg value
$.ajax({
type : "GET",
dataType : "json",
url : "<?php echo site_url('con_atk/get_outlet'); ?>",
async : false,
success : function(outlet){
$.map(outlet, function (v) {
if(v.NamaOutlet == id){
window.location.href = "page_a.php";
}
});
window.location.href = "page_b.php";
}
});

TRY IT:
var id = "Business Banking";
$.ajax({
type: "GET",
dataType: "json",
url: "<?php echo site_url('con_atk/get_outlet'); ?>",
async: false,
success: function (outlet) {
//[{"KodeOutlet_iBSM":"ACG","NamaOutlet":"Accounting"},{"KodeOutlet_iBSM":"BBG","NamaOutlet":"Business Banking"},{"KodeOutlet_iBSM":"CB I","NamaOutlet":"Corporate Banking I"},{"KodeOutlet_iBSM":"CB II","NamaOutlet":"Corporate Banking II"},{"KodeOutlet_iBSM":"CBT","NamaOutlet":"Corporate & Branch Transformation"},{"KodeOutlet_iBSM":"CCG","NamaOutlet":"Culture & Customer Care"},{"KodeOutlet_iBSM":"CHG","NamaOutlet":"Consumer Finance & Hajj"},{"KodeOutlet_iBSM":"CMG","NamaOutlet":"Commercial Banking"}]
var exist = false;
for (var i = 0; i < outlet.length; i++) {
if (outlet[i].NamaOutlet === id) {
exist = true;
break;
}
}
if (exist) {
window.location.href = "page_a.php";
} else {
window.location.href = "page_b.php";
}
}
});

$('#btn').click(function () {
$.ajax({
type: "GET",
url: '/Contrller/Action Name',
data: {},
contentType: "application/json;",
dataType: "json",
success: function (r) {
console.log(r);
if (r == true) {
$.ajax({
type: "GET",
url: '/Contrller/Action',
data: { },
contentType: "application/json;",
dataType: "json",
success: function (r) {
$("#btnclosem").trigger("click")
var select = $("#Div");
select.empty();
select.append($('<option/>', {value: 0,text: "" })); $.each(r.list, function (index, itemData) {
}
});
return false;
}
else {
alert("")
return false;
}
}
});

Related

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

Display js code in php method ajax

I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here

Ajax not working properly

Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.

If new data else stop insert over and over

To keep it simple, I'm just wanting to know how I'd go about and if else statement against my ajax to print new data out once if it finds it and not the same data over and over again. Amd how can I possibly store the last id as a variable to reuse it when searching for more new records?
Someone mentioned to me also I could save the new notification idea as a return so when the ajax restarts it uses this to find the next new set of results.
Has anybody got any ideas how to achieve these?
<script type="text/javascript">
setInterval(function(){
var time = new Date().getTime();
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
}
});
},20000);
</script>
Regarding to store the last id, you could use:
window.localStorage.setItem('key', 'value');
Then when you want to get it again you'll should use:
var lastId = window.localStorage.getItem ('key');
And regarding the duplicates issue, well, you should have a internal storage in order to handle the recieved data. May be an array can help as storage, also you can also store this array in local storage.
Once you handle this data storage, you could apply something like this to verify that your data has no duplicates:
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
UPDATE
var notification_id = window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler(response);
if(response.num){
window.localStorage.setItem('lastId', response.num);
}
});
},20000);

my javascript function dont display alert message when get data from database through ajax in mvc3 [duplicate]

This question already has an answer here:
javascript alert messages is not show in mvc3
(1 answer)
Closed 9 years ago.
I am working on a form in mvc3 and use form validations in javascript and ajax.
in my form i add code and description in database and before form submission want to check that code already exist in database or not.i get the code in javascript through ajax function call andd eturn data in json form. when i get the data i display error message in alert to user that code already exist. but my alert is not display.what can i do for it.
below is my javascript save button click function
$('#sve').click(function () {
//e.preventDefault();
var iscodeexis = CodeExistChk();
if (iscodeexis) {//
//***********************CODE TO SAVE DATA IN DATABASE***********************************
var person = { AcCode: $('#AcCode').val(), Descrip: $('#Descrip').val(), AddOn: dd };
$.ajax({
url: '/Home/Save?action=Sve',
type: "POST",
data: JSON.stringify(person),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
// $('#message').html('Record saved successfully' + result).fadeIn();
alert("Record saved successfully");
},
error: function () {
// $('#message').html('Error Occurred').fadeIn();
alert("Record not saved successfully");
}
});
}//end of is valid function chk
else
return false;//if isvalid function return false then save button also return false
}); //end button clcik function
function CodeExistChk() {
subA = $('#AcCode').val().trim();
// ===========================check whether code exist already or not
if (subA.length === 10) {
str1 = "select AcCode from Account where AcCode='";
str2 = str1 + subA + "'";
GetCodeData(str2); //check whether code exist or not
strRes = strRes.substring(1, strRes.length - 1);
if (strRes.length > 0 && strRes != "") //if code exist then return false and not allow to enter code
{
alert('Code already exist cannot insert record');
return false;
}
}
//===============================
}
below is getcodedata function which use in above code to get code from database
//===============FUNCTION TO GET CODE FROM DATABASE TO USE IN JS FILE==========
function GetCodeData(Str) {
var p = {
StrSql: Str
};
$.ajax({
url: '/Home/GetGenVal',
type: 'POST',
// contentType: 'application/x-www-form-urlencoded',
dataType: "JSON",
contentType: "application/json; charset=utf-8",
processData: false,
crossDomain: false,
traditional: true,
data: JSON.stringify(p),
cache: false,
// success: callback
success: function (data) {
//$("#Descrip").val(data);
// ResSubCode = data;
strRes = null;
strRes = data;
return strRes;
}
});
}
waiting for early solution.
Whoa, I see a some mistakes in this code.
At first, never construct your sql queries on client side to execute them. What if I modify the query to be a "delete from"? Bye bye database!
I would simply edit your logic and use a [RemoteAttribute] MVC3/4 feature to call a controller action and return simply a true or false.
Check it here: Remoteattribute test usage
You cannot be wrong!
Vincenzo.

Categories