Send extra parameters with ajax chosen - javascript

I'm currently using the chosen JQuery plugin :
http://harvesthq.github.io/chosen/
with this complement (to add an Ajax request) :
https://github.com/meltingice/ajax-chosen
I would like to know if anyone has ever been able to send extra parameters to the ajax function.
For now it only sends the letters in the input, but I would like to send an extra id.
Here's what i'm doing:
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
I'm using the CakePHP Framework, here's my ajax function:
public function ajax_getBundleItems($term = null) {
$this->layout = false;
echo "<pre>";
var_dump($this->request->data);
var_dump($this->params['url']['term']);
echo "</pre>";
}
$this->params['url']['term'] gives me the letters in the input, and I would like $this->request->data to be an id.
Regards

you can pass it in url parameter like this:
var id = 123;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems?Id="+id,
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
or
var MyId = 23;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
data: { id:MyId },
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
you can pass here you Id from some variable

This is the actual answer, using the BeforeSend option:
$('select[name=element_id]', '#f-load-tc').ajaxChosen({
type: 'GET',
url: 'dynamic_url',
dataType: 'json',
afterTypeDelay: 300,
allow_single_deselect: true,
no_results_text: "No results matched",
beforeSend: function(xhr, opts) {
opts.url += '&category_id='+$category.val();
},
},
function (data) {
console.log(data);
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});

Related

Pushing data into in array Ajax

I have the following code where I make a loop to get data and send that data to a select .
I'm trying to save this data in an array and then display that data in a select
apparently the error comes from the line newOptions.push ({v.c_group: v.c_codigo_group}); since it asks me for a string , I think
here my code.
case <?php echo "'".$row["c_codigo_producto"]."'"; ?>:
$("#divhidden").first().show("fast", function() {});
var newOptions = {};
$.ajax({
data: {
'valor': valor
},
url: 'JSON/search_group.php',
type: 'POST',
dataType: 'json',
cache: false,
success: function(data) {
$.each(data, function(k, v) {
newOptions.push({ v.c_group : v.c_codigo_group });
});
},
async: false,
});
var $el = $('#grupo');
$el.html(' ');
$.each(newOptions, function(key, value) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
break;
<?php } ?>

How To pass Array value in Ajax Parameter from Client side To Server side

$('#SendEmail').click(function () {
var sel = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
alert(sel);
SetCompanyDetailsPopUp(sel);
})
I have multiple Check box in forloop and Iam getting the value at Onclick Function "SendEmail " and Also calling the Ajax method,The Ajax method "SetCompanyDetailsPopUp"is also working fine , but Parameter at server side is showing "null"
function SetCompanyDetailsPopUp(Email) {
debugger;
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data: { "id": Value },
success: function (result) {
var data = '';
alert(result);
//alert(result);
//alert('sucessfully generated');
}
});
}
after Debugging Ajax Function The value in the "Email" parameter is
Array(2)
0:"1"
1:"2"
length:2
proto
:
Array(0)
serverside method
public ActionResult GeneratePass(string id)
{
string[] arr = id.Split(','); ; // Initialize.
// Loop over strings.
foreach (string s in arr)
{
forgotPassword(s);
}
return Json(arr, JsonRequestBehavior.AllowGet);
}
the issue from my point of view is that you don't have
[FromBody] attribute in your controller method which is needed in Post methods
please check the following link:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
So the Code should look like this:
[HttpPost]
public ActionResult GeneratePass([FromBody] string id)
{
string[] arr = id.Split(','); ; // Initialize.
// Loop over strings.
foreach (string s in arr)
{
forgotPassword(s);
}
return Json(arr, JsonRequestBehavior.AllowGet);
}
You need to add the" traditional: true "
"ajax option to post back an array to the collection
function SetCompanyDetailsPopUp(Email) {
debugger;
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data: { "id": Email},
traditional: true, //Need to Add This
success: function (result) {
var data = '';
alert(result);
}
});
}
You do not give the attribute [httppost] to the method. But your ajax is post type. Here is the code sample that work as expected.
$(document).ready(function () {
function SetCompanyDetailsPopUp(Email) {
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data: { "id": Email },
success: function (result) {
var data = '';
alert(result);
}
});
}
$('#SendEmail').click(function () {
var sel = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
SetCompanyDetailsPopUp(sel);
});
});
And then ActionMethod
[HttpPost]
public ActionResult GeneratePass(string[] Id)
{
return View();
}
Change your ajax code with this
function SetCompanyDetailsPopUp(Email) {
var Value = Email.value;
debugger;
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data:'{ id:" '+ Value + ' "}', // May be i am right, Here is problem
success: function (result) {
var data = '';
alert(result);
//alert(result);
//alert('sucessfully generated');
}
});
}

how to use json data sent from backend

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
<li>"i want to insert variable here"<li>
},
error: function (data) {
console.log('Error:', data);
}
});
controller returns this
return Response::json($results);
and it gives this
{"results":[{"id":1,"name":"user","nick":"user1"}]}
how can i acces this in ajax part
You can use the data in ajax, sent from controller like this:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) { // <-------- here data is your variable having json received from backend
$.each(data.results, function(key, val) {
// Use your results array here...
$('li.data').each(function(i) {
$(this).find('span.id').text(val.id);
$(this).find('span.name').text(val.name);
$(this).find('span.nick').text(val.nick);
});
});
},
error: function (data) {
console.log('Error:', data);
}
});
You'll get json inside the data variable under the success section of your ajax call
Hope this helps!
In your success method you can access the data returned from the server as:
success: function(data) {
var users = data.results;
var temptale = '';
for (var i = users.length - 1; i >= 0; i--) {
temptale += "<li>Name - " + users[i]['name'] + "<li>"
}
// use temptale to insert in your DOM
},
var queryInfoById= function (id) {
var params = {
"id": id,
};
$.getJSON(prefix + "/queryById.do", params, function (data) {
$("#name").val(data.name);
$("#age").val(data.age);
});
};
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
var array = data.results;
for (var i=0; i < array.length; i++){
var obj = array[i];
var id = obj.id;
var name= obj.name;
var nick= obj.nick;
//Add here the data in your UL>LI elements.
}
},
error: function (data) {
console.log('Error:', data);
}
});

Assigning ajax call return value to an var with jquery

How can I assign a variable(var) to a json object which is returned from ajax call to the server? I need to access that object in the rest of the body.
For example, I've try this, I don't know it's correct.
var selectValues=$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: onSuccess
});
})
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
Note that, variable selectValues is used in the rest of the body.
I think you should do the whole code inside the $(document).ready(function() function and then make the ajax call synchronous. Because now the ajax call will be made when the document is ready, but the other code will be run directly without waiting for the document to be ready. Also the ajax call is asynchronous by default, so you should make it synchronous and assign the selectValues variable inside the success function of the ajax call. It will become something like this:
$(document).ready(function() {
var selectValues;
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(data) {
selectValues = data
}
});
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
})
you have to define the var outside the document ready scope like this:
var selectValues;
$(document).ready(function() {
// ajax
});
in the onSuccess function you can define the selectValues = data or something like that
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
success: function (result){
var selectValues=result;
}
});
try this.
Here is how we extract the returned information from our (xml) ajax calls:
$.ajax ({
type: "POST",
url: "something.cgi?someparam=whatever",
data: "key=val&key2=val2",
dataType: "xml", // you use json, but I don't think it matters
success: function (data) {
if ($("error", data).text() === "") {
// I could assign $("error", data).text() to a var just here
// This gets the "error" parameter out of the returned xml or
// json, here contained in "data"
}
[snip the rest]
Another way to do this is to add the rest of your code in the success callback lik this:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://10.0.2.2/mobileajax/callajax.php",
data: ({name: theName}),
cache: false,
dataType: "text",
async: false,
success: function(selectValues) {
var $vendor = $('select.mobile-vendor');
var $model = $('select.model');
$vendor.change(
function() {
$model.empty().append(function() {
var output = '';
$.each(selectValues[$vendor.val()], function(key, value) {
output += '<option>' + key + '</option>';
});
return output;
});
}).change();
// bonus: how to access the download link
$model.change(function() {
$('a#download-link').attr('href', selectValues[$vendor.val()][$model.val()]).show();
});
}
});
})

jQuery $.ajax(), pass success data into separate function

I am using the jQuery $.ajax() function. I have put this into a parent function, which passes some values into the ajax function. What I would like to do, is have a user defined callback function, which gets the data param passed in from the ajax success function.
Here is what I was thinking would work, but it is not:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: callback
});
}
Then I want to be able to call that function, and pass in my custom function so that I can use the success functions data from inside that function:
testFunc('my string data', function(data){
alert(data);
});
I am wanting this to be the same as:
testFunc = function(str, callback) {
// Send our params
var data = 'some data to send';
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: data,
success: function(data) {
alert(data);
}
});
}
Works fine for me:
<script src="/jquery.js"></script>
<script>
var callback = function(data, textStatus, xhr)
{
alert(data + "\t" + textStatus);
}
var test = function(str, cb) {
var data = 'Input values';
$.ajax({
type: 'post',
url: 'http://www.mydomain.com/ajaxscript',
data: data,
success: cb
});
}
test('Hello, world', callback);
</script>
You can use this keyword to access custom data, passed to $.ajax() function:
$.ajax({
// ... // --> put ajax configuration parameters here
yourCustomData: {param1: 'any value', time: '1h24'}, // put your custom key/value pair here
success: successHandler
});
function successHandler(data, textStatus, jqXHR) {
alert(this.yourCustomData.param1); // shows "any value"
console.log(this.yourCustomData.time);
}
this is how I do it
function run_ajax(obj) {
$.ajax({
type:"POST",
url: prefix,
data: obj.pdata,
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
if(obj.func){
obj.func(data);
}
}
});
}
alert_func(data){
//do what you want with data
}
var obj= {};
obj.pdata = {sumbit:"somevalue"}; // post variable data
obj.func = alert_func;
run_ajax(obj);
In the first code block, you're never using the str parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}
I believe your problem is that you are passing testFunct a string, and not a function object, (is that even possible?)
Although I am not 100% sure what you want (probably my brain is slow today), here is an example of a similar use to what you describe:
function GetProcedureById(procedureId)
{
var includeMaster = true;
pString = '{"procedureId":"' + procedureId.toString() + '","includeMaster":"' + includeMaster.toString() + '"}';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: pString,
datatype: "json",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "webservice/ProcedureCodesService.asmx/GetProcedureById",
success: function(msg)
{
LoadProcedure(msg);
},
failure: function(msg)
{
// $("#sometextplace").text("Procedure did not load");
}
});
};
/* build the Procedure option list */
function LoadProcedure(jdata)
{
if (jdata.length < 10)
{
$("select#cptIcdProcedureSelect").attr('size', jdata.length);
}
else
{
$("select#cptIcdProcedureSelect").attr('size', '10');
};
var options = '';
for (var i = 0; i < jdata.length; i++)
{
options += '<option value="' + jdata[i].Description + '">' + jdata[i].Description + ' (' + jdata[i].ProcedureCode + ')' + '</option>';
};
$("select#cptIcdProcedureSelect").html(options);
};

Categories

Resources