Play framework JavaScript function as scala template parameter - javascript

I want to reuse a javascript function using a scala template so I would only have to pass a different success/failure function, but I don't seem to be able to able to pass a javascript function to a scala template.
Please note I'm veeeeerry new to this and don't even know if what I am doing is possible.
This is kind of what I'm trying to achieve:
#(formId: String, success: JavaScript, fail: JavaScript)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success()
/*console.log("save succesfull, progress!")
alert('Save successfull, now move on!');*/
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
//if fails
#fail()
/*console.log(jqXHR.responseText);
var errors = JSON.parse(jqXHR.responseText);
console.log(errors);
alert('Woops, something went wrong: ' + jqXHR.responseText);*/
}
});
e.preventDefault();
});
</script>
How it would be used:
#snippets.ajaxFormSubmit("#form",
function()
{
alert("Save successfull, now move on!");
},
function()
{
alert("Save failed!");
}
)

You can pass any content to a template via Html type.
#(formId: String, success: Html, fail: Html)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#fail
}
});
e.preventDefault();
});
</script>
In a client view you can user it as follows:
#successFunc = {
alert("Save successfull, now move on!");
}
#failureFunc = {
alert("Save failed!");
}
#snippets.ajaxFormSubmit("#form", successFunc, failureFunc)

Related

Ajax wait till redirect to finish executing.

I have basically the same problem as the one described in the link below, but I dont find the solution to be very clear. I want my ajax success function to wait until the window function is finished executing, THEN modify the divs. Instead, it modifies the divs of the current page, then redirects. AJAX: on success redirect then modify new page
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
I Will Suggest you Javascript Local Storage .
main.js
$("#form").submit( function(e) {
e.preventDefault();
var id = $('#searchbar').val(); // store the form's data.
$.ajax({
url: '/search',
type: 'POST',
data: {id:id},
dataType: 'text',
success: function(data) {
//Redirect to the page where we want to display the data
window.location.href = '/test';
data = JSON.parse(data);
console.log(data);
// Store
localStorage.setItem("count", "we analyzed...");
localStorage.setItem("result1", data.county);
localStorage.setItem("totals", "with a score of..");
localStorage.setItem("result2", data.totalSentiments);
},
error: function(jqXHR, textStatus, errorThrown){
console.log("error")
alert(textStatus, errorThrown);
}
});
});
On Ready on same page:
jQuery(document).ready(function(){
if (localStorage.count) {
$("#count").text(localStorage.count);
}
if (localStorage.result1) {
$("#result1").text(localStorage.result1);
}
if (localStorage.totals) {
$("#totals").text(localStorage.totals);
}
if (localStorage.result2) {
$("#result2").text(localStorage.result2);
}
});
Local Storage Store Data in Browser Storage. You Also Can Remove Data From Local Storage.
setting the value of location.href will cause a full page refresh.
Therefore all your scripts will be wiped out.
If you REALLY wants to use the result of a ajax call to a redirected page, you should store this response data somewhere, then reuse it on your new page.
//save "data" in localSotorage
localStorage.myAjaxResponse = data; //if data is JSON then use: JSON.stringify(data) instead.
Then on your "/test" page, create a script to check for the value on the localStorage then display it.
data = JSON.parse(localStorage.myAjaxResponse);
console.log(data);
$("#count").text("we analyzed...");
$("#result1").text(data.county);
$("#totals").text("with a score of..");
$("#result2").text(data.totalSentiments);
Although, there are other better ways to accomplish what you want.
You can do something like this:
On your ajax success:
data = JSON.parse(data);
console.log(data);
window.location.href = '/test?county='+data.county+'&sentiment='+totalSentiments;
Then on your test page write in javascript block:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
if (params.length > 0) {
$("#count").text("we analyzed...");
$("#result1").text(params['county']);
$("#totals").text("with a score of..");
$("#result2").text(params['sentiments']);
}

Passing dynamic field names to jquery's each method

I'm trying to pass a field name dynamically to my function in order for my form to use autocomplete. I then call this function in my page but I keep getting an error and I think it's because it's trying to get the column property literally as opposed to dynamically.
In PHP I could do something like {$fieldName}. Is there a javascript equivalent? Or am I getting this horribly wrong?
// Call to function index.php
inputSuggetion('input.search', 'http://myapi.com/endpoint', 'title')
// Function
function inputSuggestion(element, endPoint, fieldName) {
$(element).on("keydown", function(event) {
$.ajax({
type: 'GET',
dataType: "json",
data: {
q: $(element).val()
},
url: endPoint,
success: function(data) {
var apiCollection = [];
$.each(data, function(key, value) {
apiCollection.push(value.fieldName);
});
$(".autocomplete").autocomplete({
source: apiCollection
});
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
});
}
Thanks!
If I'm right then you want to get the value of field 'title' from your Json data and this field name 'title' will be passed to the function dynamically.
In this case your syntax to get the value from json is wrong.
you just need to change following line of code:
from :
apiCollection.push(value.fieldName);
to :
apiCollection.push(value[fieldName]);
let me know in case of any issue.

SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data

I've been looking all over for the solution but I cannot find anything that works,I keep getting the following error,I have a submit event that will call the function SUValidation with the data thats being
submitted through a text box in php form,I have tried putting contentType: "application/json",//note the contentType defintion looking at other posts but nothing helped..can anyone provide guidance on how to debug this error or at the best provide a solution
Error:-
SyntaxError:JSON.parse:unexpected character at line 1 column 1 of the JSON data
RESPONSE OF SUVALID.py
Just outputs the content of the python script
Hi,
submit event:-
$("#su_validation").submit(function(event) {
console.log("su_validation.submit");
event.preventDefault();
//SUValidation('#su_validation', '#su_validation_table', '#gerrits_su_validation', showDialog, "#su_validation_dialog");
$("#SUValidation_su_validation_table").empty();
var data = { 'product_lines' : [], 'gerrits' : [], 'contacts' : []};
//find all pl's that are checked
data['product_lines'] = ($("#product_line_su_validation").val()).split(",");
data['gerrits'] = ($("#gerrits_su_validation").val()).split(",");
data['contacts'] = ($("#contacts_su_validation").val()).split(",");
console.log(data);
SUValidation(data, '#SUValidation_su_validation_table', '#gerrits_su_validation', "su_validation_form");
});
Function call:-
function SUValidation(data, table_name, gerrit_form, caller) {
console.log("su_validation_form");
console.log(data);
//console.log($(form_name).find('input, select, textarea').serialize());
su_validation_return = null;
//if maintained, we care if they are in ODS
//if not maintained, we don't really mind if they aren't in ODS database
var maintained = null;
console.log("start when");
$.when(
$.ajax({
dataType: "json",
type: "POST",
url: "scripts/suvalid.py",
timeout: 180000,
data: JSON.stringify(data),
success : function(response){
su_validation_return = [];
console.log("python");
console.log(response);
....
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("error");
//alert(xhr.status);
alert(thrownError);
}
})
).then(function() {
console.log("THEN");
var gerrits = data['gerrits'];
console.log(su_validation_return);
var valid_gerrits = true;
..................

Submit Ajax Form via php without document.ready

I am submitting a number of forms on my page via php using Ajax. The code works great in forms preloaded with the page. However, I need to submit some dynamic forms that don't load with the page, they are called via other javascript functions.
Please, I need someone to help me review the code for use for forms that don't load with the page. Also the 'failure' condition is not working.
The code is below:
<script type="text/javascript">
feedbar = document.getElementById("feedbar");
jQuery(document).ready(function() {
$('#addressform').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
Thanks.
You need to bind event by existing html (e.g body).
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()
see api: https://api.jquery.com/on/
Try like this:
$("body").on('submit', '#addressform',function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
you can delegate to document:
$(document).on('submit', '#addressform', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----serialize with "this"
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
error: function () { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
As you have posted this line as below:
I need to submit some dynamic forms that don't load with the page
What i understand with this line is you want a common submit function for all forms which are generated dynamically, then you can do this:
$(document).on('submit', 'form', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----"this" is current form context
success: function () {
//some stuff
},
error: function () { //<----use error function instead
//some stuff
}
});
e.preventDefault();
});
});
For your last comment:
You can try to get the text in ajax response like this:
success: function (data) {
feedbar.innerHTML='<div class="text-success">'+ data +'</div>';
},
error: function (xhr) { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">' + xhr.responseText + '</div>';
}
if Success:
here in success function you get the response in data which is the arguement in success function, this holds the response which it requested to the serverside.
if Error:
Same way if something goes wrong at the serverside or any kind of execption has been occured then xhr which is the arguement of error function holds the responseText.
And finally i suggest you that you can place your response in feedbar selector using jQuery this way:
var $feedbar = $('#feedbar');
so in success function:
$feedbar.html('<div class="text-success">'+ data +'</div>');
so in error function:
$feedbar.html('<div class="text-success">'+ xhr.responseText +'</div>');

Spring MVC: Not able to send xml DOM to controller

Trying to build xml out of form values. Earlier I was building it with the help of jQuery. jQuery has a bug and then I have to build XML with plain javascript. But Now when I submit the form, browser hangs and request does not reach the controller.
Controller
#RequestMapping(value="/save",method=RequestMethod.POST,consumes={"application/json", "application/xml", "text/xml", "text/plain"})
#ResponseBody public String handleSave(#RequestBody String formData)
{
System.out.println("comes here");
System.out.println(formData);
return "SUCCESS";
}
jQuery
$('form').submit(function () {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: collectFormData(),
headers: {
"Content-Type":"application/xml"
},
dataType: 'application/xml',
success: function (data) {
alert('Success:'+data)
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('jqXHR:'+jqXHR+'\n'+'textStatus:'+'\n'+textStatus+'errorThrown:'+errorThrown);
}
});
return false;
});
CollectFormData
function collectFormData()
{
$rootElement = $('<FormXMLDoxument/>');
xmlDoc = document.implementation.createDocument("", "", null);
root = xmlDoc.createElement($('form').attr('name'));
$('form').find('div.section').each(function(index, section) {
sectionElement = xmlDoc.createElement($(section).attr('name'));
$(section).find('input').each(function(i, field) {
fieldElement = xmlDoc.createElement($(field).attr('name'));
fieldText=xmlDoc.createTextNode($(field).val());
fieldElement.appendChild(fieldText);
sectionElement.appendChild(fieldElement);
});
root.appendChild(sectionElement);
});
console.log((new XMLSerializer()).serializeToString(root));
return root;
}
Everything works fine if I implement collectFormData with jQuery but then I loose camel casing on element names.
Old collectFormData
function collectFormData()
{
$rootElement = $('<FormXMLDoxument/>');
$formElement = $.createElement($('form').attr('name'));
$('form').find('div.section').each(function(index, section) {
var $sectionElement = $.createElement($(section).attr('name'));
$(section).find('input').each(function(i, field) {
console.log($(field).attr('name'));
var $fieldName = $.createElement($(field).attr('name'));
$fieldName.text($(field).val());
$sectionElement.append($fieldName);
});
$formElement.append($sectionElement);
});
$rootElement.append($formElement);
console.log('Form XML is '+$rootElement.html());
return $rootElement.html();
}
My question related to jQuery bug

Categories

Resources