Appending service name in jQuery.ajax url parameter - javascript

If I was to set up future ajax calls using:
$.ajaxSetup({
url: '/WebServices/AjaxService.asmx',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
Is there any way I could append the service name in future calls? Like this:
$.ajax({
url: '+=/ServiceName'
});
Or is a global variable my best option?

Not the way you are suggesting (although $.ajaxSetup.url could be used that way), but you may want to create an object that has the path fixed and you can set the service method name:
function Service(){
var path = 'http://myserver';
this.getServiceUrl = function(serviceName) { return path + '/' + serviceName; };
}
...
var s = new Service();
$.ajax({
url: s.getServiceUrl('myServiceName'),
...
});
Or something like that. I hope that helps.

$.ajaxSettings will allow you to access the ajax settings. You could then go:
$.ajax({
url: $.ajaxSettings + "/ServiceName"
...
});

Related

Run if/else script with only part of a URL

I am trying to edit my Javascript to pull different data via an AJAX call based upon only part of a URL. Currently, my if/else script looks like this:
if (window.location.href=="london") {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data-london.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
} else {
$.ajax({
url: '../financial-reports/outwork-vs-expenses-data.php',
dataType: 'json'
}).done(function(data) {
data.forEach(function(item) {
dates.push(item.date);
expenses.push(item.expense);
outworks.push(item.outwork);
expensesOutworks.push(item.expensesOutwork);
budgetedOutworks.push(item.budgetedOutwork);
myExpensesChart.update();
});
});
}
This doesn't work as currently written since if window.location.href=="london") is only part of the URL, not the full URL. Is there a way to edit this script to run only based off of the last bit of the page URL? For example: /london, /nw, etc.? Is there a better way to accomplish this task?
Instead of
if (window.location.href=="london") {
Use below code
var URL = window.location.href;
if(URL.indexOf("london") !== -1)
The .indexOf function will find out a substring is exist or not in a string. And in your case you wants "london" is exist or not in URL.
I assume you are asking, when the url something like 'https://example.com/london' , so you just want to include or get the value of london. below code will help to provide always last bit of value of the url.
window.location.pathname.splitOnLast('/')[1]
it will give you '/london'. or you can just check the existence of theondon in the url.
Firstly it is not necessary to use if else like above
You can use like below
var dataurl = document.URL
$.ajax({
url: 'somepage.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});
in somepage.php file you can process the data however you want based on the dataurl
And also in javascript you can do like below
var urlTopost="other.php";
if(document.url.indexOf("london")!==-1)
{
urlTopost="london.php";
}
$.ajax({
url: urlTopost,
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: dataurl
});

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

Html.Action from Javascript include js var as parameter

I am having trouble on calling a methode. I can do it with below codes but how to put in js var with my call?
$.ajax({
url: '#Url.Action("surfacepost", "surface", new { text = "ThisSchouldBeAJaVar" })',
method: 'GET',
success: function (data) {
}
});
In fact this mthode is getting a partial as I am going to display. So if there is a better way of dynamic load a partial using js, please also let me know.
Thanks
The problem is that the '#Url.Action()' method is executed by .NET, before the page is send to the browser, it is not aware of any javascript on the page, and the execution of the method cannot be influenced by javascript that is run after the page has 'left the server'
What you could do is create a placeholder, and replace it in javascript:
var url = '#Url.Action("surfacepost", "surface", new { text = "placeholder" })'
url.replace('placeholder', ThisSchouldBeAJaVar);
$.ajax({
url: url,
method: 'GET',
success: function (data) {
}
});
Or you could just type the url and append the var:
$.ajax({
url: '/surface/surfacepost/?text=' + ThisSchouldBeAJaVar,
method: 'GET',
success: function (data) {
}
});

How to add post parameters to $.ajax and $.ajaxSubmit

I used the ajax method of jquery for my forms. but now I need to add a field to the function.
how can I have my forms fields and my new post parameter.
var frm = $(n);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
//contentType:frm.attr('enctype'),
data: frm.serialize(),
success: function (data) {
$(dataform).html(data);
$(des).html('');
$("button[type='submit']").attr('disabled',null);
}
});
the data parameter should be like this:
data: frm.serialize() + {'foo':'bar'}
thanks in advance.
.serialize() returns a string of parameters like you'd see in a querystring, so just add on + "&foo=bar"
try something like this
data: frm.serialize()+'&foo=bar',

Setting data-content and displaying popover

I'm trying to get data from a resource with jquery's ajax and then I try to use this data to populate a bootstrap popover, like this:
$('.myclass').popover({"trigger": "manual", "html":"true"});
$('.myclass').click(get_data_for_popover_and_display);
and the function for retrieving data is:
get_data_for_popover_and_display = function() {
var _data = $(this).attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}
What is happening is that the popover is NOT showing when I click, but if I hover the element later it will display the popover, but without the content (the data-content attribute). If I put an alert() inside the success callback it will display returned data.
Any idea why is happening this? Thanks!
In your success callback, this is no longer bound to the same value as in the rest of get_data_for_popover_and_display().
Don't worry! The this keyword is hairy; misinterpreting its value is a common mistake in JavaScript.
You can solve this by keeping a reference to this by assigning it to a variable:
get_data_for_popover_and_display = function() {
var el = $(this);
var _data = el.attr('alt');
$.ajax({
type: 'GET',
url: '/myresource',
data: _data,
dataType: 'html',
success: function(data) {
el.attr('data-content', data);
el.popover('show');
}
});
}
Alternatively you could write var that = this; and use $(that) everywhere. More solutions and background here.
In addition to the answer above, don't forget that according to $.ajax() documentation you can use the context parameter to achieve the same result without the extra variable declaration as such:
get_data_for_popover_and_display = function() {
$.ajax({
type: 'GET',
url: '/myresource',
data: $(this).attr('alt'),
dataType: 'html',
context: this,
success: function(data) {
$(this).attr('data-content', data);
$(this).popover('show');
}
});
}

Categories

Resources