jquery if data not empty add class issue - javascript

not sure why this isn't working still fairly new with js. I am trying to check if there is any data and if there is then it should add a hidden class or should remove it if it has no data.
$(function() {
$('#search').keyup(function() {
var followerList=$("#followerlist");
if($('#search').val() !== ""){
followerList.addClass('hidden');
}else{
followerList.removeClass('hidden');
};
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text': $('#search').val(),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}

Your searchSuccess function has to be like this:
function searchSuccess(data, textStatus, jqXHR)
{
var followerList=$(".followerlist");
$('#search-results').html(data);
if(data !== "")
{
followerList.addClass("hidden");
}
else
{
followerList.removeClass("hidden");
}
}

Related

Javascript use results from one AJAX function to make another

I have a javascript function which uses AJAX to grab the coordinates from a country name PHP file.
$("#innerSelect").on("change", () => { //Handles changing the country select.
addCountryBorder($("#innerSelect").val()); /* Calls function that adds country border to map */
$.ajax({
url: "libs/php/getCoordsFromCountryName.php",
type: "GET",
dataType: "json",
data: {
countryName: $("#innerSelect").val(),
},
success: function(result) {
if (result.status.name == "ok") {
map.panTo(new L.LatLng(result["data"][0]["geometry"]["lat"] , result["data"][0]["geometry"]["lng"]))
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
These seem coordinates (lat and long) can be used to grab the country code from a different API, how can I make another AJAX function something like below to take the lat/long from above and use it to navigate to the right country code?
function getCountryCode(countryName) {
$.ajax({
url: "assets/php/countryCode.php",
type: "GET",
dataType: "json",
data: {
lat and long
},
success: function(result) {
GET THE COUNTRY CODE
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
}
I have tried this to no avail
let latitude;
let longitude;
$("#innerSelect").on("change", () => { //Handles changing the country select.
addCountryBorder($("#innerSelect").val()); /* Calls function that adds country border to map */
$.ajax({
url: "libs/php/getCoordsFromCountryName.php",
type: "GET",
dataType: "json",
data: {
countryName: $("#innerSelect").val(),
},
success: function(result) {
if (result.status.name == "ok") {
latitude = (result["data"][0]["geometry"]["lat"])
longitude = (result["data"][0]["geometry"]["lng"])
map.panTo(new L.LatLng(result["data"][0]["geometry"]["lat"] , result["data"][0]["geometry"]["lng"]))
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
});
let countryCode;
function getCountryCode(countryName) {
$.ajax({
url: "assets/php/countryCode.php",
type: "GET",
dataType: "json",
data: {
lat: latitude,
lng: longitude
},
success: function(result) {
console.log(JSON.stringify(result));
if (result.status.name == "ok") {
$('#countryCode').html(result['data'][0]['countryCode']);
countryCode = (result['data'][0]['countryCode']);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// your error code
}
});
}
function countryInfo() {
$.ajax({
url: "assets/php/countryInfo.php",
type: 'POST',
dataType: 'json',
data: {
country: countryCode,
},
success: function(result) {
if (result.status.name == "ok") {
coords.push({currencyCode: result.data[0].currencyCode});
let formattedPopulation = result['data'][0]['population'].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
let formattedArea = Math.round(result['data'][0]['areaInSqKm']).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
$('#continent').html(result['data'][0]['continentName']);
$('#capital').html(result['data'][0]['capital']);
$('#countryName').html(result['data'][0]['countryName']);
$('#population').html(formattedPopulation);
$('#currencyCode').html(result['data'][0]['currencyCode']);
$('#area').html(formattedArea);
currencyConverter();
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
console.log(textStatus)
console.log(errorThrown)
}
});
}
Try putting your first ajax request on a function like this
function fetchApi() {
return jQuery.ajax({
url: 'yoururl',
method: 'GET',
dataType: 'json',
success: function (result) {
//return the value from the request
return result;
}
});
}
Now you can call your second request just after the first one and pass the lat and long values to it
fetchApi().then((data) => //do something with the data)

it showing "undefined" in tree view using ASP.NET MVC with javascript

While fetching data from the oracle database it showing "undefined" in Tree View structure using ASP.NET MVC and Gijgo tree view JQuery plug-in, The Tree View control can display a hierarchical (or nested, or recursive) collection of data in a tree of expandable nodes.. How to solve this?.Please, anyone helps me.
I am trying this link
https://www.codeproject.com/Articles/1185174/How-to-create-Dynamic-draggable-and-droppable-Tree
#section Scripts {
#Scripts.Render("~/bundles/Scripts/jqueryval") <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="#Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"></script>
<script src="~/Scripts/Gijgo/gijgo.js"></script>
<link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//'Hierarchy/GetHierarchy'
$(document).ready(function () {
var Usertree = "";
var tree = "";
$.ajax({
type: 'get',
dataType: 'json',
cache: false,
url: '/Hierarchy/GetHierarchy',
success: function (records, textStatus, jqXHR) {
tree = $('#tree').tree({
primaryKey: 'Id',
dataSource: records,
dragAndDrop: true,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
tree.on('nodeDrop', function (e, ID, PID) {
currentNode = ID ? tree.getDataById(Id) : {};
console.log("current Node = " + currentNode);
parentNode = PID ? tree.getDataById(PID) : {};
console.log("parent Node = " + parentNode);
if (currentNode.PID === null && parentNode.PID === null) {
alert("Parent node is not droppable..!!");
return false;
}
// console.log(parent.HierarchyLevel);
var params = { id: ID, parentId: PID };
$.ajax({
type: "POST",
url: "/Hierarchy/ChangeNodePosition",
data: params,
dataType: "json",
success: function (data) {
$.ajax({
type: "Get",
url: "/Hierarchy/GetHierarchy",
dataType: "json",
success: function (records) {
Usertree.destroy();
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
}
});
}
});
});
$('#btnGetValue').click(function (e) {
var result = Usertree.getCheckedNodes();
if (result == "") { alert("Please Select Node..!!") }
else {
alert("Selected Node id is= " + result.join());
}
});
//delete node
$('#btnDeleteNode').click(function (e) {
e.preventDefault();
var result = tree.getCheckedNodes();
if (result != "") {
$.ajax({
type: "POST",
url: "/Hierarchy/DeleteNode",
data: { values: result.toString() },
dataType: "json",
success: function (data) {
alert("Deleted successfully ");
window.location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
});
}
else {
alert("Please select Node to delete..!!");
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
// show model popup to add new node in Tree
$('#btnpopoverAddNode').click(function (e) {
e.preventDefault();
$("#modalAddNode").modal("show");
});
//Save data from PopUp
$(document).on("click", "#savenode", function (event) {
event.preventDefault();
$.validator.unobtrusive.parse($('#formaddNode'));
$('#formaddNode').validate();
if ($('#formaddNode').valid()) {
var formdata = $('#formaddNode').serialize();
// alert(formdata);
$.ajax({
type: "POST",
url: "/Hierarchy/AddNewNode",
dataType: "json",
data: formdata,
success: function (response) {
// $("#modalAddNode").modal("hide");
window.location.reload();
},
error: function (response) {
alert('Exception found');
// $("#modalAddNode").modal("hide");
window.location.reload();
},
complete: function () {
// $('.ajax-loader').css("visibility", "hidden");
}
});
}
});
//Close PopUp
$(document).on("click", "#closePopup", function (e) {
e.preventDefault();
$("#modalAddNode").modal("hide");
});
$('.rbtnnodetype').click(function (e) {
if ($(this).val() == "Pn") {
$('.petenddiv').attr("class", "petenddiv hidden");
$("#ParentName").val("");
}
else {
$('.petenddiv').attr("class", "petenddiv");
}
});
});
</script>
}
Just make sure you name the property “text”, including lowercases, as the library binds this field to the label. Not having a property with this name renders it undefined.

Ajax call not working for every controller

I am using mvc 4 ,I need to call controller actions using ajax.So I created a new scripts.js file at Scripts folder.In my project there are lot of controllers and I wrote ajax functions for each of them in the same js file.But except the default controller other controllers are not initiated by the ajax code. Scripts.js file contains:
$(document).ready(function () {
//END COUNTRY ................................................................
$("#savecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/SaveCountry',
data: {name: $('#country').val() },
dataType: 'json', encode: true,
async: false,
cache: false,
//contentType: 'application/json; charset=utf-8',
success: function (data, status, jqXHR) {
// alert("success");
console.log(jqXHR);
console.log(status);
console.log(data);
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
//console.log(jqXHR);
//console.log(textStatus);
//console.log(errorThrown);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$("#updatecountry").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Country/Update',
data: { id:$('#id').val(), name:$('#country').val() },
dataType: 'json', encode : true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
$('#cancel').click(function () {
$('input:text').val('');
});
//$('.deleteRow').click(function () {
// alert('ewewrwr');
// $.ajax({
// type: "POST",
// data: { id: $('#id').val() },
// url: "/Country/DeleteCountry",
// dataType: 'json', encode: true,
// async: false,
// cache: false,
// success: function (data, status, jqXHR) {
// alert("success");
// //$.each(data, function (index, customer) {
// // alert(customer.Name + " " + customer.UserName);
// //});
// },
// error: function (jqXHR, textStatus, errorThrown) {
// console.log(jqXHR);
// if (typeof (console) != 'undefined') {
// alert("oooppss");
// }
// else { alert("something went wrong"); }
// }
// });
//});
$("#updateoffer").click(function () {
//var car = { id: 4, name: "India" }
$.ajax({
type: "POST",
url: '/Offer/Update',
// contentType: "application/json; charset=utf-8",
data: { id: $('#id').val(), name: $('#offer').val(), description: $('#description') },
dataType: 'json', encode: true,
async: false,
cache: false,
success: function (data, status, jqXHR) {
alert("success");
//$.each(data, function (index, customer) {
// alert(customer.Name + " " + customer.UserName);
//});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
if (typeof (console) != 'undefined') {
alert("oooppss");
}
else { alert("something went wrong"); }
}
});
});
});
Here Country is the default controller and ajax call working well.But call to Offer controller Update ajax not working .Page not responding error will result.
You should take project name to baseUrl for call ajax function.
$(document).ready(function(){
var baseurl = "";//your project name
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry', // baserurl+"/controller name/action"
.....
}
The accepted answer has a serious flaw in commercial deployments, so offering alternatives.
Yes, you need the base address of the website, but you do not want to hard-wire it into the code.
Option 1
You can inject a global javascript variable into your master page as a string constant.
e.g. put this at the top of your master page
<script>
window.baseurl = "#Url.Content("~/")";
</script>
then just use window.baseurl prepended to your URLs
e.g
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: window.baseurl+'/Country/SaveCountry',
Option 2
You can inject a data- attribute into the DOM in your master page. e.g. on the body tag
then extract it using jQuery:
e.g.
var baseurl = $('body').data('baseurl');
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: baseurl+'/Country/SaveCountry',
Option 3 (I do not advise this one)
Inject the string literal into your Javascript
$("#savecountry").click(function () {
$.ajax({
type: "POST",
url: "#Url.Action("SaveCountry", "Country")",
This is bad for maintenance and debugging as the code must be in a Razor view in order to work.
We used to use option 2 a lot, but now tend to use option 1.

Can I call ajax function inside another ajax function? [duplicate]

Is it possible to make an ajax request inside another ajax request?
because I need some data from first ajax request to make the next ajax request.
First I'm using Google Maps API to get LAT & LNG, after that I use that LAT & LNG to request Instagram API (search based location).
Once again, is this possible, and if so how?
$('input#search').click(function(e) {
e.preventDefault();
var source = $('select[name=state] option:selected').text()+' '+$('select[name=city] option:selected').text()+' '+$('select[name=area] option:selected').text();
var source = source.replace(/ /g, '+');
if(working == false) {
working = true;
$(this).replaceWith('<span id="big_loading"></span>');
$.ajax({
type:'POST',
url:'/killtime_local/ajax/location/maps.json',
dataType:'json',
cache: false,
data:'via=ajax&address='+source,
success:function(results) {
// this is where i get the latlng
}
});
} else {
alert('please, be patient!');
}
});
Here is an example:
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page=' + btn_page,
success: function (data) {
var a = data; // This line shows error.
$.ajax({
type: "post",
url: "example.php",
data: 'page=' + a,
success: function (data) {
}
});
}
});
Call second ajax from 'complete'
Here is the example
var dt='';
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page='+btn_page,
success: function(data){
dt=data;
/*Do something*/
},
complete:function(){
$.ajax({
var a=dt; // This line shows error.
type: "post",
url: "example.php",
data: 'page='+a,
success: function(data){
/*do some thing in second function*/
},
});
}
});
This is just an example. You may like to customize it as per your requirement.
$.ajax({
url: 'ajax/test1.html',
success: function(data1) {
alert('Request 1 was performed.');
$.ajax({
type: 'POST',
url: url,
data: data1, //pass data1 to second request
success: successHandler, // handler if second request succeeds
dataType: dataType
});
}
});
For more details : see this
$.ajax({
url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data) {
if (data.web == 0) {
if (confirm('Data product upToWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 1},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
else {
if (confirm('Data product DownFromWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 0},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});

Controller can give either json or html

The question is that the controller can give json or html piece. How to know what is it?
$(document).on("submit", "form.client-form", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
if (result is json) {
...
} else if (result is html) {
$("#result").html(result);
}
}
});
});
Another solution...found here: jquery how to check response type for ajax call
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(result, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//html here
$("#result").html(result);
}
if (ct.indexOf('json') > -1) {
//json here
}
}
});
});
How about using converters? Take a look at Using Converters on jquery ajax api: http://api.jquery.com/jQuery.ajax/
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
try {
var response = $.parseJSON(result);
}
catch (ex){
//something else
$("#result").html(result);
}
}
});
});

Categories

Resources