Ajax unable to pass other variables with serialize() - ajax

What I am trying to achieve is making an Ajax call to the server to return some data whilst also taking into consideration what filters have been selected in my form ".searchfilters form". I am trying to pass variables along with a form serialize and am getting a syntax error unepected token . on page load. Have I merged the normal variables I want to pass along with the form.serialize in the wrong way? Also if there is a better method to applying filters to an ajax request im open to it but this is the main method I have found from online examples.
$(".sidebar-list-parent li a, .sidebar-list-child li a").click(function(){
var soundid = $(this).attr("soundid");
var soundidparent = $(this).attr("class");
var filters = $(".search-filters form");
$.ajax ({
type: 'GET',
data: {filters.serialize(), soundid:soundid, soundidparent:soundidparent, }
url: "audio-module.php",
success: function(data) {
$('.audio-modules-container').html(data);
}
});

Change
data: {filters.serialize(), soundid:soundid, soundidparent:soundidparent, }
to
data: {filters.serialize(), soundid:soundid, soundidparent:soundidparent },

Related

django ajax, can't capture a list from get ajax request

I'm trying to capture a list of filters in an ajax request, but although I can capture a single filter, when I try to capture a list, I just get an empty list for some reason.
Below is the relevant part of my view and the ajax (jQuery) function. When I try and send a single filter with $.ajax({ .... 'filters': fixed }) this works but fails with a list.
Update: trying data: {'filters': JSON.stringify([fixed])}, does pass the data through as a string to django '["fixed"]' (which I can handle if I don't use getlist but .get and then json.loads() but I think there must be a simpler method here.
def quotes_results_filter_view(request):
results_filters = request.GET.getlist('filters') or []
quotes_results = request.session['quotes_results']
for results_filter in results_filters:
.......
Ajax function:
$(document).ready(function () {
$('#id_filter').change(function (e) {
var fixed = $(this).val()
console.log(fixed)
$.ajax({
url: '/users/filters/',
data: {
'filters': [fixed]
},
dataType: 'json',
success: function (data) {
console.log(data)
}
})
When you send a list through jQuery it changes the keyword to
so in Django you probably have to get like this:
request.GET.getlist('filters[]')

get data from ajax as an attribute value for callback function

Im new to ajax. I was trying to find the answer but was not lucky to find the corresponsing one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.
This ajax part is just a method of myObject.
So, in the end I need this kind of functionality:
myObject.getData(url, callback(data) {
//my custom code of what I wanna do after ajax is complete
});
My code
/*
HERE COME SOME PROPERTIES AND OTHER METHODS WICH IS NOT THE CASE
*/
//This is where Im stuck
var getData = function getFromUrl($url) {
$.ajax({
type: 'get',
url: $url,
dataType: 'html',
success: function(html) {
$obj = html;//Im lost on this step!
},
});
};
P.S. Im trying to find an async way (without using async:false). Hope its possible
First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.
var getData = function getFromUrl(url) {
$.ajax({
url: 'http://cors.io/?' + url,
crossDomain: true,
dataType: 'html',
success: function (html) {
var match = $(html).find(".bounty-indicator-tab").first().html();
console.log(match);
return match;
},
error: function(e) {
console.log('Error: '+e);
}
});
};
url = 'http://stackoverflow.com/';
data = getData(url);
//You cant use data yet because its working async

Ajax form submission

I am using ajax to submit a html input form and to redirect the output page when it is done. I tried two approaches but not sure why their results are different.
HTML form is something looks like this:
<form id="output_post" method="post" action="output.html">
<table class="input"></table>
</form>
Approach 1:
var frm = $('#output_post');
frm.submit()
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
success: function (url) {
window.location = "/output.html"
}
});
Approach 2:
var frm = $('#output_post');
$.ajax({
type: "POST",
url: frm.attr('action'),
success: function(url) {
window.location = "/output.html"
}
});
Approach 1 worked as I expected but I got error message in Approach 2 405 Method Not Allowed The method GET is not allowed for this resource. The difference between Approaches 1 and 2 is frm.submit(), and I am very sure both approaches have successfully initiate calculation.
Could anyone give me some hints on this issue? Thanks!
Firstly, I would actually say .submit() would be better reserved for allowing the Browser to actually go ahead with the natural/indented behaviour of following through to the action="" - if you wanted to actually have a different 'end result' - that's where $.submit() comes into help.
/**
* $.submit will listen to
* the .submit event, preventing
* default and allowing us to mimic
* the submission process and have our
* bespoke end result.
**/
$('#output_post').submit(function(event) {
event.preventDefault();
var getValues = $(this).serialize();
$.post( 'yourScript.php', getValues, function() {
window.location.href = "/output.html";
}
});
Comments to the Question
Approach One
This 'leaves' the function. Prematurely sending you away from the page before it's allowed to execute the rest of the script. The native .submit() will follow through to the action, which is the indented behaviour. Thus, $.ajax never ran.
Approach Two
Servers could/can decide on it's accepted content types.
No Data was sent to the URL, thus - defaulted to GET (Despite type: POST) But there's no serialised. array given.
This may 'act' different if you define 'data: values' in Approach Two.
Try this:
var frm = $('#output_post');
$('#output_post').submit(function(event) {
$.ajax({
type: "POST",
url: frm.attr('action'),
success: function(url) {
window.location = "/output.html"
}
});
});
-
Thanks

How to perform ajax call to doaction in ofbiz

I would like to use Ajax to perform an action in OFBiz without the page refreshing. The task will be like filters. When I choose any Checkbox it should perform some action and display the result in the very same page.
What are all the steps i need to do?
I would appreciate some sample code for controller.xml,javascript calling Ajax ..etc
Thanks.
You can use form submission through ajax on an event in your ftl's. Here's a sample code for ajax call from say an ExampleCreateParty.ftl:
$.ajax({
url: '<#ofbizUrl>addSecurityPermissionToSecurityGroup</#ofbizUrl>',
type: 'POST',
accepts: 'xml',
data: $("form#Permissions").serialize(),
success: function(e) { console.log(e);
var xmlDoc;
try {
xmlDoc = $.parseXML(e);
var error = $(xmlDoc).find("Message").find("Error").find("ErrorCode").text();
var errorMsg = $(xmlDoc).find("Message").find("Error").find("ErrorMessage").text();
if (error=='0'){alert(errorMsg);}
console.log(xmlDoc);
} catch (err) {
alert('Saved Successfully!');
}
},
error: function(e) { console.log(e); }
})
Here in response to the service called i.e. addSecurityPermissionToSecurityGroup you can specify the response in the controller.xml which you can get within the success key in the ajax call itself.
To see a full end-to-end example have a look at this OFBiz page
As you can see whenever you change the product configuration, the product price is updated with Ajax call. Then you can find out for yourself the freemarker file containing javascript and the controller doing calculations and returning it back.

jQuery filtering AJAX data and then replaceWith data

I am calling pages via AJAX in jQuery.
The content of these pages needs to be filtered so that i only grab a certain DIV class. In this instance 'Section1'.
This filtered data needs to replace the same data on the current page in the DIV of the same class.
I currently have this but it is not really working for me:
$("#dialog_select").live('change', function() {
//set the select value
var $optionVal = $(this).val();
//$(this).log($optionVal);
$.ajax({
type: "GET",
url: $optionVal,
dataType: "html",
cache: false,
success: function(data) {
var $filteredData = $(data).filter('.Section1');
$('.Section1').replaceWith($filteredData);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
I think your problem is likely here:
var $filteredData = $(data).find('.Section1');
$('.Section1').replaceWith($filteredData);
.filter() would only find top level elements in the response (if it's a page, that's <html>, and wouldn't have any results). .find() looks for decendant elements. Also keep in mind that if you have multiple .Section1 elements, this won't behave as expected and will have some duplication going on.
This is a tricky thing to do and I would recommend placing the data into something like a DOMParser or document.implementation.createDocument or MSXML.
if (window.DOMParser) {
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
is a basic code example. jQuery itself can filter on a selector with the load function. http://api.jquery.com/load/ This however has several limitations such as not being able to filter on html, head, or body tags. This is why the above method is safer.

Resources