I'm unsure of the best practice for modifying the DOM based on an ajax response. I'll try to let the code do the talking because it's hard to explain.
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
var cb = $(this); // for the sake of discussion i need this variable to be in scope
$("form").ajaxSubmit({ dataType: "script" });
}
The server sends a response back, and the js gets eval'd and that means "cb" is out of scope.
What I've done so far is create a couple of helper functions:
var target = undefined;
function setTarget(val) {
target = val;
}
function getTarget() {
return target;
}
And that turns the first snippet of code into this:
// page has multiple checkboxes
$("input[type='checkbox']").live('click', function {
setTarget($(this));
$("form").ajaxSubmit({ dataType: "script" });
}
Then on the server's response I call getTarget where I need to. This seems hackish... Any suggestions?
It's unclear what you're actually trying to do, but I feel like you want to be looking at the success parameter for that AJAX call. The success callback function should execute in parent scope and do what you're looking for.
See 'success' on this page in the jQuery docs.
So what you are trying to do is get the form to submit the content via ajax whenever the user checks/unchecks a checkbox? And because there are several checkboxes, you need to find out which one triggered the submit, so you can change its value to whatever is stored on the server?
If you submit the entire form everytime, why don't you reply with all the checkboxes values, and then change each and every one of them? If not, get the server to reply with the id and the value of the checkbox, then use jquery to find the checkbox with that ID and then change it's value.
How about:
jQuery(function($) {
// give it scope here so that the callback can modify it
var cb,
cbs = $('input[type="checkbox"]');
cbs.live('click', function {
// taking away var uses the most recent scope
cb = $(this);
// disable checkboxes until response comes back so other ones can't be made
cbs.attr('disabled', 'true'); // 'true' (html5) or 'disabled' (xhtml)
// unless you are using 'script' for something else, it's best to use
// a callback instead
$('form').ajaxSubmit({
success : function(response) {
// now you can modify cb here
cb.remove(); // or whatever you want
// and re-enable the checkboxes
cbs.removeAttr('disabled');
}
});
}
});
Related
What i'm trying to do is what i thought would be quite easy, but it doesnt seem to be working. I want to get the href of an object and all the function is returning is undefined.
This is the page that i'm requesting and what i'm trying to retrieve is the href held in the element of the first seller (who's ClassName is ui-link-inherit)
var buy = $.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
alert($(data).find(".ui-link-inherit:eq(0)").attr('href'));
}
);
I thought it was a permissions issue at first but it still wont work even if you run that on the page.
Did you tried to just alert the data you get?
If there is no .ui-link-inherit ofc it wont work and since .ui-link-inherit seems to be a class of jqueryUI which adds the classes after the page is loaded via javascript, you wont get this class via GET
//EDIT: I dont get all this "you cant access the data cause ajax is asynchronus". He is using the get-fukction completely right. He can access data since data IS the returned stuff from the server. Did I miss something that you all get this that way?
You cannot return a value from that function, it is executed asynchronously. Instead just wait for the AJAX to finish and then do something with the result
// don't do this
// var buy = $.get(... etc...);
// the variable buy will never have any value
// do this instead
function getHREF(){
$.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
var buy = $(data).find(".ui-link-inherit:eq(0)").attr('href');
doSomething(buy);
}
);
)};
function doSomething(buy) {
// in here do whatever you want with the ajax data
}
$(document).ready(function () {
getHREF();
});
The site does not allow Cross-site HTTP requests. Read here: HTTP access control
I have a modal window that has a lot of new dynamic elements (inputs, buttons, etc.). I want to see if a certain element(or in this case, and input) gets created and if it does, then change its value.
The scenario is that if I make an ajax request for populating data, and as the user browses the modal window I can reuse some of that data. When the input field I'm looking for gets created, I can just put the value of the ajax call I made previously.
I have tried: $("#myinput_id").val(sellerData['id']);
obviously the above wont work because the element doesn't exists, yet. I'm also trying to avoid new ajax calls for the same data :/
Any thoughts?
$( "#add").bind('click', function() {
$.ajax({
url: '/seller/get',
type: 'POST',
success: function(response) {
sellerData = jQuery.parseJSON(response);
//other code here
//this doesn't work
$("#myinput_id").val(sellerData['id']);
}
});
});
Then the above gets triggers. The input field doesn't exist yet. How can I make it "look for it" if in the future the input field gets created?
Try using .length http://api.jquery.com/length/
if($("#myinput_id").length) //There is at least one element selected
//Do something
a bit confusing question you are saying u want to populate the data and your are using POST
Im running into a problem where i have an ajax driven page that is drawn when a user selects something from a simple drop down:
<select id = "selectdepartment">
<option id = "default">Select an option...</option>
....
</select>
and the remainder of the page is drawn using the jquery .change() :
$('#selectdepartment').change(function(){
});
Which then runs some ajax to php script. everything works great, the problem is when i submit a form that was drawn with ajax (using $_SERVER['PHP_SELF'];), the data gets submited, the page reloads, and the page is cleared but the select box is still left where it was. The user has to move to a different option then back to the one the selected originally to re-fire the .change(). that sucks.
I could fix this by passing a php variable in all of my forms, then checking to see the variable set on every page load and if it is draw the page parts then, but this would lead to pretty messy code and it's less than desirable.
There has to be a way to do this with the jquery library, though my knowledge of the javascript language in general is not what i would like it to be. If anyone has any helpful hints please share, dont do it for me though, i wont learn that way :)
edit: code with .trigger
$('#selectdepartment').change(function(){
var department = $('#selectdepartment').val();
var day = $('#data').data('day');
var month = $('#data').data('month');
var year = $('#data').data('year');
//alert (department);
if(department === "Select an option..."){
$('.hiddenuntildepartmentisselected').css({"display":"none"});
}
else{
$('.hiddenuntildepartmentisselected').css({"display":"block"});
}
showpoints(department);
drawpointstable(department, day, month, year);
displaytheuseresforselecteddepartment(department, '');
$('#sendthedepartment').val(''+department+'');
$('#hiddendepartmentidforaddinganewpoint').val(''+department+'');
}).trigger('change');//end run functions
You can use the .trigger() function to immediately trigger the change event handler when the page has loaded:
$('#selectdepartment').change(function() {
// code here
}).trigger('change');
Or if you need to call it elsewhere via JavaScript/jQuery:
$('#selectdepartment').trigger('change'); // or just .change() as a shorthand
Updated
Your button for the form could make use of the onClick attribute, which would invoke a method to parse the form fields and post the data to your php script via .ajax().
In the success event method you then check any flags you need to and modify the element as you desire if needed.
Basic example:
Inside of .ajax():
...
url: 'xxx.xxx.xxx',
async: true,
type: 'POST',
dataType: 'html',
data: JSON.stringify( form_fields ),
beforeSend: function()
{
// Pre send stuff, like starting a loading gif
},
success: function( data, textStatus, xhr )
{
// Be sure you load the page with the content first
$( '#containing-div' ).html( data );
// Do your check here, and modify your element if needed here
if( flagtocheck === 'xxx' )
{
// Modify the element in question...
}
// I call a custom method termed `.ctrls()` here that makes any
// adjustments to the DOM once its loaded/updated.
},
error: function( xhr, textStatus, errorThrown )
{
}
Of course, you'll want to set flagtocheck appropriately in your case.
Hope that helps!
Note regarding edit
This post was edited to be a little more descriptive and more easily understood. Since the person asking the question is already using the .ajax() method, the success event method is the ideal place for doing what the person asking the question is requesting. It is 1 less method invocation to directly modify the element there than using it to call .trigger() or .change() which then also directly modifies the element.
Is there any way to intercept an ajax request being made via jquery, to insert additional variables into it?
I know that .ajaxStart() lets you register a callback which triggers an event whenever an ajax request begins, but what I'm looking for is a way to cancel that ajax request if it meets certain criteria (e.g url), insert some more variables into its content, and then submit it.
This is for a plugin for a 3rd party software whose own code can't be changed directly.
Edit: Seems like .ajaxSetup() lets you set some global variables related to ajaxRequests. If I registered a beforeSend function, would that function be able to cancel the request to make a different one on meeting certain criteria?
Figured it out, this was the code I used:
jQuery(document).ready(function()
{
var func = function(e, data)
{
//data.data is a string with &seperated values, e.g a=b&c=d&.. .
//Append additional variables to it and they'll be submitted with the request:
data.data += "&id=3&d=f&z=y";
return true;
};
jQuery.ajaxSetup( {beforeSend: func} );
jQuery.post('example.php', {a : 'b'}, 'json');
} );
To cancel the request, returning false from func seemed to work.
I have two drop down forms. When the first is "changed" the second is populated with some data via ajax.
It's work but the value of the second drop down is not cleared on every request (I'm using $('#second_drop_down').children().remove();)
Here is sample code
$('#first_drop_down').live('change', function() {
var x = "some ajax data recived via ajax";
$('#second_drop_down').children().remove();
$('#second_drop_down').append(f);
});
Here you have a code that works, but it is practically like yours (you have a mistake in your example, 2 differente variables "x" and "f"):
http://www.jsfiddle.net/dactivo/8jfHG/
var timeChanged=1;
$("#first_drop_down").change(function()
{
$("#second_drop_down").children().remove();
$("#second_drop_down").append("<option value=\"volvo\">Volvo"+
timeChanged+
"</option><option value=\"saab\">Saab"+ timeChanged+
"</option><option value=\"mercedes\">Mercedes"+ timeChanged+"</option>");
timeChanged++;
});
Probably the code you received by ajax is malformed (I suppose).
Do you make a synchronous Ajax call? If not, you must put the code that changes the second drop down in the callback function, otherwise you will work on data that was not yet received. Assuming you use jQuery:
$.get( 'http://www.example.com', {first:$('#first_drop_down').val()},
function(data) {
$('#second_drop_down').children().remove();
$('#second_drop_down').append(data);
});