Here's the most basic code of it (i'm using this)
$("form").relatedSelects({
onChangeLoad: 'datasupplier.php',
selects: ['stateID', 'countyID', 'townID', 'villageID']
});
i need to pass several more parameter for some reason. my usual ajax code is something like this
$.post("ajax/template.php", {myparams: $("#myparams").val(), action: "SEARCH_MEMBER_DETAILS" },
function (data){
var returnCode = data.returnCode;
if (returnCode == "1"){
$("#data").val(data.name);
}
},"json");
question is, how do I send the params like myparams and action to the jQuery Related Selects code?
i tried something like
$("form").relatedSelects({
onChangeLoad: 'datasupplier.php',
data: {action: "SEARCH_MEMBER_DETAILS"},
selects: ['stateID', 'countyID', 'townID', 'villageID']
});
but it seems the additional params are not sent
The relatedScripts plugin does not provide any facility to manipulate the ajax request.
But it is possible to alter it slightly to achieve the requirement.
If you are ready to make a change in the plugin do the following steps
In the populate($caller,$select,o) method of the plugin make the following change
beforeSend: function(){
return o.onLoadingStart.apply($select, Array.prototype.slice.call(arguments,0));
},
It is now beforeSend: function(){ o.onLoadingStart.call($select); },
Then change your script like
$("#example-2").relatedSelects({
onChangeLoad : 'datasupplier.php',
loadingMessage : 'Please wait',
selects : ['stateID', 'countyID', 'townID', 'villageID'],
onLoadingStart : function(jqxhr, settings) {
console.log('st', arguments, settings.url);
settings.url += '&t=tttt'
}
});
Demo: Fiddle
I've went through the documentation of the plugin and seems that there's not a way to achieve what you need.
If you don't want to extend the plugin and implement the functionality by yourself, you can try by creating the parameter inside the onChangeLoad and pass them as GET parameter like this:
$("form").relatedSelects({
onChangeLoad: 'datasupplier.php?myparams='+$("myparams").val()+'&action=SEARCH_MEMBER_DETAILS',
selects: ['stateID', 'countyID', 'townID', 'villageID']
});
Related
I'm trying to pass dynamically keys for data option into ajax call.
data:{action:'add',id:10},
Actually I'm trying to create global function, which can be use for all tables for disable the specific rows onClick event. For that purpose I need to add different actions and table column names for calling php function. So i want to pass keys also as well as values.
JS Function
function globalDisable(id,table_column,call_action){
// call_action is use for calling the related php function
// table_column is use for calling the column name of that table
action_parm = {call_action:'disable',table_column:id}
$.ajax({
type:'POST',
url:'post.php',
data:action_parm,
success: function(response){
}
});
}
Call JS Function
onclick="return globalDisable(10,'user_id','disableUser');"
Php Script
$disableUser = (isset($_REQUEST['disableUser']))? (string)$_REQUEST['disableUser']:'not';
if($disableUser != 'not'){
$response->disArea($user_id);
}
When I run the function, in console doesn't changing its remains same call_action=disable&table_column=10.
So is this possible to pass dynamically keys for data option in ajax call? I would like to appreciate if someone guide me regarding this. Thank You
Instead of action_parm = {call_action:'disable',table_column:id}, write:
var action_param = {};
action_param[call_action]='disable';
action_param[table_column]='id';
See: How do I add a property to a JavaScript object using a variable as the name?
You are passing your action as a parameter to the function but then not using it in the ajax call
function globalDisable(id,table_column,call_action){
// call_action is use for calling the related php function
// table_column is use for calling the column name of that table
//action_parm = {call_action:'disable',table_column:id}
var action_parm = {call_action: call_action,
table_column: table_column,
user_id: id};
$.ajax({
type:'POST',
url:'post.php',
data:action_parm,
success: function(response){
}
});
}
You could do this like this, maybe you will find it easier to read
function globalDisable(id,table_column,call_action){
// call_action is use for calling the related php function
// table_column is use for calling the column name of that table
$.ajax({
type:'POST',
url:'post.php',
data:{ call_action: call_action,
table_column: table_column,
user_id: id
},
success: function(response){
}
});
}
Also in the PHP you are testing for the wrong parameter in $_REQUEST
$disableUser = (isset($_REQUEST['call_action']))? (string)$_REQUEST['call_action'] : 'not';
if($disableUser != 'not'){
$response->disArea($user_id);
}
Consider "Method A: no ajax":
$(function() {
var emails = [
"john#beatles.com",
"george#beatles.com",
"paul#beatles.com",
"ringo#beatles.com"
];
$( "#invitees" ).autocomplete({
source:emails
});
});
This is given a relatively small, "unfiltered" array. The autocomplete function filters it for you as you type. I want to fetch this data once, thereby only requiring one call to the database.
Consider "Method B: 'internal' URL:
$( "#invitees" ).autocomplete({
source:"/api/get/users"
});
This does not work as I expect it to. No matter what I type, the entire list is always there. Now, after research reading the docs, other S/O questions, and every example I can find- they usually conclude with something like this:
"Data should be filtered server side. The autocomplete widget adds the term parameter to the url, so the resulting url is something like: /search.php?term=whatityped
I can handle that, but that's not totally happening in "Method A", is it? For larger data sets, I get it: no need to pre-load 100,000 results. But in this case, I want the ability to run one query and be done with it. That way if a mobile user is standing in the desert with "one bar" of service, his phone won't lock up while the server repeatedly requests new data every time he types a letter, right?
When the request goes to the internal URL:'/api/get/users'... here's the relevant part of the PHP code:
function get($className,$param1="all",$param2=""){
//above parameters will be refactored...
$stmt=$this->db->prepare('SELECT username FROM users');
$stmt->execute();
$this->data=$stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($this->data);
}
That function returns:
["john#beatles.com","george#beatles.com","paul#beatles.com","ringo#beatles.com"]
So again, If I explicitly do this, the filtering works:
var emails = [
"john#beatles.com",
"george#beatles.com",
"paul#beatles.com",
"ringo#beatles.com"
];
$( "#invitees" ).autocomplete({
source:emails
});
but this does not:
$( "#invitees" ).autocomplete({
source:"/api/get/users"
});
What am I missing here?
PS: Here is an unpolished attempt at method C, by the way- "ajax callback":
(Note: it's meant to accept an associative array from PHP, but the point is that it also does not "self-filter")
$( "#invitees" ).autocomplete({
source: function(request,response){
$.ajax({
url:"/api/get/users",
dataType:"json",
data:{
maxRows:5, // ? does not work
//name_startsWith: request.term // ? does not work
},
error: function(xhr,status){
alert(status);
},
success: function (data){
// alert(data);
response($.map(data,function (item){
return{
label: item.username,
};
}));
}
});
}
});
//ensures autocomplete is not set to "off"
$('input[name=invitees]').attr('autocomplete','on');
For completeness, here's My HTML:
<label for="invitees">Invite by email: </label>
<input id="invitees" name="invitees"/>
You can put the autocomplete function inside a callback function and pass the return data into that.
An example:
$.getJSON('/myJSONdata', function(data) {
$( "#input_field" ).autocomplete({
source: data
});
});
This will assign the autocomplete function to the desired fields after the callback is complete and the data would be assigned just as if it were plain text written into the function.
The autocomplete function obviously won't work until the callback completes successfully so that is something that you might want to keep in mind.
I'm trying to create a facebook style like/unlike link and I need to pass some php variables through the JQuery. At the moment I'm passing:
<a class="likelink" href="like.php?id=****&username=****&type=****">Like</a>
But although this works it is refreshing the page and I want it to do it fluently like twitter or facebook, so I need to pass the id, username, etc through JQuery.Ajax post. Can anyone tell me how this would be possible? Also then I want the .likelink to change to Unlike.
Thanks
Use an ajax request for the 'like' action and then change the class in the success callback function:
$('.likelink').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'like.php',
data: {
id: ***,
username: ****,
type: ****
},
success: function() {
$('.likelink').removeClass('likelink').addClass('unlikelink');
}
});
});
You could do something along the lines of:
$('.likelink').on('click', function(e){
var $this = $(this);
$.get($this.attr('href'), function(){
$this.addClass('liked').attr('href', unlikeLink).text('Unlike');
});
e.preventDefault();
});
I have a dilemma that just seems beyond my abilities at the moment!
I have a group of connected sortables using the class 'biglist'.
What I want to do is bind #biglist 's sortreceive callback (which is made whenever a list receives an element from another) to take the 'boxnum' value of the element (which signifies which list its coming from) and perform an UPDATE query changing the id's boxnum value from say 5(list it came from) to 7 (list its been dragged to) so that the state persists.
So the exchange would happen like so (roughly)
$( "#biglist" ).bind( "sortreceive", function(event, ui) {
ajax call to boxchange.php
create vars to represent elements 'boxnum' value and 'box moved to' value
});
Then inside boxchange.php ->
$id = $_POST['id']
$box = $_POST['boxnum']
->update query SET boxid to new boxid WHERE id = posted ID of element
I hope this makes sense. It seems like a pretty slick way to make my program work!
Any help is greatly appreciated.
EDIT:
Just cleaned up the function to see if there are any changes that need to be made to it (which I know there are, because it looks sloppy) This function would need to be copied/altered for each sortable separately but it'd totally make the program work at least!
function ReceiveTwo()
{
$('#sortable2').bind('sortreceive', function(event, ui)
{
boxnum = $(this).attr('boxnum');
id = $(this).attr('id');
$.ajax
({
url: "boxchange.php",
type: "POST",
data: boxnum, id,
success : function(feedback)
{
$('#data').html(feedback)
}
})
});
$('#sortable2').sortable("refresh");
});
$('#sortable2').bind('sortreceive', function(event, ui) {
$.ajax({
url: "boxchange.php",
type: "POST",
beforesend: function(){
boxnum = $(this).attr('boxnum');
id = $(this).attr('id');
},
data: {'boxnum': boxnum, 'id': id},
success : function(feedback) {
$('#data').html(feedback),
}
});
});
beforesend is the event that fires before the ajax call. I believe here you could set your properties to accomplish what you want.
I think the way you want to send your Javascript data to your server-side PHP script is using a Javascript associative array, like so:
$.ajax({
url: "boxchange.php",
type: "POST",
data: {'boxnum': boxnum, 'id': id},
success: function(data,status) { ... }
Your "boxchange.php" script would then be able to access those variables via $_POST['boxnum'] and $_POST['id'].
I think that was your goal, but I'm not entirely sure...
Hoping that using something like this demo it is possible to drag items within and between two columns, and update their order either live or with a "save" button to MySQL. Point being that you can make changes and return to the page later to view or update your ordering.
http://pilotmade.com/examples/draggable/
Doing it for just one column is fine, but when I try to pass the order of both columns, the issue seems to be passing multiple serialized arrays with jQuery to a PHP/MySQL update script.
Any insight would be much appreciated.
If you look below, I want to pass say...
sortable1entry_1 => 0entry_5 => 1
sortable2entry_3 => 0entry_2 => 1entry_4 => 2
EDIT: This ended up doing the trick
HTML
<ol id="sortable1"><li id="entry_####">blah</li></ol>
jQuery
<script type="text/javascript">
$(function()
{
$("#sortable1, #sortable2").sortable(
{
connectWith: '.connectedSortable',
update : function ()
{
$.ajax(
{
type: "POST",
url: "phpscript",
data:
{
sort1:$("#sortable1").sortable('serialize'),
sort2:$("#sortable2").sortable('serialize')
},
success: function(html)
{
$('.success').fadeIn(500);
$('.success').fadeOut(500);
}
});
}
}).disableSelection();
});
This is the PHP query
parse_str($_REQUEST['sort1'], $sort1);
foreach($sort1['entry'] as $key=>$value)
{
do stuff
}
what I would do is split them up
data :
{
sort1:$('#sortable1').sortable('serialize'),
sort2:$('#sortable2').sortable('serialize')
}
then when you post you can get the request and set them as needed, I hope that makes sense
so what I do is this
parse_str($_REQUEST['sort1'],$sort1);
foreach($sort1 as $key=>$value){
//do sutff;
}