I use this serializeObject function for my forms.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};`
I can do this for the ajax call
$('form#changeprofileform').serializeObject();
This works fine for the textfields I have, but when I want to upload a file, the input type="file" is not in the object so I cannot send it to the server to upload.
I searched around on stackoverflow but I can't really find anything that will help.
Does anyone know why this is not working and what I can do about that ?
P.S. I know it is possible to upload files with an iframe, but I want to do it this way
Thanks!
edit
I can ofcourse do it without the serializeObjectfunction and send all the inputs with .val, but that will not work in IE9 :(
Related
AJAX code:
var data = $('#myIDform').serializeObject();
$.post(
'my url',
{data: data},
function(response){
response
});
The serializeObject() function: (I took it from a similar post in here)
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
I don't have any kind of parsing or stringify method or so, and whenever I add a new entry on my db with special characters (e.g. 'ñ') it shows perfectly in the response, but the database saves this: 'ñ'
I am not sure the problem is in the database, because the same thing without AJAX, works.
EDIT: When I manually refresh the page it shows as the database, since it's where the data is taken
I have been reading over here and JSON.parse and JSON.stringify dosen't seem to work for me, because I get something strange in the database: '{'I guess I am not doing it correctly or something is working not as intended.
In the .php i parsed it as: $result = $obj->insert ( JSON_parse($_POST['data']) );
And in the .js i strigified it as: var data = JSON.stringify($('#myIDform').serializeObject();
How it looks like in the database: http://prntscr.com/99t6po
EDIT: SOLVED. Database and PHP were in different charsets
I am trying to submit a form as a JSON object because I want to create a REST API with play.
The issue that I have is that Play tells me that is not a valid JSON.
My FORM code:
#(form : Form[Product]) #main("Create Form"){
#helper.form(routes.Products.createProduct, 'enctype -> "application/json"){
#helper.inputText(form("name"))
<button>Commit</button>
} }
Controller Code:
// Read JSON an tell if it has a name Path
#BodyParser.Of(BodyParser.TolerantJson.class)
public static Result createProduct() {
JsonNode json = request().body().asJson();
String name = json.findPath("name").textValue();
if (name == null) {
return badRequest("Not JSON");
} else {
return ok(name);
}
}
Whats the best way to do this? a read about submitting with Ajax but because I am new with play I don´t figure it out the way to do this with Play´s form syntax.
You can do it easily with jQuery (so make sure you have jQuery included in your head) and formAsJson() function based on serializeObject function.
#helper.form(routes.Products.createProduct(), 'id -> "myform") {
#helper.inputText(jsonForm("name"))
<button>Commit</button>
}
<script>
$.fn.formAsJson = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return JSON.stringify(o)
};
var $myform = $("#myform");
$myform.on('submit', function () {
$.ajax({
url: $myform.attr('action'),
type: $myform.attr('method'),
contentType: "application/json",
data: $myform.formAsJson(),
success:function(){
alert("Great! Everything's OK!");
},
error: function(){
alert("Booo, something wrong :(");
}
});
return false;
});
</script>
and your createProduct() action could look just like:
public static Result createProduct() {
JsonNode json = request().body().asJson();
String name = json.findPath("name").textValue();
if (json==null || name==null || ("").equals(name.trim())){
return badRequest();
}
return ok();
}
$(function(){
var a=document.getElementById('text_editor_textarea'),regEx=/^\s*$/,
updateOrig = function() {
var sc = $(a).data('sceditor');
if(sc){
sc.bind('keypress', sc.updateOriginal);
sc.blur(sc.updateOriginal);
}else {
setTimeout(updateOrig , 200);
}
};
updateOrig();
if(a.value !== "" && regEx.test(a.value) ){
window.onbeforeunload = function(){
return "You have a post waiting to be submitted";
};
}
});
This code should check if there is data in a and if there is onbeforeunload the alert should be prompted. It works except that even if there is no data in the textarea it still is prompted. Am I doing something wrong here?
Just do a.value !== "" instead of a.value !== null || a.value !== "" inside of this if block:
if (a.value !== null || a.value !== "") {
window.onbeforeunload = function () {
return "You have a post waiting to be submitted";
};
}
Also, flip the if and the event function assignment to this:
window.onbeforeunload = function () {
if (a.value !== "") {
return "You have a post waiting to be submitted";
}
};
I didn't realize this before, but only on page load would your message get called since otherwise the assignment wouldn't occur since the textarea would be empty when you first opened the page.
jsFiddle
I am pretty new to jquery and can't seem to figure this issue out.
I need to figure out how to dynamically set the key:value pairs in this code below from a form that has dynamic values for form inputs. The code works if I add the key:value pairs manually, but I don't always know what the form names are going to be as they are created by the user.
Please see the notes in the middle section of code below. I am trying to use the values from .serialize() to pass as the $_POST value.
Here is the value I currently get from the var formValues:
ID=10&user_login=test9&wplp_referrer_id=&&block_unblock=u
However when I try to pull the values in my function using:
$user_id = $_POST['ID'];
The ID of '10' is not being set in $user_id, indicating that the syntax or method I am using to pass the serialized results is not correct below.
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var formValues = $("#wplp_edit_member").serialize(); //Get all the form input values
alert(formValues); //Check form values retrieved for testing only
var numbers = /^[0-9]+$/;
// Validate fields START
var wplp_referrer_id = $("#wplp_referrer_id").val();
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Post data to ajaxurl
$.post(ajaxurl, {
action: "wplp_edit_member", //Call the PHP function to update/save form values
data: formValues, //Use data to pass form field values as $_POST values to the function above
// No More manual inputs of form fields to be passed
//ID:$("#ID").val(),
//user_login:$("#user_login").val(),
//wplp_referrer_id:$("#wplp_referrer_id").val(),
//block_unblock:$("#block_unblock").val(),
},
// Success
function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
}
);
return false;
});
});
Thanks!
If you want to post data as json, you can use a variation of $.fn.serialize(), Add the jquery extension,
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and use it as,
var data = $('#some-form').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
If posting json is not your requirement $.fn.serializeArray can work.
hope this helps.
What you want is to dynamically add properties to a javascript object. How this can be done is all over the web, but also demonstrated here:
Is it possible to add dynamically named properties to JavaScript object?
so in your case, you would set your object up first before calling .post:
var formData = {};
for (...) {
formData[...] = ...;
}
$.post(ajaxurl, formData, function (data) {
...
});
One way you might accomplish the iteration above is to just collect values from all inputs between your <form> tags:
$('form input').each(function ($input) {
formData[$input.attr('name')] = $input.val();
});
There are lots of ways to skin this cat. Also, jQuery has lots of plugins that might be of help here, although usually YAGNI (You Aren't Going To Need It), so just KISS (Keep It Simple, Stupid).
Here is the solution I was able to get working based on the code provided by #shakib
jQuery(document).ready( function($) {
$("#wplp_edit_member").submit( function() {
var numbers = /^[0-9]+$/;
var wplp_referrer_id = $("#wplp_referrer_id").val();
// Validate fields START
if( !wplp_referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var data = $('#wplp_edit_member').serializeObject(); //the dynamic form elements.
data.action = "wplp_edit_member";
$.post(ajaxurl, data, function(data) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
//alert("Member Updated");
//document.location.reload();
});
return false;
});
});
This is actually a very simple implementation if you understand Jquery/Javascript! ;o)
Thank you to everyone for your input!
var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod != '' && newprod != null) {
$.ajax({
//posting code here
});
}
if (act != false) { document.location.href = window.location; }
The page is refresh in every condition even act false or not.
It is fired on an event.
Can anyone tell me why it page is refreshed in all condition?
var act = false;
var newprod = prompt("tell me somthing", "");
if (newprod) { // not null, undefined or 0
$.ajax({
//posting code here
});
}
if (act) { window.location.reload(1); }
assuming that is what the code was supposed to do. document.location is deprecated and in theory read-only.
This should work
if( newprod != null && newproda.length != 0) {
//Execute the code
}
To the reason why it was always working was that newprod was not the same as ''.
As the question is what is wrong with that JavaScript code i will advise.
if(act) {
document.location.href = window.location;
}
You may want to learn more about false-y values in JavaScript. My guess is that your if statement is giving you some problems because it does not compare the way you think it should compare.