How to add Validate() function? - javascript

I have this form:
<form method='post' id='registration'>
...
<input type='submit' value='Submit' />
</form>
And a script which send the form via POST:
<script>
$(document).ready(function(){
$( "#registration" ).submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var form = $(this);
var username = form.find( "input[name='username']" ).val();
var password = form.find( "input[name='password']" ).val();
var url = "action.php";
// Send the data using post
$.post( url, {
username: username,
password: password
});
});
});
</script>
I have written Validate() function also. Where is the right place to add it and how?

I'd personally do it right before the post.
if (validate()) {
$.post();
{
This requires your function validate() to return either false or true if the form is valid.

#Rebirth is quite right.
#Nikolay Tsonev, Why don't you put
var form = $(this);
var username = form.find( "input[name='username']" ).val();
var password = form.find( "input[name='password']" ).val();
var url = "action.php";
into your Validate() function.
and it would just go like directly like;
event.preventDefault();
if (validate()) {
$.post();
{

Related

How to call same ajax function on multiple pages with different url?

Hı gusy!
I am trying to drop ajax post function to one and use it on whole site with different url on each page.
This is my original function and how it works :
<button type="button"class="submit">send</button>
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
var form = $(this).closest('form');
$.ajax({
type:'POST',
url:'ActionPage.php',
data:form.serialize(),
success:function(vardata){
var json = JSON.parse(vardata);
if(json.status == 101){
alert(json.msg);
window.location.replace("/");
} else {
alert(json.msg);
console.log(json.msg);
}
}
});
});
});
Exp: I have multiple forms in some pages, so I need to use $(this).closest('form'); to post each form.
This is what I want to do, original function will be in scripts and included in page :
function ajaxLoader(url) {
var form = $(this).closest("form");
$.ajax({
type:"POST",
"url" : url,
data:form.serialize(),
success:function(vardata){
var json = JSON.parse(vardata);
if(json.status == 101){
alert(json.msg);
window.location.replace("/");
} else {
alert(json.msg);
console.log(json.msg);
}
}
});
}
And on the page I want to call it like this :
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
ajaxLoader("ActionPage.php", true);
});
});
I getting undefined message on all cases when I click send button, when I move $(this).closest("form"); to second function then I get undefined form error.
I have searched on site there are similar question but none of them has usefull answer. example : this one
$(this).closest("form"); does not resolve to the closest form element of the clicked button when inside your function `ajaxLoader'. Do a 'console.log( this )' in that function.
You can either inject the form directly into your function:
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
let form = $(this).closest("form");
ajaxLoader("ActionPage.php", form);
});
});
function ajaxLoader(url, form) {
...
}
Or you could use the action attribute of your form and hook to the submit event of the form directly:
$('form').on('submit', function( e ) {
e.preventDefault();
const $form = $(this);
const url = $form.attr('action');
const data = $form.serialize();
const method = $form.attr('method');
$.ajax({
url: url,
data: data,
success: function(response) {
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="actionpage.php" method="POST">
<button type="submit">
submit
</button>
</form>
How this is scoped is based on the context of how it is called. You can change what this is with call/apply/bind. Basic example below.
function ajaxLoader(url) {
console.log(this, url)
var form = $(this).closest("form");
console.log(form[0]);
}
$(document).ready(function (){
$('.submit').on("click", function(e){
e.preventDefault();
ajaxLoader.call(this, "ActionPage.php");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="foo">
<button class="submit">Click</button>
</form>

AJAX Multiple Forms With Same Submit/Click Function

I've got multiple forms (that are similar) that are passed using Ajax to appended a PHP page using this code below. However, when I click the first or second form, it only sends the data from the first form. Can I use just the one function on all forms, or is there a better way to go?
$('.col_1').click(function(){ // $('#col_1').on("click", function(){
var parent_id = $('input[name=parent_id]').val();
var child_id = $('input[name=child_id]').val(); ////
$.ajax({
type:"POST",
url: "array-2.php",
data:{parent_id: parent_id, child_id: child_id},
success: function(){
//do stuff after the AJAX calls successfully completes
}
}).done(function(data) {
$('body').append(data);
});
});
Here is the HTML I'm using.
<form name="col_1" id="columnA1" class="col_1"><div>Entrepreneur</div>
<input name="parent_id" type="hidden" id="parent_id" value="1234" />
<input name="child_id" type="hidden" id="child_id" value="abcd" />
</form>
<form name="col_1" id="columnA2" class="col_1"><div>Musician</div>
<input name="parent_id" type="hidden" id="parent_id" value="5678" />
<input name="child_id" type="hidden" id="child_id" value="efgh" />
</form>
I've seen similar threads using the submit functions but none with the click event. Thanks
You need to make your selector specific, what you have is too generic that it will select all the input[name=parent_id] and val() on the collection will return the value of the first item in the collection.
So change it to:
var $this = $(this),
parent_id = $this.find('input[name=parent_id]').val(),
child_id = $this.find('input[name=child_id]').val();
Also note that you may want to use submit event instead of click event. What you have is an event registered for the click event on the form which will keep invoking the event when you click anywhere inside the form(unless you really want to do so).
You can also use serializeObject. It will take care of all form fields:-
$.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;
};
and you can do:
$.ajax({
type:"POST",
url: "array-2.php",
data: $(this).serializeObject(), //This will give you the map
success: function(){
...
}
...
Demo
you should really be using the submit method and not click, your current code will fire every time the whole form is clicked on, it should look something like this:
$('.col_1').on('submit', function(e){ // fire on submit
var form = $(this);
var parent_id = form.find('input[name=parent_id]').val();
var child_id = form.find('input[name=child_id]').val();
$.ajax({
type:"POST",
url: "array-2.php",
data:{parent_id: parent_id, child_id: child_id}
}).done(function(data) {
$('body').append(data);
});
e.preventDefault();
});
Don't use the click on a form. It does not make any sense.
Just do this
<div class="col_1" data-parent_id="1234" data-child_id="abcd">Entrepeneur</div>
<div class="col_1" data-parent_id="5678" data-child_id="efgh">Musician</div>
using
$(function() {
$('.col_1').click(function(){
var parent_id = $(this).data("parent_id");
var child_id = $(this).data("child_id]");
$.post("array-2.php",{parent_id: parent_id, child_id: child_id},
function(data){
//do stuff after the AJAX calls successfully completes
$('body').append(data);
});
});
});

Hidden input text submit with jquery

I have a javascript var that returns the value of a input text ID "ven_prod", with the value of "ven_prod" I need to make a search in my database without submiting the page.
I can't use a javascript var in the java code, so i've setted the value in a hidden input text ID "prod_hidden", but I need to submit it to get the value with the java code and make the search...How do I do it ?
<input id="ven_prod" type="text" placeHolder="Código de Barras" autofocus>
<input id="prod_hidden" type="text" value="">
<script>
$('#ven_prod').keypress(function (e)
{
if(e.keyCode==13)
{
var table = document.getElementById('tbprodutos');
var tblBody = table.tBodies[0];
var newRow = tblBody.insertRow(-1);
var prod = document.getElementById('ven_prod').value;
var qtd = document.getElementById('ven_qtd');
var barra = prod.substring(0, 12);
var num = prod.substring(14, 16);
document.getElementById('prod_hidden').value = barra;
var ref = <%=pd.getProdutosBarra(request.getParameter("prod_hidden")).getPro_referencia()%>;
OR
var ref = <%=pd.getProdutosBarra(JS VAR 'barras HERE).getPro_referencia()%>;
if(prod.length==16) {
var newCell0 = newRow.insertCell(0);
newCell0.innerHTML = '<td>'+ref+'</td>';
var newCell1 = newRow.insertCell(1);
newCell1.innerHTML = '<td>'+num+'</td>';
var newCell2 = newRow.insertCell(2);
newCell2.innerHTML = '<td>'+qtd.value+'</td>';
var newCell3 = newRow.insertCell(3);
newCell3.innerHTML = '<td>R$ '+valor+'</td>';
var newCell4 = newRow.insertCell(4);
newCell4.innerHTML = '<td>'+barra+'</td>';
document.getElementById('ref').value = '6755';
document.getElementById('imgsrc').src = './?acao=Img&pro_id=1';
document.getElementById('valortotal').value = 'Testando novo valor';
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
} else {
document.getElementById('ven_prod').value = '';
document.getElementById('ven_qtd').value = '1';
alert("Código de barras inválido!");
}
return false;
}
});
</script>
you can make ajax call using jQuery as follows. will submit your form data as well along with hidden elements.
var form = jQuery("#YourFormID");
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data);
}
});
value of a input text named "pro_barras"
Are you sure? Look at this:
<input type="hidden" id="pro_barras">
its not the name of the input, its the ID. You can try using this:
<input type="hidden" name="pro_barras">
And now, you can use $.ajax to send the request to a new page, where you will request the data from the database. And then you'll write the response, and take it back on the first page.
What it will do depends on how you use it. I will try to ask you to simply use serialize() method by jQuery API, this will let you to create a simple URL param with the data from the form, use it as:
$.ajax({
var data = $('#formid').serialize(); // serialize the form..
url: "link/to/file.cshtml",
data: data,
success: function (datares) {
$('#resultid').html(datares); // write the result in the element
}
})
If you want to get only the value from that field you can use
var data = $('input[name=pro_barras]').val();
without submiting the page.
Your page will have to be submitted when you click on input type="submit" button. To prevent that you can use
$('#idofsubmitbutton').click(function () {
return false; // stop execution and stay on page..
}
Then the ajax will continue, other method is to remove the input type="submit" and use <button></button> which won't cause any submission.
get the value with the java code
This isn't java :) Its JavaScript, they are totally different. :)
a) You can use like that:
$("#pro_barras").bind("change paste keyup", function() {
//$('.someClass').submit();
$('#it_is_form_id').submit(); // it call form's submit function
});
The piece of code detected when input text change. To more info see also here If you want to customize form submit function
$('#it_is_form_id').bind("submit", function(){
//alert("submit");
// make here simple ajax query
return false; //<-- it is used so that default submit function doesn't work after above code.
});
Don't forget, all code will be inside
<script>
$(function() {
// your code must be here
});
</script>
b) If you don't want to use form, you can do like that:
<script>
$(function() {
$("#pro_barras").bind("change paste keyup", function() {
var text = $("#pro_barras").val();
$.ajax({
type: "POST",
url: "yourUrl",
data: text,
success: function(res){
console.log(res);
},
error: function(err){
console.log(err);
}
});
});
});
</script>
Making simple ajax query:
Using Jquery post method
https://stackoverflow.com/a/8567149/1746258
Pass entire form as data in jQuery Ajax function
You could also add a custom attribute to your input element (in Jquery):
<input type='text' id='pro_barras' customattr='myCustomInfo'/>
<script>
var customValue = $('#pro_barras').attr('mycustomvar');
alert(customValue);
</script>
Fiddle

remember password after jquery post

Here is code
<script type='text/javascript'>
$("#focusform").submit(function(event)
{
event.preventDefault();
var $form = $( this ),
usname = $form.find( 'input[name="name"]' ).val(),
uspass = $form.find( 'input[name="pass"]' ).val();
if($('#chk').is(':checked')) var checked='yes';
else var checked='no';
$.post("/login/submit/", { name: usname, pass: uspass, checkbox: checked, template_framed:"yes",submit: "yes" }, function(data)
{
if(data=='error'){
alert("You have made an error");
return false;
}
else{
if(checked=='yes')window.location='/usercookie/';
else window.location='/login/success/';
return true;
}
});
});
</script>
But browser doesn't want to promt whether save password or not. Cant't you help me?
I would do a pre check and use Ajax to check the is correct, this would then return the error or success message, if success continue to post the form otherwise display the error using Ajax
The browser won't offer to save passwords if your <form> doesn't have an action URL and doesn't have a submit button. Your password field must also be an <input type="password" />.
It doesn't work when you try to assign the submit function with jQuery in that way:
$("#focusform").submit( ...
However it does work if you add an onsubmit attribute to the form:
<form id="focusForm" action="page.php" method="post" onsubmit="return mySubmit()">
^^ here
And then return false in your submit function:
function mySubmit()
{
// do the jquery ajax or whatever you want to do here
return false;
}
<iframe id="temp" name="temp" src='/engine/blank.html' style="display:none"></iframe>
<form id='focusform' target='temp' method='post' onsubmit="return mySubmit()">
...
</form>
<script type='text/javascript'>
function mySubmit()
{
var $form = $("#focusform"),
usname = $form.find( 'input[name="name"]' ).val(),
uspass = $form.find( 'input[name="pass"]' ).val();
var checked = ($('#chk').is(':checked')?'yes':'no');
$.post("/login/submit/", { name: usname, pass: uspass, checkbox: checked, template_framed:"yes",submit: "yes" }, function(data)
{
if(data=='error'){
alert("<?=$lang['made_error']?>");
}
else{
alert("Loged in");
}
});
}
</script>
And it works :)

Jquery post method

I have a jquery post method that sends name , password and email to register.php
function postData()
{
thisBtn = $(this);
parent = $(this).parent();
name = parent.data('name');
password = parent.data('password');
email =parent.data('email');
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) ;
parent.next('#message').html(data);
}
The button that performs the function onclick:
<button onclick = 'postData()' class='regular' name='save'>
However nothing seems to be happening when the button is cicked
Since you call postData with no associated object, inside the function this is the same as window so none of the elements you access are the ones you expect.
Don't use intrinsic event attributes, bind your handlers using JavaScript. Since you are already using jQuery you should use the methods it provides for that.
This syntax looks mangled
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) ;
parent.next('#message').html(data);
// no {} for function, no closing ) for $post, and premature ;
Try
$.post('register.php', {name: (name), password: (password), email: (email)}, function(data) {
parent.next('#message').html(data);
});
you have 2 options ...
either pass and object in the onclick :
<button onclick='postData(this)' class='regular' name='save'>
or attach the click handler using jQuery - preferred method when using jQuery :
$('input[name="save"]').click(function() {
// your post code here
}};
there would then be no need for the onclick='postData(this)'
Send the post data like this you will get proper output
name = 'demo';
password = '123456';
email = 'demo#gmail.com';
$.post('register.php',{ 'name': name, 'password': password, 'email': email},function(html){
alert(html);
},"html");
//register.php
echo $_POST['name'];
Use jQuery to bind to the button click as well if you want things to work properly. (EDIT: also, let's use a non-deprecated element)
<input type='button' class='regular' name='save' id='btnPost' value='Post' />
Javascript:
$(document).ready(function() {
$("#btnPost").on("click", function() {
var thisBtn = $(this);
var parent = thisBtn.parent();
// Replacing this by serializing the parent form -
// not sure what parent.data is going to give without seeing the rest
// of the html
// name = parent.data('name');
// password = parent.data('password');
// email =parent.data('email');
$.post('register.php', thisBtn.closest("form").serialize(),
function(data) {
parent.next('#message').html(data);
});
});
});
});
You could try this :
$(document).ready(function(){
var $this = $('id_of_button');
$this.click(function(){
//ajax logic here
$.ajax({
type: 'POST',
url: url,
data: data,//data to send to serverside
success: success, //function to call on success
dataType: dataType//datatype eg.text,json etc.
});
});
});

Categories

Resources