Using ajax to pass text to a db - ajax

I am trying to take simple text from a form, pass it to my controller via ajax, and have that send to the data base.
View
<form method="POST">
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="rate" type="submit">
</form>
<script type = "text/javascript">
$(function(){
$("#rate").click(function(){
dataString = $("#email").serialize();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>index.php/trial/insert_into_db",
data: dataString,
});
});
});
</script>
The controller code and the model code work fine. I am almost sure that it is the ajax code that is not working.
Any information would be greatly appreciated!
Thank you.

One thing missing from your posted code is disabling the default form submission. There still could be other issues.
You don't specify an action so by default the action is the same url as the page.
<form method="POST">
You are doing AJAX but you have not disabled the default behavior with return false or event.preventDefault
$("form").submit(function(event) {
event.preventDefault();
// or
return false;
});
I prefer preventDefault() but the point is you need to prevent the default browser behavior.
Edit: This is how I would submit the form with AJAX.
If you had more than one form button to consider then
$("form").submit(function(e) {
e.preventDefault();
});
$("#rate").click(function(e) {
$.ajax({ ... });
});
But it's (marginally) easier to do it with one handler. I'd also stick the action on the form so the form still submits to the correct url if the javascript failed.
<form id="myform" action="<?php echo base_url();?>index.php/trial/insert_into_db" method="post">
Instead of handling the button click handle the form submission
$("#myform").on("submit", function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.ajax({
type = "post",
url = $(this).attr("action"),
data = formData
})
.done(function(result) {
// do something with the response
});
});

Related

YA Submitting Multiple Forms with AJAX Post

I searched high & low, found a ton of near hits, and yet still searching for an answer.
Consider basic scenario:
<form id="id1" onsubmit="return submit_add2cart();" >
<script>
function submit_add2cart() {
$.ajax
({
type:'POST',
url: 'ajax.pl',
data:$('id1').serialize(),
success: function(response) {
alert(response);
}}
);
return false;
}
</script>
Now, let's say I have multiple forms on same page that want to call same submit_add2cart() function; submit_add2cart() should only process calling form.
<form id="id1" onsubmit="return submit_add2cart();" >
<form id="id2" onsubmit="return submit_add2cart();" >
<form id="id3" onsubmit="return submit_add2cart();" >
What would the code look like for submit_add2cart()?
Thank you,
Michael
Add forms with action attribute, which is compulsory and add a class, say ajax-submit:
<form id="id1" action="ajax.pl" class="ajax-submit">
<form id="id2" action="ajax.pl" class="ajax-submit">
<form id="id3" action="ajax.pl" class="ajax-submit">
Now, using jQuery's unobtrusive method to bind the submit action:
$(function () {
$(".ajax-submit").submit(function () {
$.post($(this).attr("action"), $(this).serialize(), function (response) {
alert(response);
});
return false;
});
});
You don't need a separate function, or three different methods for it. Only the form that gets submitted will be submitted along its own data and not others'.

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

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.

jQuery Mobile avoid changePage() in ajax form submit

I have a post form, I want the submit to be done in an AJAX way but I don't want the page URL to change.
For example:
<form action="/countries/change_country" data-ajax="true" method="post">
<select name="country_code">
<option value="FR" selected="selected">France</option>
<option value="DE">Germany</option>
</select>
<input type="submit" value="change country" />
</form>
When I click in the change country button the form is sent through AJAX what is nice but the page URL is changed to /countries/change_country what is not nice because this URL doesn't exist in my server which is very picky with HTTP verbs.
I know it is possible to change this default behavior for the whole application but I would like to deactivate the changePage() only for this form.
Submit the form through Javascript/jQuery instead.
First: Disable the default submit-behaviour
$('#form').on('submit', function (e) {
if (e.preventDefault) e.preventDefault();
return false;
});
Second: Serialize the form data with jQuery
var serializedFormData = $('#form').serialize();
Third: Post your form with $.ajax();
$.ajax({
url: '/countries/change_country',
type: 'POST',
data: serializedFormData
});

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

Resources