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.
Related
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)
var object={
"longDynamicLink": "https://[APP_NAME].page.link/?link=[LINK_HERE]",
"suffix":{
"option":"SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
dataType: "json",
data: object,
success: function(response, textStatus, jqXHR) {
alert(response.shortLink);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
The above code works if the "suffix" is deleted from the request. That makes an "UNGUESSABLE" url, but I want a short URL. As stated in the documentation at https://firebase.google.com/docs/dynamic-links/rest?authuser=0 I added the suffix option parameter, but it results with a 400 response. Any ideas why?
I haven't ever tried this but, ...
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
var params = {
"longDynamicLink": "https://example.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
"suffix": {
"option": "SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
data: jQuery.param(params) ,
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
This is a very weird problem but I will provide as much detail as possible. This Javascript function is in a separate .js file and referenced into various HTML pages in a Cordova application. When a push notification, with 2 parameters: id, type, is received into the device, a function called LaunchFromNotif is executed with these 2 parameters passed as arguments.
function LaunchFromNotif(id, type) {
try {
var ebyidurl = url + "ReturnEByID";
var nbyidurl = url + "ReturnNByID";
if (type != null) {
if (type == "n") {
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code here
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "e") {
$.ajax({
type: 'GET',
url: ebyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
//code
},
error: function (xhr, status, error) {
alert('Error: ' + error);
}
});
} else if (type == "a") {
combined(id);
}
}
} catch (exception) {
//window.location = "Warning2.html";
}
}
Combined(id) is another function with 2 Ajax calls. I used when and then, to make sure that the first ajax call completes before starting the second.
function combined(id) {
alert("combined");
$.when(
$.ajax({
type: 'GET',
url: nbyidurl,
data: { id: id },
dataType: 'json',
processdata: true,
success: function (data) {
alert("success of first ajax");
},
error: function (xhr, status, error) {
alert('Error 1: ' + error);
}
})
).then(function () {
$.ajax({
type: 'GET',
url: Verifytempurl,
data: { Username: localStorage.getItem('user') },
success: function (data) {
alert("success of second ajax");
},
error: function (xhr, status, error) {
alert('Error 2: ' + error);
}
});
});
The problem is that this is working well in only one HTML page. In 3 other pages in which I tried, it shows the "combined" alert and seems to never access the Ajax call. The logic seems to make sense, especially since it is in working order in one page. What could normally go wrong in something of the sort? I am left with few debugging possibilities, especially since this is a Cordova app and being tested on mobile devices.
Thanks in advance!
i am writing this code in my html page to hide one id in that page..alerts are also not working..method is not called
*<script>
alert("yo");
$(function checkUsertype(email_id)
{
alert("yup")
var usertype = $("#txtusertype").val();
$.ajax({
alert("hide")
url: 'rest/search/userType?email_id='+email_id,
type : "GET",
datatype : 'json',
cache : false,
success : function(data)
{
if(usertype=='webuser')
{
$("#themer").hide();
}
},
error : function(xhr, data, statusText,errorThrown)
{
}
});
})
alert("yo");
<script/>*
This is the problem.
$.ajax({
alert("hide")
You're trying to alert inside the ajax which is Syntax error. Try removing the alert inside ajax and it should work.
You can use alert in success, error callbacks as follow:
$(function checkUsertype(email_id) {
var usertype = $("#txtusertype").val();
$.ajax({
url: 'rest/search/userType?email_id=' + email_id,
type: "GET",
datatype: 'json',
cache: false,
success: function(data) {
alert('In Success'); // Use it here
console.log(data); // Log the response
if (usertype == 'webuser') {
$("#themer").hide();
}
},
error: function(xhr, data, statusText, errorThrown) {
alert('In Error'); // Use it here
console.log(errorThrown); // Log the error
}
});
});
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');
}
});