Jquery .AJAX doesn't works on click event - ajax

I'm going to implement the following:
When user presses button AJAX query is performed to servlet. Depending on the request from server, I change label text.
web.xml
<servlet>
<servlet-name>RemindPassword</servlet-name>
<servlet-class>app.RemindPassword</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RemindPassword</servlet-name>
<url-pattern>/RemindPassword</url-pattern>
</servlet-mapping>
html code of button
<form>
<div class="field">
<label for="email">Your e-mail:</label>
<input name="email" type="text" class="t">
</div>
<input id ="btn" type="submit" value="Send" />
</form>
JS
<script type="text/javascript">
$(document).ready(function() {
$('#btn').click(function() {
$.ajax({
type: "GET",
url: "/RemindPassword",
//dataType:text,
//data: $("#registerSubmit").serialize(),
success: function(msg){
$('input[type="submit"]').after("<label for='submit'>" + msg+" " +"</label>");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('input[type="submit"]').after("<label for='submit'>" + fail+" " +"</label>");
}
});
});
});
Probably useful information:
I perform AJAX query from domain/someJSP/RemindPassword.
I put servlet in the root of my web app and intentionally put slash before URL in AJAX call. No success. When I used .get JQUERY function it worked when I call it on render bit didn't work when I put ajax call onclick. .ajax didn't work in both cases.

change ID selector, add prevent default and better handle the form submit instead of button click
$('#form1').click(function(e) {
e.preventDefault()
assuming that form tag will have ID=form1

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

Cross Domain Ajax Issue

I have two files
1) index.php(picks data from the code editor and submits for processing via Jquery Ajax to exec.php)
2) exec.php (currently just transfer the data it recieved via index.php using jsonp)
Code of index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function test() {
var code = document.getElementById('code').value;
var code_data = "code=" + code;
alert(code_data);
$.ajax({
type: "POST",
crossDomain: true,
url: "http://code1.guru99.com/exec.php",
data: code_data,
dataType: "jsonp",
success: function (data) {
alert(data);
}
});
alert("End of Test");
}
</script>
<form name="myform" id="myform" method="POST" class="code-box">
<textarea name="code" id="code"><?
$code='<?php
"Hello";
?>';
echo $code;
?>
</textarea> <!-- for add html tag in text area nad print the code-->
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="submit" value="Run" id="submit" onClick="test();"><!--<img id="ajax-loader" name="ajax-loader" src="/img/ajax-loader.gif" class="hidden" style="vertical-align:middle" />-->
</form>
<div name="label" id="label"> </div>
<div name="out" id="out"> </div>
Code of exec.php
<?php
$code=$_POST['code'];
$fp=fopen("file.txt","w"); // Storing the data into a file just to know that data is passed
fwrite($fp,$code);
fclose($fp);
header('Content-Type: application/jsonp');
echo $_GET['callback']."(".json_encode($code).");"
?>
The problem is data just does not pass into exec.php. I am not sure why...
The code is live at http://code.guru99.com/php/
Please help...
You cannot use AJAX to do this. Instead consider posting from a hidden Iframe using a regular FORM and setting the action to the URL you desire. You can still submit the form using JavaScript.
You can also listen to the onload event on the iframe to detect when your post has completed.
Alternately, you can use a server-side proxy.
The code syntax is correct.
May the problem could be with your server

sending values to database and return the results to same page with Ajax onclick

can one help on how can i submit the form to search page script on index page and return the results of search script on specific DIV id search_results we out going to the search.php or refresh the index page using AJAX onClick
Am not good in Ajax but i try my best to come out with the following code which does what am looking for but is loading the page we out clicking anything i need a user to trigger the event when he/she enters what they are looking for? Any answer or suggestion is greatly appreciate
<script language="javascript" src="js/jquery-8.js"></script>
<script language="javascript">
var grbData = $.ajax({
type : "GET",
url : "search_m.php",
data : "q=",
success: function (html) {
$("#more-info").html(html);
}
});
</script>
<div id="more-info"></div>
I wish the above code to use this following htm form
<form method="get" style="width:230px; margin:0 auto;" id="find">
<input type="image" src="images/searchthis.png" id="search_btn">
<input type="text" id="search_toggle" name="q" placeHolder="type to start searching">
</form>
Add a click event to the search_btn element.
$('#search_btn').click(function(e) {
e.preventDefault();
$.ajax({
type : "GET",
url : "search_m.php",
data : $('#search_toggle').val(),
success: function (html) {
$("#more-info").html(html);
}
});
HTH.

Barcode scanner and jquery ajax call?

I am stuck with the following: I have a simple form on index.phpwith one input field. On button click the form makes a jquery ajax request to lookup.php which returns some data. This data is shown on index.php. So far nothing special and it works when i use the keyboard.
Now when i use the barcode scanner it doesn't work, with some trial and error it looks like the barcode scanner uses the "submit" handler. But in my case the ajax request is handled by
$("#btnSubmit").on("click",
and button btnSubmit is of the type=button and not submit.
How can i fix this so the barcode scanner is also making the ajax request?
jquery submit with $.ajax doesn't seem to work
If you have a simple form like:
<div id="status"></div>
<form action="">
<input id="foo"/>
<input type="submit" value="Submit">
</form>
You can do:
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: "lookup.php",
type: "POST", // Can change this to get if required
data: { foo: $("#foo").val(); },
success: function(data) {
$("#status").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
$("#status").text(textStatus);
}
});
});

AJAX call then page redirect

I can call an AJAX request when a form submit button is clicked, but if the page reloads/redirects due to the form submission, will the AJAX request still complete? I'm asking this so I could do something like upload a file via AJAX as the form is submitted.
I'm pretty sure I can't get the output of the AJAX call, but could I be wrong?
It's possible, but there's no guarantee that the request would have completed by the time you leave the page. If you're submitting a form via AJAX and also want to submit a file, you might consider placing the file upload in a completely separate form tag, then trigger the form submission after the AJAX call is successful. For example:
<!-- First form with your data -->
<form action="/your/url/here" method="post" id="form1">
<input type="text" name="title" />
<input type="submit" value="Save" />
</form>
<!-- Second form with your file -->
<form action="/uploadfile" method="post" id="form2" enctype="multipart/form-data">
<input type="file" name="fileupload" />
</form>
Then in Javascript (using jQuery example for brevity, note I haven't tested this code at all):
$('#form1').bind('submit', function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: 'post',
success: function() {
$('#form2').submit();
}
});
return false;
});

Resources