How to load and validate a form using jquery? - javascript

let's say I have 2 pages :
index.html with this code :
<!DOCTYPE html>
<html lang="fr">
<head>
<title>test formulaire</title>
</head>
<body>
<div id="formulaire">
</div>
<!-- /#formulaire -->
Montre le formulaire
<!-- jQuery -->
<script src="js/jquery.js"></script>
<script src="js/monscript.js"></script>
</body>
</html>
I have an other page that containts my form :
<form name="monformulaire" id="monformulaire" role="monformulaire">
<input type="text" name="montexte" id="montexte" value="" />
<button id="bouton" type="submit">Let's go man !</button>
</form>
I have a Jquery.js and a personnal script like this :
function montreformulaire() {
alert('ok charge formulaire');
$.get( "monformulaire.html", function( data ) {
var formData = $.parseHTML (data );
$( "#formulaire" ).html( formData );
});
$('monformulaire').submit(function(event) {
alert('formulaire envoyé !');
event.preventDefault();
/*
$.ajax({
type: 'POST',
url: 'ajoute.php',
data: $(this).serialize(),
success: function (data) {
alert($('form').serialize());
//showMsg(data);
showSupportPage(id);
},
cache: false
});
*/
});
$( "#montexte" ).val( 'toto' );
}
my problem is that when the form is submit I want to use a jquery submit function but it doesn't work.
I don't see why and how I could fix that.
Any idea is welcome :-)
Thanks,
Alex

Because you missed a # while passing the id on submit handler
$('#monformulaire').submit(function(event) {
// Your code here..
});
Other selector is
$('[name=monformulaire]').submit({
// Your code here..
});
Choose whichever suits you.

Very classic and common question. You make an ajax call to an element, but you do element.click(...) before it is fetched, thus before it actually exists.
Place the $('#monformulaire').submit(function (with a #, that you forgot) inside the ajax callback function, like this :
$.get( "monformulaire.html", function( data ) { // This is done FIRST
var formData = $.parseHTML (data );
$( "#formulaire" ).html( formData ); // this is done THIRD, #monformulaire now exists
$('#monformulaire').submit(function(event) {........}) // this is done FOURTH, accessing the element!
});
$('#monformulaire').submit(function(event) {........}) // This is done SECOND and won't do anything because #monformulaire doesn't exist yet
Welcome to the world of async languages :)

Your submit functions is not good. Do it like so:
$('[name=monformulaire]').submit();
or
$('[name=monformulaire]').submit(function(){
//Do your thing here
});

You have to use $('form[name="monformulaire"]').submit(...)

Related

Sending GET Request when Button is Clicked

I'm attempting to send a GET request as soon as a button is pressed. As I'm quite inexperienced with HTML and JQuery/Ajax, I'm a little bit confused as to how to do this. My code is as following
<div id = "Reset">
<!-- <form method="get"></form> -->
<!-- <form action="https://wt.ops/reset" method="get"> -->
<button>Reset</button>
<!-- </form> -->
</div>
<script>
$("Reset").ready(function(){
$( "#Reset" ).click(function(){});
$.get( "https://wt.ops/reset", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
})});
</script>
Currently what it's doing is that it just loads the JQuery scripts automatically when the page is reloaded. But when I click the button, it does nothing.
You should attach the click handler after the document is loaded.
$("document").ready(function(){
//.. click handler
});
Your $.get should be within the click handler.
$("#Reset").click(function(){
$.get( "https://wt.ops/reset", function( data ) {
$( ".result" ).html( data );
alert( "Load was performed." );
});
});
Few things you have to update
1. this is just to ask have you added the jquery script in head
2. You have to change the id from div to button tag or remain as it is
<div>
<!-- <form method="get"></form> -->
<!-- <form action="https://wt.ops/reset" method="get"> -->
<button id="Reset">Reset</button>
<!-- </form> -->
</div>
3. You have to update the script function to below function. I have only changed the url to check the data
$(document).ready(function () {
$("#Reset").click(function () {
$.get("https://jsonplaceholder.typicode.com/todos", function (data) {
console.log(data);
alert("Load was performed.");
})
});
});
I see you use Jquery.
<div id = "reset">
<button >Reset</button>
<span id='result'> data</span>
</div>
$().ready(function(){
$( "#reset" ).click(function(){
console.log('click')
getFileFromNet();
});
function getFileFromNet(){
$.get( "https://rickandmortyapi.com/api/character/2", function( data ) {
$( "#result" ).html( data );
alert( "Load was performed." );
})
}
});
https://jsfiddle.net/eaLjb1n5/
Maybe it help you
First, you add jQuery in your html file. We use ajax method for send request.
Here is my code
<div>
<button id="submit">Reset</button>
</div>
<script>
$(document).ready(function(){
$("#submit").on("click",function(event){
$.ajax({
url: "", //your url
method: "GET",
success: function(data){
console.log(data);
},
error: function(){
alert("error");
}
});
});
});
</script>
if you have form data then you can submit form like this
<form id="form">
<input name="name" type="text"/>
<button type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#form").on("submit",function(event){
event.preventDefault();
var f = $(this).serialize();
$.ajax({
url: "", //your url
method: "GET",
data: f,
success: function(data){
console.log(data);
},
error: function(){
alert("error");
}
});
});
});
</script>

Onclick event with PHP, ajax and jQuery not working

I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});

JQuery Ajax Uncaught Type error of Of Object

I am currently using JQuery BBQ Js plugin for ajaxified navigation of my website, while I am navigating the whole site with ajax, there's one link that would show me this error.
This is my markup
<ul>
<li><a id="thankyou" href="#views/thankyou.jsp">Ajaxified Thank You Message</a></li>
<li><a id="register" href="#views/ajaxvalidation.jsp">Ajaxified Register Register</a></li>
<li><a id="register" href="#views/othermessage.jsp">Ajaxified Other Message</a></li>
</ul>
All of those two links are working, but when I click the 2nd link and submit the form this error shows up when I click the other anchor tags.
Uncaught TypeError: Object function (e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")} has no method 'fragment'
That error was triggerd by this script.
$(function(){
var cache = {
'': $('.bbq-default')
};
$(window).bind( 'hashchange', function(e) {
var url = $.param.fragment();
$( 'a.bbq-current' ).removeClass( 'bbq-current' );
$( '.bbq-content' ).children( ':visible' ).hide();
url && $( 'a[href="#' + url + '"]' ).addClass( 'bbq-current' );
if ( cache[ url ] ) {
cache[ url ].show();
} else {
// Show "loading" content while AJAX content loads.
$( '.bbq-loading' ).show();
// Create container for this url's content and store a reference to it in
// the cache.
cache[ url ] = $( '<div class="bbq-item"/>' )
.appendTo( '.bbq-content' )
.load( url +"#content");//loads the content and get the div you want
}
})
$(window).trigger( 'hashchange' );
});
Specifically this line
var url = $.param.fragment();
What's causing that error?
Also this is what the second link looks like..
<!DOCTYPE HTML>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#content').on('submit','#result',function(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
//this is the php file that processes the data and send mail
url: "register.action",
type: "POST",
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
$('#content').html(html);
}
});
})
})
</script>
</head>
<body>
<h3>Simple Ajax Validation.</h3>
<div id="divErrors"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id = "content">
<s:form action="register" id="result">
<label>UserName</label>
<s:textfield name="userBean.username" />
<s:fielderror />
<input type ="submit" id = "result_0" value="AJAX Submit" />
<!-- Test if Even Outside the main page can access the other elements -->
</s:form>
</div>
</body>
</html>
I've found the solution, the Jquery-bbq js is not being included on the Ajaxvalidation.jsp, what I did was I have included the jquery-bbq.js and its AJAX request in another JS file and both imported them if the respective page made a request

Django button ajax click

I have some HTML that Django is rendering well. I'd like to click a button on the HTML and have that cause an event to fire in the view.
It doesn't look like the button is causing the post to fire. I'm not sure what I'm doing wrong.
This is my views.py code:
def log(request):
if not request.POST:
template = loader.get_template('log.html')
html = template.render(Context())
return HttpResponse(html)
print "Post"
This is my log.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
$("#update_log_button").bind("button", function(){
$.post("hello");
return false;
});
</script>
</head>
<body>
<p>
<span>SPHIINX Log</span>
</p>
<p>
<textarea cols="2" name="log" rows="25"></textarea>
<input id="update_log_button" name="update_log" type="button" value="Update Log"/>
</p>
</body>
</html>
Is there a reason Why you are not using the click event directly?
Try this:
<script type="text/javascript">
$(function(){
$("#update_log_button").click(function(){
$.post(
url : "/hello/",
dataType:"html",
success: function(data, status, xhr){
//do something with your data
}
);
return false;
});
});
</script>
If the button is dynamically created then you may want to use the bind function to attach click event handler to the element:
<script type="text/javascript">
$(function(){
$("#update_log_button").bind('click', function(){
$.post(
url : "/hello/",
dataType:"html",
success: function(data, status, xhr){
//do something with your data
}
);
return false;
});
});
</script>
Try this URL to include the JQuery library:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

How to put a jQuery code into one file which will be referenced by all pages?

I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.

Categories

Resources