How to prevent jQuery ajax submit form on page - javascript

I have two ajax calls on a page. There are text inputs for searching or for returning a result.
The page has several non ajax inputs and the ajax text input is within this . Whenever I hit enter -- to return the ajax call the form submits and refreshes the page prematurely. How do I prevent the ajax from submitting the form when enter is pressed on these inputs? It should just get the results.
However, I cannot do the jquery key press because it needs to run the ajax even if the user tabs to another field. Basically I need this to not submit the full form on the page before the user can even get the ajax results. I read return false would fix this but it has not.
Here is the javascript:
<script type="text/javascript">
$(function() {
$("[id^='product-search']").change(function() {
var myClass = $(this).attr("class");
// getting the value that user typed
var searchString = $("#product-search" + myClass).val();
// forming the queryString
var data = 'productSearch='+ searchString + '&formID=' + myClass;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/product_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results" + myClass).html('');
$("#searchresults" + myClass).show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results" + myClass).show();
$("#results" + myClass).append(html);
}
});
}
return false;
});
$("[id^='inventory-ESN-']").change(function() {
var arr = [<?php
$j = 1;
foreach($checkESNArray as $value){
echo "'$value'";
if(count($checkESNArray) != $j)
echo ", ";
$j++;
}
?>];
var carrier = $(this).attr("class");
var idVersion = $(this).attr("id");
if($.inArray(carrier,arr) > -1) {
// getting the value that user typed
var checkESN = $("#inventory-ESN-" + idVersion).val();
// forming the queryString
var data = 'checkESN='+ checkESN + '&carrier=' + carrier;
// if checkESN is not empty
if(checkESN) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/checkESN.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#esnResults" + idVersion).html('');
},
success: function(html){ // this happens after we get results
$("#esnResults" + idVersion).show();
$("#esnResults" + idVersion).append(html);
}
});
}
}
return false;
});
});
</script>

I would suggest you to bind that ajax call to the submit event of the form and return false at the end, this will prevent triggering default submit function by the browser and only your ajax call will be executed.
UPDATE
I don't know the structure of your HTML, so I will add just a dummy example to make it clear. Let's say we have some form (I guess you have such a form, which submission you tries to prevent)
HTML:
<form id="myForm">
<input id="searchQuery" name="search" />
</form>
JavaScript:
$("#myForm").submit({
// this will preform necessary ajax call and other stuff
productSearch(); // I would suggest also to remove that functionality from
// change event listener and make a separate function to avoid duplicating code
return false;
});
this code will run every time when the form is trying to be submitted (especially when user hits Enter key in the input), will perform necessary ajax call and will return false preventing in that way the for submission.

Related

How to pass javascript variable in .html() to php

I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;

Adding to JSON array by HTML button

I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.

On ajax response return false doesn't work and form doesn't cancel submit

I am facing issue, i f i am using ajax call, the return false not working..
and form submitted sucessfully.. I want that when i get response 1 form don't submit.. but on ajax request response form still submitting please help me..
here is code:
<form action="<?php echo base_url(); ?>do/add/review" method="post" name="dologin" id="dologinsubmitreview" onSubmit="return showpopupbox();">
function showpopupbox(){
var strs = $("form").serialize();
var autocompleteURL = "<?php echo base_url(); ?>grahak/save_record_session?rnd=" + Math.random() +"&sessiondata="+ $("form").serialize();
$.ajax({
url : autocompleteURL,
async: false,
cache: false,
method : "POST",
success : function(respd)
{
if(respd == 1){
$("#classiconpopupbx").show();
return false;
}
else {
return true;
}
}
});
}
You need to redesign your flow. Javascript is asynchronous, which means that the form is submitted LONG before the AJAX call is complete.
Instead, use jQuery on to bind to the event, capture the event in the function, and run event.preventDefault() immediately which will stop the form from submitting. THEN run your AJAX call.
In your AJAX success function, you'll need to decide what to do when it comes back "truthy". Without knowing more about your desired outcome, it's impossible to advise how to handle that piece.
<!-- remove the inline onsubmit script handler -->
<form action="<?php echo base_url(); ?>do/add/review" method="post" name="dologin" id="dologinsubmitreview">
// no-conflict safe document ready
jQuery(function($) {
// Bind to the form submit here, and call event.preventDefault immediately
$('#dologinsubmitreview').on('submit', function(event) {
event.preventDefault();
showPopUpBox(event);
}
function showpopupbox() {
var strs = $("form").serialize();
var autocompleteURL = "<?php echo base_url(); ?>grahak/save_record_session?rnd=" + Math.random() +"&sessiondata="+ $("form").serialize();
$.ajax({
url : autocompleteURL,
async: false,
cache: false,
method : "POST",
success : function(respd) {
if(respd == 1){
$("#classiconpopupbx").show();
} else {
// Do what you need to do here if the AJAX is true
}
}
});
}
});
One way you can do this is to prevent the submit, always, then if your Ajax call returns true, post the form (and tell the code to allow it this time):
For starters, don't mix inline event handlers with jQuery. The jQuery way is better:
// Start by not allowing submit
var allowSubmit = false;
$('form').submit(function(){
var $form = $(this);
// Only run the ajax if this is not a "real" submit
if (!allowSubmit){
// do the ajax call
$.ajax({
url: ...
success: function(respd){
if(respd == 1){
$("#classiconpopupbx").show();
}
else {
allowSubmit = true;
$form[0].submit(); // important - bypass jQuery event handler
}
}
});
}
// Conditionally allow the form to submit
return allowSubmit;
});

jQuery grabbing wrong form when using ajax

I have a php function that loops thru matches in a database, inside the loop, there is a form that gets returned to the page where the function is called:
while($row=mysql_fetch_array($get_unconfirmed))
{
echo "<form name='confirm_appointment' method='post' class='confirm_appointment'>";
echo "<input type='hidden' name='app_id' value='$appointment_id'>";
echo "<input type='hidden' name='clinic_id' value='$clinic_id'>";
echo "<td><input type='submit' class='update_appointment_button' value='$appointment_id'></td>";
echo "</form>";
}
Then I have jQuery to submit the form:
$( document ).ready(function() {
$(".update_appointment_button").click(function(){
var url = "ajax/update_appointment_status.php";
$.ajax({
type: "POST",
url: url,
data: $(".confirm_appointment").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
But the issue is, the way its set up, no matter what row I push "submit" for - I always get the values from the last row (form).
So I know the issue, I am not telling jQuery to get the values from the form with the button thats pushed. I need to somehow use .this maybe, but just cant seem to figure out the correct syntax.
Any help would be appricated!
You can access its parent form like this
data: $(this).closest(".confirm_appointment").serialize(),
or something like this
data: $this.parent().parent().serialize(),
Another way: replace the button click event by the form submit event.
$(document).ready(function () {
$('.confirm_appointment').submit(function (e) {
e.preventDefault();
var url = "ajax/update_appointment_status.php";
var serialized = $(this).serialize();
$.ajax({
type: "POST",
url: url,
data: serialized,
success: function (data) {
alert(data); // show response from the php script.
}
});
});
});
JSFiddle demo

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Categories