JS: + variable is this right? - javascript

$.ajax({
type: "POST",
url: "misc/AddFriend.php",
data: {
mode: 'ajax',
friend: c,
uID: $('#uID').val(),
fID: $('#fID').val(),
bID: $('#bID').val()
},
success: function (msg) {
alert('OK');
$('#friend' + fID).slideUp('slow');
}
});
IS this right? It wont slide up right now

Well, you can find out the ID by alerting the result of the concatenated expression.
Since you're feeding an anon object you don't have a reference. It's probably easiest if you just invoke .val() again:
$('#friend' + $('#FID').val() ).slideUp('slow');
Otherwise it's probably doing $('#friendundefined').slideUp.

try:
$.ajax({
type: "POST",
url: "misc/AddFriend.php",
data: {
mode: 'ajax',
friend: c,
uID: $('#uID').val(),
fID: $('#fID').val(),
bID: $('#bID').val()
},
success: function (msg) {
alert('OK');
$('#friend' + $('#fID').val()).slideUp('slow');
}
});

The syntax is correct, but whether those ids and the value of variable c make sense in the context of your application is a different story.
I notice that you are using fID in the function to execute when the call succeeds. fID and also c would need to be defined outside of the function - I mean that you can't use the value of property fID of the object assigned to data.
You could create that object outside of the ajax function however and use the property for both data and in the selector in the function to run when the call succeeds.

Related

How to set function as value to property that expects anonymous function

I'm using jquery API - jquery DataTables and I have this code snippet :
oSettings.aoDrawCallback.push({
"fn": function(){
},
"sName": "user"
});
Inside the body of the function I want to execute an Ajax request. when I write it drectly here like so:
"fn": function(){
$.ajax({
url: "url",
type: "POST",
async: false,
data: data,
success: function (data) {
console.log(data);
}
}),
There is more that is just an example to show the way everything's work fine. Then I create my own function :
function initCredits(id, inputVal, chkSelected) {
console.log(id);
$.ajax({
url: "URL",
type: "POST",
async: false,
data: data
success: function (data) {
}
})
}
and try to assing it do fn like so:
oSettings.aoDrawCallback.push({
"fn": initCredits(id, inputVal, chkSelected),
"sName": "user"
});
which gives me an error Uncaught TypeError: Cannot read property 'apply' of undefined. Now the text comes from the jquery DataTables API but there may be only two reasons I can think of that may break my code, since it's working befor taking it to outer function. First - I'm tryng to assing the function in a wrong way and second - as you may see I need three variables for my ajax request (id, inputVal, chkSelected) which are collected from the function where I'm doing this :
oSettings.aoDrawCallback.push({
"fn": initCredits(id, inputVal, chkSelected),
but the console log shows that the values are correct so I think this is less likely to be the problem, but still I consider it.
This:
"fn": initCredits(id, inputVal, chkSelected),
… calls the function and assigns the return value.
To assign the function, just do:
"fn": initCredits,

what is 'this' refers to in jquery's $.ajax success?

Sorry if I have made some mistakes of js terms in my question.
I'm trying to call a method in $.ajax success event which is within the same namespace, here is the demo:
"use strict";
var example = window.example || {};
example.Demo = {
doSomething: function(data) {
console.log(data);
},
main: function() {
$(document).ready(function() {
$.ajax({
url: 'url/to/some/place',
type: 'GET',
async: true,
dataType: "json",
success: function (data) {
this.doSomething(data);
}
});
});
},
};
example.Demo.main()
but it will fail with the following error:
Object # has no method 'doSomething',
seems this can works:
...
main: function() {
var that = this;
...
...
success: function (data) {
that.doSomething(data);
...
but I want to know whether there is any best practice for such case, or this is exactly the proper solution.
it refers the ajax settings by default, you can use the context to pass a custom object
context
This object will be made the context of all Ajax-related callbacks. By
default, the context is an object that represents the ajax settings
used in the call ($.ajaxSettings merged with the settings passed to
$.ajax).
example.Demo = {
doSomething: function (data) {
console.log(data);
},
main: function () {
//don't use dom ready handler here
$.ajax({
url: 'url/to/some/place',
type: 'GET',
//see the use of context
context: this,
async: true,
dataType: "json",
success: function (data) {
this.doSomething(data);
}
});
},
};
In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript. An onclick property, though, is owned by the HTML element it belongs to.
This "ownership" is the result of JavaScript's object oriented approach. See the Objects as associative arrays page for some more information.
Remove $(document).ready(function(){... inside the main , that will solve the problem

Prototype conversion ajax.updater

I have got a website that currenty uses prototype that im trying to get away from. These are the only 3 functions that use it.
I have been trying all morning to convert these but as my understanding of jquery isnt great im so struggling.
function GetCountries() {
new Ajax.Updater('country_list','site_countries.php', {parameters: '&onchange=1', onComplete: GetRegions});
}
function GetRegions() {
new Ajax.Updater('region_list','site_regions.php', {parameters: '&regionID='+$('regionID').value+'&countryID='+$('countryID').value+'&onchange=1', onComplete: GetTowns});
}
function GetTowns() {
new Ajax.Updater('town_list','site_towns.php', {parameters: '&regionID='+$('regionID').value+'&countryID='+$('countryID').value});
}
this is what i have come up with but it doesnt work:
function GetCountries() {
$.ajax({
type: "POST",
url: "site_countries.php",
data: '&onchange=1',
success: function( transport ){
$('#country_list').html(transport.responseText)
GetRegions
}
});
}
the page that is calls just returns a select dropdown list that replaces one within span called country_list on the page then it calles GetRegions which does the same.
Any assistance would be greatly received!
Steve
It is possible that the way you are providing the data field might be the issue here.
Try something like the following:
$.ajax({
type: "POST",
url: "site_countries.php",
data: {onchange: 1},
success: function( transport ){
$('#country_list').html(transport.responseText)
GetRegions
}
});
OR
function GetCountries() {
$("#country_list").load("site_countries.php", {onchange: 1}, function(){
// call your GetRegions() here
});
}

Send array with $.post

I'm trying to execute a $.post() function with an array variable that contains the data, but it seams that I'm doing something wrong because it won't go or it's not possible
var parameters = [menu_name, file_name, status, access, parent, classes];
console.log(parameters);
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json'); //Doesn't work
Firebug debug: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
So, which would be the propper way of doing it (if possible)?
i am using for such kind of issues always the $.ajax form like this:
$.ajax({
url: 'do.php',
data: {
myarray: yourarray
},
dataType: 'json',
traditional: true,
success: function(data) {
alert('Load was performed.');
}
});
the traditional is very important by transfering arrays as data.
Could be the variables in the parameters array
Having ran your code and supplemented the parameters for something like:
var parameters = ['foo','bar'];
It seems to work fine. I think the problem must be in the variables that you are passing as part of the array. i.e. are menu_name, file_name, status, access, parent and classes variables all as you expect them to be? e.g. console log them and see what they are coming out as. One might be an object which doesn't convert to json.
Use JSON.stringify()
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
$.post('do.php', {
OP: 'new_menu',
data: JSON.stringify(parameters)
},
function(result) {
console.log(result);
},
'json'
);
And then, in the server-side use json_decode() to convert to a php array.
http://php.net/manual/es/function.json-decode.php
Ok, so with the help of these StackOverflow fellows I managed to make it work just the way I wanted:
var parameters = {
'name': menu_name.val(),
'file': file_name.val(),
'status': status.val(),
'group': group.val(),
'parent': parent.val(),
'classes': classes.val()
};
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json');

jQuery autocomplete - pass targeted element attribute as an extra parameter?

I'm using the jQuery UI Autocomplete plug-in to make an ajax call and retrieve data. As well as passing the text of the input element I'm trying to pass in the 'id' attribute of the input element as an additional parameter. An extract of my code looks like this -
$("#autocomplete input").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(this).attr('id')
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label,
value: item.name
}
}))
}
})
},
});
The extra parameter is added to the 'data' property in the ajax call. It works okay if I specifically pass in a value e.g. '3' but I want to pass the 'id' attribute of the input element the function is being called on e.g. $(this).attr('id').
I assume it's a problem with 'this' not being evaluated in this part of the code, but I'm at a loss to see how else I can reference the element that is being targeted. Any help appreciated!
$('#autocomplete input').each(e, function() {
$(e).autocomplete('/path?param=' + $(e).attr('id'), function() { ... });
});
$('#autocomplete input').each(e, function() {
$(e).autocomplete({ source:function ... extra_param: $(e).attr('id') ... });
});
There maybe a more elegant way, but, I know autocomplete is somewhat sophisticated. I personally generate the request w/get parameters and use formatItem/formatResult instead of assigning the source to an ajax call.
I've got it working by breaking the autocomplete call out into an each. This allows me to capture the target element before I execute the autocomplete -
$("#autocomplete input").each(function() {
var that = this;
$(that).autocomplete({
source: function(request, response, this_element) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(that).attr('id')
}
....
"Source" is the ID of your input, you receive this item and save it in the variable, "that". When the input "Source" calls the autocomplete function, you can send the value of your id stored in the variable "that" for AJAX.
Example:
<script type="text/javascript">
$(document).ready(function() {
$("#Source").each(function() {
var that = this;
var url = "<?php echo constant('URL'); ?>";
$(that).autocomplete({
source: function(request, response){
$.ajax({
url: url+"models/queries/C_getOptions.php",
dataType:"json",
data:{
word:request.term,
id : $(that).attr('id')
},
success: function(data){
response(data);
}
});
},
minLength: 1,
select: function(event,ui){
//alert("Selecciono: "+ ui.item.label);
}
});
})
});

Categories

Resources