how do I add an ajax response to my form without adding a new js file? - ajax

I have this simple submission form and I want to "ajaxify" it so the user isn't redirected to this page thanks.php after submission. I want the content from thanks.php to respond and show inside the div.
What jquery code will plug right into this to show the response.
<div ><form method="post" action="http://domain.com/thanks.php">
<input type="text" placeholder="Enter Email" name="email" id="email" >
<input type="submit" name="submit" value="Submit" ></form></div>

I would give 'form' and 'div' a class or id so it is not so generic, but this should work.
$("form").submit(function (){
$.ajax({
url: "http://{url}/thanks.php",
type: 'POST',
data: {email: $("#email").val()},
success: function ( data ) {
$("div").html(data);
}
});
return false;
});

Related

Play framework write Action with Ok(...) that doesn't load new page

Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps

Automate AJAXed forms with Jquery

I want to improve my website and figured out a good way to do it was by submitting forms via AJAX. But, I have so many forms that it would be inpractical to do $('#formx').submit(). I was wondering if there was a way to do this automatically by making an universal markup like;
<form class="ajax_form" meta-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
</form>
And have this submit to ajax/pagename.php, where it automatically includes inputx and inputy?
This would not only save me a lot of time but also a lot of lines of code to be written.
First question so I hope it's not a stupid one :)
Something like this should work for all forms. It uses jQuery - is this available in your project? This specific code chunk hasn't been tested per say, but I use this method all the time. It is a wonderful time saver. Notice I changed meta-submit to data-submit so that its value can be fetched using $('.elemenet_class').data('submit');
HTML
<!-- NOTE: All Form items must have a unique 'name' attribute -->
<form action="javascript:void(0);" class="ajax_form" data-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
<input type="submit" value="go" />
</form>
JavaScript
$('.ajax_form').submit(function(e){
var path = $(this).attr('data-submit'); //Path to Action
var data = $(this).serialize(); //Form Data
$.post(path, {data:data}, function(obj){
});
return false;
})
PHP
//DEBUGGING CODE
//var_dump($_POST);
//die(null);
$data = $_POST['data'];
$inputx = $data['inputx'];
$inputy = $data['inputy'];
you can create ajax fot text boxes so that it can update to database whenever change the focus from it.
<form id="ajax_form1">
<fieldset>
<input type="text" id="inputx" value="x_value" />
<input type="text" id="inputy" value="y_value" />
</fieldset>
</form>
<script>
$(document).ready(function()
{
$("form#ajax_form1").find(":input").change(function()
{
var field_name=$(this).attr("id");
var field_val=$(this).val();
var params ={ param1:field_name, param2:field_val };
$.ajax({ url: "ajax/pagename.php",
dataType: "json",
data: params,
success: setResult
});
});
});
</script>

How can Prevent Cross site request forgery via Ajax post?

I have a Form with AntiforgeryToken() value in Mvc project. while submiting the form, it validated with their corresponding controller Post action ValidateAntiforgeryToken in MvC project.
It goes to confirmation page. In the confirmation having two button which having hidden Form , this will go to same Post action in previous above.I have added Html.Antiforgerytoken() in that two hidden forms. while clicking the button, we don't need to Form Post[page reload], instead of this Using Ajax post.
I have tried using Ajax post (using Antiforgerytoken) but it does not hit Post action. Shows 404 error.
Can you please suggest how to enable AntiforgryToken using Ajax post? For that what type of code handle and where do it add?
Form details:
<form method="post" action="">
#Html.AntiForgeryToken()
<input type="hidden" name="Name" value="#downloadInfo.Name" />
<input type="hidden" name="Company" value="#downloadInfo.Company" />
<input type="hidden" name="Email" value="#downloadInfo.Email" />
<input type="hidden" name="Phone" value="#downloadInfo.Phone" />
</form>
Ajax Post:
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(Formdatas),
contentType: 'application/json; charset=utf-8',
beforeSend: showLoadingGraphic(id),
success: onSuccessfulPost
});
If you've received a 404 it's not from the token, you had an invalid URL or method.
You are including your token in your ajax form post, so look by using the tool Fiddler what URL is being requested and fix that first.
I'm guessing your Ajax call using 'URL' is incorrect
Try generating your form as it should (using the Html.BeginForm helper):
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" }))
{
#Html.AntiForgeryToken()
<input type="hidden" name="Name" value="#downloadInfo.Name" />
<input type="hidden" name="Company" value="#downloadInfo.Company" />
<input type="hidden" name="Email" value="#downloadInfo.Email" />
<input type="hidden" name="Phone" value="#downloadInfo.Phone" />
}
and then:
var myForm = $('#myForm');
$.ajax({
url: myForm.attr('action'),
type: myForm.attr('method'),
data: myForm.serialize(),
beforeSend: showLoadingGraphic(id),
success: onSuccessfulPost
});
Now the antiforgery token and the hidden fields will be properly sent to the server.

jQuery mobile, login page reload needed for ajax to work

I have a simple "login" form and ajax is working. But every time I load the page freshly in new tab, and "login" page loads, I input the username and password, press "login" button and for some reason page just reloads, but on the reloaded page when I press "login" button, ajax works just fine. Anyone know what does this mean?
Here is simple login form:
<form id="login_form" name="login_form" data-ajax="false">
<label for="basic">Username:</label>
<input type="text" name="usr" id="usr" value=""/>
<label for="basic">Password:</label>
<input type="password" name="psw" id="psw" value=""/>
<input type="submit" value="Login" id="login" name="login"/>
<label><input type="checkbox" name="remember_me" id="remember_me" value="checked_remember"/>Remember me!</label>
</form>
<div id="login_message"></div>
And here is my ajax script:
$(document).ready(function(){
$("#login").click(function(){
username=$("#usr").val();
password=$("#psw").val();
$.ajax({
type: "POST",
url: "http://imes.jzpersonal.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true')
{
$("#login_message").html("Logged in, congratulation.");
}
else
{
$("#login_message").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#login_message").html("Loading...")
}
});
return false;
});
});
Also I'm using POST method but I still get address in address bar like this:
http://imes.**********.com/login_page.php?usr=Jakub&psw=********&login=Login
Is this an jQueryMobile thing?
Reason for this is you cant use $(document).ready(function(){ with jQuery Mobile. You should use :
$(document).on('pageinit'){
});
or if your page has an id then use it like this:
$('#page_id').on('pageinit'){
});
More info about this problem can be found here: http://jquerymobile.com/test/docs/api/events.html
Read this article to find more about this and jQM page events: https://stackoverflow.com/a/14010308/1848600

Submitting form into a div

Can anyone tell me why this is not working or give me another way into doing what I want.
I have a form on a page when click submit I want it to process into add.php and for it to open up in a DIV called right.
Form page
<script>
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</head>
<body>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload">
</form>
</body>
Now if I add action to form to direct it to add.php all works fine so other script is ok yet when i do it this way,nothing happens it does not load add.php into the 'right' div like I want it to.
Anyone got any suggestions?
Your $("#Submit") selector does not match anything (the submit button has no id and is defined after that bind attempt), so the function is not bound to any event, thus never executed.
Instead the form acts the way it should: upon submit it posts its content to the url specified in the 'action' attribute. This is what happens, that div is never touched.
you have to go back to understand how jquery selectors work. How to bind a function to an event.
Is this your exact code? There are a few issues:
$("#Submit").click should be wrapped in a document ready
handler so it doesnt run before the page has actually loaded.
There is no button that matches #Submit
There is no div that matches #right
Try
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
</head>
<body>
<div id="right">
</div>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload" id="Submit">
</form>
you have to create on div in body tag which id will be right and
<input id="submit" type="submit" name="upload" >
add new div in body tag like this
<div id="right"></div>

Resources