form.serialize() doesn't send all values in the Ajax $.post() - javascript

I'm getting all the values from a form using serialize() and send them through a Ajax call using $.post() as follow:
$('button#btnBuscar').on('click', function (ev) {
ev.preventDefault();
$.post('someRoute', $('#buscadorNorma').serialize(), 'json')
.done(function (data, textStatus, jqXHR) {
console.log(data.entities);
})
.fail();
});
After click the submit button I check the POST data (in Firebug) send ​​to the route and I notice that only the last parameter was taken in this case comite_tecnico but what about the rest of them? Even if have values isn't send at all, why? I leave a fiddle for testing purpose, can I get some help?
This is a image showing the results:
Note: for check the POST data use Firebug or any other tool!

Add name attributes to your input elements like this:
<input type="text" id="codigo_norma" name="codigo_norma" class="form-control">

Related

Do a form submit calling a function instead create specific submit on its id

I did on a project many forms with its "" in the part of page (generated by php) that add specific function to it per form id and are working, for example:
$("#fregistrazione").submit(function(event){
...
}
I did the same with an html part loaded with ajax request but is not working.
I thinked to do in a different way with the same function called by many form submit, instead having one different defined for any form on any form submit, call a function with additional parameter that do the specific form things with less code duplication but I'm unable to have it working.
I did many try, for example:
<form id="f_man-marker_edit-marker" method="post" action="#" onsubmit="TM.editMarker(this)">
...
...
TM.editMarker = function(rform){
// Abort any pending request
if (request) { request.abort(); }
let form = $(rform);
// Let's select and cache all the fields
let inputs = form.find("input, select, button, textarea");
// Serialize the data in the form
let serializedData = form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
inputs.prop("disabled", true);
request = $.ajax({
url: "ajax.php?req=man-marker_edit-marker",
type: "post",
data: serializedData,
dataType: "html"
});
request.done(function (response){
$("#ajaxoutput2").empty().append(response);
$("#ResultModal2").modal("show");
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"Ajax man-marker_edit-marker request failed. The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
inputs.prop("disabled", false);
});
};
but on submit reload the page with parameters as "get" in url and didn't execute the edit marker function.
Can someone please tell me what I did wrong and how to do a correct call of a function from the form submit instead do a .submit on any form id containing dozens of duplicate lines for each form and not working if generated by a code that is received through ajax request?
Thanks for any reply and sorry for my bad english.
EDIT:
I did what suggested by ChrisG and I tried to add a parameter in TM.editMarker but I not found how to maintain correctly event as first parameter and add 2 other parameters.
For example adding 1 parameter:
TM.editMarker = function (e, ajax_request) {
...
I tried (even if IDE gave me event as deprecated):
$('#f_man-marker_edit-marker').on('submit', TM.editMarker(event, 'man-marker_edit-marker'));
And also without but in both case don't work.
EDIT2:
solved with:
$('#f_man-marker_edit-marker').on('submit', function(e){
TM.editMarker(e, $(this), 'man-marker_edit-marker');
});
...
TM.editMarker = function (e, form, ajax_request) {
...
but I'm open to better solutions.
Simple Answer:
You manipulated the DOM, so your selector is not there yet on event-binding.
Use a parent selector thats already there like document
$(document).on("submit", "#fregistrazione", function(event){
event.preventDefault(); // stop the form submitting if needed
...
});
this way it will work

Exchange data between HTML page and Java servlet without page refreshing

I would like to create a simple login form with HTML and Java (and maybe JSON). So, I have a login form with several input fields with the following id-s: txtUsername, txtPasswd, btnLogin.
After click on the button (btnLogin) I would like to send data to the servlet, and get back just a true/false value deepends on the user-passwd combination.
I can write the HTML code of this form, and the server side code, but I don't know, how can I send and recive data without page refreshing.
Here is my frontend code:
<script>
function login(){
var user=document.getElementById("txtUsername");
var passwd=document.getElementById("txtPasswd");
//???
}
</script>
Username: <input type="text" id="txtUsername"/> <br/>
Password: <input type="password" id="txtPasswd"/> <br/>
<input type="button" value="Login" id="btnLogin" onclick="login()"/>
You have to use an AJAX request. One way of doing it is to wire up and event handler on a your login button (like onclick), which calls a JS function to use an Ajax request (XmlHttpRequest), just like you have started.
You can do it in vanilla Javascript, but it is easier to use a library like jQuery. The code would look something like this (with jQuery, note the '$'):
function login() {
$.ajax({
type: 'POST',
url: url, //Url of login endpoint
data: DATA, //Now here you would want to send a payload i.e. your username and password data
dataType: 'json',
contentType: 'application/.json',
success: function(data) {
//HERE 'data' would represent your true or false that came back from the server.
//You can do stuff here with the response
},
error: function(jqXHR, textStatus, errorThrown) {
//IF ERROR then this code would be executed.
}
});
}
Hope this gives you a starting point!
You must use jquery AJAX.
Here is a link to the official documentation: http://api.jquery.com/jquery.ajax/
Hope it helps.

Scripts loaded through ajax don't send the post data to themselves properly?

So the structure is:
index.php
loads /index.php#ajax/landing.php
landing.php has a form, the form data is sent as post request (Tamper data show the POST data being sent), but var_dump($_POST); in landing.php is showing empty. I'm guessing because of the way the script is loaded the post data must be being sent to index.php and must not be accessible to landing.php?
is there a work around for this?
I've considered the possibility of using ajax to send the post data and show the result in a div but i'm not that good with it and don't really understand what i'm doing,
so in my scenario here is what i'm trying to do:
<form name="search_form" id="search_form" method="POST">
<input type="text" name="search" id="search" />
<input type="submit" name="submit_search_form" id="submit_search_form" value="search" />
</form>
<div id="search_results">
</div>
How would I make this send a POST request to /php/search.php then put the results of what the script does with the post data into the search results div?
Any ideas / help would be greatly appreciated.
note i'm asking for POST as GET/query strings can be accessed by the page, but isn't appropriate for other tasks like changing passwords so although in the scenario i've mentioned would be fine as a GET request, I need to figure out a way to get POST working regardless.
I use something like this (which requires jQuery):
$(document).ready(function() { // When the document is completely loaded this function runs
$('form').unbind('submit').bind('submit', function(event) { // catch the pressing of enter and catch submit action. Makes sure the form does not get posted the normal way
if (event.keyCode == 13) { // if enter is pressed
return false;
}
pageRetrieve($(this).attr('action')+"?"+$(this).serialize(), 'POST'); // send this data to the function that sends the post
event.preventDefault();
return false;
});
});
function pageRetrieve(href, sType) { // this function send the data to the server
sType = (typeof sType === "undefined") ? "GET" : sType; // if 'POST' is not set in the previous function, set it to GET
$.ajax({ // function to send the data to the server
url: href, // the url to send it to
type: sType, // the type (post/get)
success: function (data) { // when the server responds successful
$('#search_results').html(data); // put the data in your div
},
error: function () { // if call to server is not correct (eg wrong url)
alert("error");
}
});
}
This just posts data to the specified url in the form.

Ajaxform getting the data before the submit is called

I am working with AjaxForm plugin
I want to alert the data what is being pushed to server.
<form class='frmAppList'>
<input type='hidden' name='deviceid' value='<deviceId>'>
<input type='hidden' name='operationtype' value='<Coming from server>'>
<input type='hidden' name='type' value='command'>
<button type="submit" class='btnAppsList button'>
APPS LIST
</button>
</form>
This is in loop in jsp so the form is generated more than once having class -> frmAppList.
I am using the class to apply ajaxform like this:
$('.frmAppList').ajaxForm({
url : 'urltoserver',
dataType : 'json',
type : 'post',
beforeSubmit : function() {
return false;
//something here that gives me the device id that is passed
//since the form is not one I cant use id, also every form has **deviceid**
//i need to get that deviceid so that i can pass it in **success** ajax call
//at ***Label->(A)***
},
success : function(response) {
if (response.status) {
//***Label*** ->(A)
//have to call other ajax call to take the data
//for that i need the device id that is going in this ajax call
}
},
error : function(xhr, ajaxOptions, thrownError) {
alert('error');
},
timeout :10000
});
How can I get that device Id,plz help me....
Thanks a ton.....
From ajaxForm doc :
success
Callback function to be invoked after the form has been submitted. If a 'success' callback function is provided it is invoked after the response has been returned from the server. It is passed the following arguments:
1.) responseText or responseXML value (depending on the value of the dataType option).
2.) statusText
3.) xhr (or the jQuery-wrapped form element if using jQuery < 1.4)
4.) jQuery-wrapped form element (or undefined if using jQuery < 1.4)
Default value: null
The third and fourth argument are what you're looking for. Start there:
success : function(response,status,request,form) {
console.log(request,form);
}

getJSON fails, JSON validates

I have a getJSON call which is inexplicably failing. The idea is, you click to submit a comment, a URL gets hit which determines if the comment is OK or has naughty words in it. The response is given in JSON form.
Here's the paired down JS that generates the call. The comment and the URL are already on the page, it grabs them and hits the URL:
FORM HTML:
<fieldset id="mg_comment_fieldset" class="inlineLabels">
<div class="ctrlHolder">
<textarea id="id_comment" rows="10" cols="40" name="comment"></textarea>
</div>
<div class="form_block">
<input type="hidden" name="next" value="" />
<input id="mg_comment_url" type="hidden" name="comment_url" value="" />
<input id="mg_comment_submit" type="submit" value="Remark" />
</div>
</fieldset>
SPECIFIC JS BLOCK THAT SENDS/READS RESPONSE:
$('input#mg_comment_submit').click(function(){
var comment = $("textarea#id_comment").val();
var comment_url = $('input#mg_comment_url').val();
$.getJSON(
comment_url+"?callback=?&comment="+comment+"&next=",
function(data){
console.log(data);
alert(data);
});
});
The JSON response:
[{"errors": {"comment": ["Weve detected that your submission contains words which violate our Terms and Conditions. Please remove them and resubmit test"]}}]
It's being returned as a mimetype of application/json. It validates in JSONLint. I also tried adding a couple AJAX functions to try to catch errors, and they're both silent. I can see the request going out in Firebug, and coming back as status 200 responses, which validate in JSONLint and which I can traverse just fine in the JSON tab of the response. If I put an alert before the getJSON, it runs; it's just that nothing inside of it runs. I also find that if I change .getJSON to .get, the alerts do run, suggesting it's something with the JSON. I'm out of ideas as to what the problem could be. Using Firefox 3.0.13.
The querystring parameter "callback=?" comes into play if you are using cross-site scripting or jsonp, if you are posting the same server, you don't need to use that.
If you need or want to use that option, the server side code needs to come back with the callback function included in the json response.
Example:
$jsonData = getDataAsJson($_GET['symbol']);
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"symbol" : "IBM", "price" : "91.42"});
So either make a server side change if necessary or simple remove the "callback=?" parameter from the url.
Here's more info on jsonp
Are you able to manually call your service without any errors? Have you tried using firebug and looked under XBR to see the post/response of the JSON payloads? I normally use .NET as my endpoints, and with .NET 3.5 I need to use content type "application/json; charset=utf-8".
Here is an example of a working JSON call I use in .NET with jQuery 1.3.2
$.ajax({
type: "POST",
url: "WebService1.ASMX/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
success: function(res) {
// Do your work here.
// Remember, the results for a ASMX Web Service are wrapped
// within the object "d" by default. e.g. {"d" : "Hello World"}
}
});
Have you tried it with $.ajax? You can then define both error and success callbacks and have better idea.
Can you try adding a global ajaxError function to log the error.
$.ajaxError( function(event, XMLHttpRequest, ajaxOptions, thrownError){
console.log( thrownError );
});

Categories

Resources