Ajaxform getting the data before the submit is called - javascript

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);
}

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

How to get parameter from URL in PHP but after load page by jQuery?

I need get (date) parameter form URL by php but after load "step-02.php" by .load jQuery.
For example:
http://localhost:8000/selectRoom?hotelID=100&date=2016-11-08&night=5
I get the 2016-11-08 value from URL by php is $_GET['date'] but after I load step-02.php with jQuery this code $_GET['date'] does not work.
$(function () {
$('#Step-01').hide();
$('#Step-02').show();
$('#Step-02').load('step_02.php');
})
HTML in step-02.php:
<div class="alert alert-success">
// This line gives an error and not work!
<?php echo $_GET['date']; ?>
</div>
http is stateless so unless you pass the date back in the ajax request, or save it to the session, the server has no way of remembering what you've told it previously.
Put this in step1.php somewhere
<input type="hidden" id="date-input" value="<?php echo $_GET['date']?>" />
Then do this:
$(function () {
var date = $('#date-input').val();
$('#Step-01').hide();
$('#Step-02').show();
$('#Step-02').load('step_02.php?date='+date);
})
if i understand well at first you call this url , with these parameters : http://localhost:8000/selectRoom?hotelID=100&date=2016-11-08&night=5, that is why in your PHP file you can get the parameters , $_GET['hotelID'], $_GET['date'] and $_GET['night'] .
When you call step_02.php
The url does not change to a new one , it remains as it was : http://localhost:8000/selectRoom?hotelID=100&date=2016-11-08&night=5,
and that is the problem! The php file step_02.php , did not get any parameters from the client on the server request , so it does not recognise any parameter , although they are on the url.
Solutions:
A. You can get the url by : $_SERVER['HTTP_REFERER'] , which is going to give you all the url as it is, and by explode("?", $_SERVER['HTTP_REFERER']) you are going to get the part of the url that has the parameters, after that you can use explode again..
B. you can pass the parameters you wish while you execute the ajax call to the server, and get them with $_GET['parameter'], like so:
data = {'hotelID':100,'date':2016-11-08,'night':5};
$.ajax({
cache: false,
url : url,
type: "GET",
data : data,
beforeSend: function( xhr ) {
//load your spinner img
},
success : function(data, textStatus, jqXHR){
//get response from server
},
error : function(xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
OR if it need be with load():
$('#Step-02').load('path', 'key=value');
Hope helps, good luck.
Your question is not clear but I assume that you want to get the date value after load.
Use callback()
$('#Step-02').load('step_02.php', function(response, status, xhr) {
alert( "Load was performed." );
console.log(response);
});

ajax form submitting but calling error function

This is a simple form which takes 2 dates from and to and I am submiiting those to values to server.
<form action="#" method="get">
<label for="from">From</label>
<input type="text" id="from" name="fromDate">
<label for="to">to</label>
<input type="text" id="to" name="toDate">
<input type="button" value="Recv Amount" id="recv">
</form>
and the following is the controller code
#RequestMapping("getPayments")
#ResponseBody
public void getPayments(HttpServletRequest request,Model uiModel)
{
String toDate=request.getParameter("toDate");
String fromDate=request.getParameter("fromDate");
System.out.println(fromDate+" "+ toDate);
}
and this is js code
$('#recv').click(function(){
var fromDate=$('#from').val();
var toDate=$('#to').val();
$.ajax({
type: "GET",
url: url,
data:{"fromDate":fromDate,"toDate":toDate},
dataType:"json",
success: function( data ) {
console.log('success');
},
error:function()
{
console.log('failed');
}
});
});
when ever I hit the button I can see todate and from date in the server console (This means System.out.println(fromDate+" "+ toDate); is executed) but in the browser console failed is printed(this means console.log('failed'); is executed)
I do not have any error in browser console but the success function of ajax is never executed.
What could be the reason behind it?
jsfiddle
You are waiting for a JSON answer, but you are not returning anything. jQuery is going to give you an error. Remove 'dataType' from your ajax request or return a valid json object.
From jQuery documentation:
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
jQuery ajax query
EDIT:
Based on the information provided issue is that data is expected the way you formed your success parameter.
Since no data is returned (void method) it won't actually do anything.
Therefore you need to use:
statusCode: { 200: function() { alert( "success" ); } }
Remove success and error as success won't work (no data being returned) and error will display (simply because no data is returned) and replace them with relevant status codes.

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

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">

How to pass form data to PHP via AJAX call (CodeIgniter Framework)

I have the following HTML structure:
<form method="POST">
Name : <input id="asgname" type="text"> <br>
Description : <input id="asgdescription" type="text"> <br>
Save
</form>
I want that on clicking the save button, the form values are sent to the server via AJAX call.
For that, I've attached the click event via following command
$("#asgsave").click(save_assignment);
save_assignment is also a javascript function defined as follow:
function save_assignment() {
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: $('form').serialize(),
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
The above is not working. So I tried the following approach as well:
function save_assignment() {
var formvalues = {
name : $('#asgname').text(),
descripion : $('#asgdescription').text(),
};
return $.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/user/save_assignment",
data: {values : formvalues},
success: function(response) {
alert('Form was submitted');
},
error: function(error) {
alert("Error");
}
});
}
But this is also not working.
Can anyone please guide me as to why are the above methods not working and what is the correct way to do so ?
EDIT-1 :
By not working, I mean: in the first case ($('form').serialize() approach) the data is not being sent to the server. I checked it via chrome and firefox debugger that there was no post data sent corresponding to the form.
And in the second case, empty values are being sent. i.e. the post data sent to server is like following:
values[name]
values[description]
i.e. the above values are empty.
EDIT-2:
By logging on firephp, I have confirmed that the save_assignment PHP script is BEING EXECUTED. Thus ajax call is working fine but it is NOT passing the data correctly.
Try to use event.preventDefault() like,
$("#asgsave").on('click',function(e){
e.preventDefault();
save_assignment();
});
or use return false after ajax call like,
function save_assignment() {
//ajax code
return false;
}
you have to use callbacks in the success function, cause ajax is asynchronously
edit
have you already tried console.log('foo'); in your function? so you are able to test if the function is called ;)
edit 2
add the following line to your ajax options
dataType: "json"
You could just serialize your form values:
http://api.jquery.com/serialize/
However, looking over your code, I'll take a stab and guess that you are not getting and sending your values properly. Using jQuery, you grab a value from input like so:
$('#idofInput').val();
http://api.jquery.com/val/
You are doing: $('#asgname').text()
Format your data properly: data : { foo : 'bar', bar : 'foo' }
One last guess, make sure your CodeIgniter config has CSRF protection disabled, otherwise you would need to pass: $this->security->get_csrf_token_name() & $this->security->get_csrf_hash();

Categories

Resources