i have designed a search form. i want to select the destination using ajax, php and mysql. What happens is when i select the value from the first text box using the list fetched from database using ajax; that option gets selected for another text box as well.
Here's my code for ajax:
$(document).ready(function(){
$('#location').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#countryList').fadeIn();
$('#countryList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#location').val($(this).text());
$('#countryList').fadeOut();
});
ajax for another destination input:
$('#des').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search2.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#destinationList').fadeIn();
$('#destinationList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#des').val($(this).text());
$('#destinationList').fadeOut();
});
//Form:
<form>
<br>
<div class="row">
<div class="form-group col-sm-5">
<label for="usr">From</label>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-globe"></i></span>
<input id="location" type="text" class="form-control" name="loc" placeholder="Location">
</div>
<div id="countryList"></div>
</div>
<div class="col-sm-2">
</div>
<div class="form-group col-sm-5">
<label for="usr">To</label>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-globe"></i></span>
<input id="des" type="text" class="form-control" name="des" placeholder="Destination">
</div>
<div id="destinationList"></div>
</div>
</div>
Related
As from the title, I want to submit a form by click a span element. I also want to prevent the page from refreshing. I also want to add normal submit button for mobile view. But on submit won't work unless I directly submit the form. Is there a way to submit the form with ajax when I hit the span element? I also know that having submit elemnt in form might give trouble to sending data to php. So, is there a way to resolve this?
My code -
HTML
<div class="row">
<div class="col">
<form action="" class="w-50 m-lg-0 m-auto" id="contactForm">
<label for="name" class="change text-white minor- text-white change font mb-2">Your Name</label>
<input type="text" name="name" class="form text-white change bg-color" id="name" required><br>
<label for="email" class="change text-white minor-font text-white change mb-2">Email</label>
<input type="email" name="email" class="form text-white change bg-color" id="email" required><br>
<label for="subject"class="change text-white minor-font text-white change mb-2">Subject</label>
<textarea class="form bg-color text-white change" name="subject" id="subject" required></textarea>
<input type="submit" class="btn btn-outline-light title-font mt-5 w-75 m-auto m-lg-0 mt-lg-5 d-block" id="send" value="Send">
</form>
</div>
<div class="col-12 col-md 6 col-lg-4 d-xl-block d-none">
<div class="parent">
<img src="photos/cloud.png" alt="cloud" class="cloud" width="700px">
<span class="change text-white fs-1 pos" id="paper">
<i class="fa-regular fa-paper-plane"></i>
</span>
</div>
</div>
</div>
Jquery
$("#paper").on("click", function () {
$("#contactForm").validate();
console.log("good")
$("#contactForm").on("submit", function (e) {
e.preventDefault();
var dataString = $(this).serialize();
console.log("nice")
$.ajax({
type: "POST",
url: "_actions/sendmail.php",
data: dataString,
success: function () {
console.log("best")
$("#paper").addClass("posRun");
}
});
return false;
});
});
Never add additional events inside other event callback!
You should just trigger form submunition on click, not add event:
$(document).on("click", "#paper", function () {
$("#contactForm").validate({
submitHandler: function(form) {
console.log("good");
form.submit();
}
});
});
$(document).on("submit", "#contactForm", function (e) {
e.preventDefault();
var dataString = $(this).serialize();
console.log("nice")
$.ajax({
type: "POST",
url: "_actions/sendmail.php",
data: dataString,
success: function () {
console.log("best")
$("#paper").addClass("posRun");
}
});
return false;
});
I have a modal for entering user information. A user should be linked to a building. After user information has been entered and submit button has been clicked, I am preventing the default action and am overlaying/showing a building modal over the user modal.
Code for doing so follows.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
}
});
$('#modalConnectBuilding').modal('show');
});
})(window.jQuery);
console.log() logs the input information correctly, however in 'modalConnectBuilding.php' the following does not work:
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
?>
Producing the following errors:
Undefined index: name_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: address_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: city_user in
C:\laragon\www\modals\modalConnectBuilding.php
My intent is to do a classic 'form action="./php/processConnectBuilding.php" method="post"' but would need access to the three undefined variables as seen above. Adding users and buildings works in isolation but not when connected in this way. Any help would be greatly appreciated and if you need any more info, please ask. Thank you!
Code for the form (within the modal) I'm submitting follows (please note, default action is being suppressed by preventDefault() so action attribute is never "called", also the form for connecting a building is basically the same, but the action attribute is not suppressed):
<form role="form" id="formAddUser" action="./php/processAddUser.php" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form role="form" id="formAddUser" action="" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
</body>
</html>
<script>
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: 'tariffdetaildata.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function(data) {
alert(data)
}
});
});
</script>
tariffdetaildata.php
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
Try this way I think you need to open the modal popup once you get the response back from the ajax.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
$('#modalConnectBuilding').modal('show');
$("#modalConnectBuilding .modal-body #name_user").val( name_user);
$("#modalConnectBuilding .modal-body #address_user").val( address_user);
$("#modalConnectBuilding .modal-body #city_user").val( city_user);
}
});
});
})(window.jQuery);
I am using php mysql to insert to the database and that was working, however the bootstrap modal won't let me submitting another item. The button still says inserting and the last inserted data is still showing in the inputs.
I want to insert multiple times as this becomes part of a larger edit form.
This is put outside of the edit form submit button:
<div id="add_data_Modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add A New Item</h4>
</div>
<div class="modal-body">
<form method="post" id="insert_form">
<input type="hidden" name="job_id" id="job_id" value="<?php echo $job_id;?>">
<input type="hidden" class="form-control" id="job_mat_qty" name="job_mat_qty" value="1" />
<div class="form-group">
<label for="job_mat_desc" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea class="form-control editors" id="job_mat_desc" name="job_mat_desc" autocomplete="off" placeholder="Enter item title and / or description" />
</textarea>
</div>
</div>
<div class="form-group">
<label for="job_mat_cost" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<div class="input-group input-group"> <span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" class="form-control calculate invoice_product_price txt" autocomplete="off" id="job_mat_cost" name="job_mat_cost" aria-describedby="sizing-addon1" placeholder="0.00" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-10"> </div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" name="insert" id="selected" value="Insert" class="btn btn-success" />
</div>
</form>
</div>
</div>
</div>
$(document).on('click', '.delete-rows', function(){
var id = $(this).attr("id");
if (confirm("Are you sure you want to delete this Item?")) {
$.ajax({
type: "POST",
url: "job_remove_material_new.php",
data: ({
id: id
}),
cache: false,
success: function(html) {
$(".delete_mem" + id).fadeOut('slow');
}
});
} else {
return false;
}
});
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
$(function () {
$(document).on("hidden.bs.modal", "#add_data_Modal", function () {
$('#insert_form')[0].reset();
});
});
}
});
Sorry I have no clue how to add this code correctly for this forum so please be kind....
Thanks
You should try like this
$('#insert_form').on("submit", function(event){
event.preventDefault();
if($('#job_mat_desc').val() == "")
{
alert("Description is required");
}
else
{
$.ajax({
url:"add_material.php",
method:"POST",
data:$('#insert_form').serialize(),
cache: false,
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
//$('#insert_form')[0].reset();
$('#insert_form input[type="text"],textarea').val(''); // here is change
$('#add_data_Modal').modal('hide');
$('#invoice_table').html(data);
}
});
In my case it will work successfully so I hope it will help you
After posting data I can't see the success message in safari browser because page is refreshing after submitting the data. Other browsers shows the success message they are not refreshing. Please find the below code and help me to find out the issue?
HTML
<form action="" method="post" id="form-add-vehicleDetails">
<ol style="visibility:hidden;"></ol>
<div id="successvehicleadded"></div>
<div class="addvehicledetailsform">
<div id="validatevehicledetails"></div>
<div class="form-group form-group-default required">
<label for="Producer">Producer</label>
<input type="text" name="producer" id="producer" class="form-control" maxlength="100" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="Model">Model</label>
<input type="text" name="model" id="model" class="form-control" maxlength="100" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="Motor">Motor</label>
<input type="text" name="motor" id="motor" class="form-control" maxlength="100" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="LicensePlate">License Plate</label>
<input type="text" name="licenseplate" id="licenseplate" class="form-control" maxlength="20" autocomplete = "off" >
</div>
<div class="form-group form-group-default required">
<label for="Freetext">Freetext</label>
<textarea class="form-control" rows="9" id="freetext" name="freetext"></textarea>
</div>
<div class="modal-footer">
<input type="hidden" name="_token" value="{!! csrf_token() !!}">
<button class="btn btn-primary btn-cons m-b-10" type="button" id="addvehicle">Add Vehicle Details</button>
</input>
</div>
</div>
</form>
js
$(document).ready(function(){
$('[data-toggle="modal"]').click(function() {
var id = $(this).attr('data-id');
$("#addvehicle").click(function(e){
e.preventDefault();
var producer = $('#producer').val();
var model = $('#model').val();
var motor = $('#motor').val();
var licenseplate = $('#licenseplate').val();
var freetext = $('textarea#freetext').val();
var token = $('input[name=_token]').val();
var addvehicle = $('#addvehicle').val();
var dataString = 'producer='+producer+'&model='+model+'&motor='+motor+'&licenseplate='+licenseplate+'&freetext='+freetext+'&token='+token+'&addvehicle='+addvehicle+'&id='+id;
$.ajax({
type: "post",
url: "{!! URL::to('socialaddvehicle') !!}",
data: dataString,
success: function(data) {
//alert(data);
//$('.addvehicledetailsform').fadeOut('slow'); //hiding form
var successContent = '<div class="alert alert alert-success" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span></button><strong>Well done!</strong> Vehicle added successfully.</div>';
$('#successvehicleadded').html(successContent);
},
error: function(data) {
if( data.status === 422 ) {
//process validation errors here.
var errors = data.responseJSON;
errorsHtml = '<div class="alert alert-danger"><ul>';
$.each( errors , function( key, value ) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul></div>';
$( '#validatevehicledetails' ).html( errorsHtml );
}
}
});
return false;
});
});
});
Remove the action attribute and add onsubmit="return false;" to your form.
This should fix Opera trying to send the form.
This should do the trick.
$('#form-add-vehicleDetails').on('submit', function(e){
return false;
});
This do two things in to the submit event, fired after send the form.
Cancel the default event. e.prventDefault();
And stops the propagation prevent the event from bubbling up. e.stopPropagation()
As karim79 explains in his answer.
I got an ajax issue I can't get my head around. I'm using a ajax post method to send an email. But everytime I send one the post happens 2 times. I've tried adding preventDefault and stopPropagation but it doesn't seem to do the trick.
Jquery
$(document).ready(function()
{
$("#submit_btn").click(function(event)
{
event.preventDefault();
event.stopPropagation();
var proceed = true;
var submit = $('#submit_btn');
$("#contact_form input, #contact_form textarea").each(function () {
$(this).closest("div").removeClass('has-error');
if(!$.trim($(this).val())) {
$(this).closest("div").addClass('has-error');
proceed = false;
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).closest("div").addClass('has-error');
proceed = false;
}
});
if(proceed){
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'subject' : $('select[name=subject]').val(),
'msg' : $('textarea[name=message]').val()
};
$.ajax({
type: 'POST',
url: "./mail.php",
data: post_data,
beforeSend: function() {
submit.html('Sending...');
},
success: function(data){
output = '<div class="alert alert-success" role="alert">Hi ' + $('input[name=name]').val() + ' Thank you for your email</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
},
error: function(){
output = '<div class="alert alert-danger" role="alert">Something went wrong. Please try again</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
}
});
return false;
}
else{
output = '<div class="alert alert-danger" role="alert">Please fill in the required fields so I can get back to you !</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
}
});
$("#contact_form input, #contact_form textarea").keyup(function() {
$(this).closest("div").removeClass('has-error');
$("#contact_form").find("#contact_results").slideUp();
});
});
HTML
<div class="clear" id="contact">
<h3>Contact Me</h3>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" id="contact_form" action="">
<div class="form-group">
<label for="name">Name</label><input name="name" type="text" placeholder="Name" class="form-control" id="name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" placeholder="E-Mail" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="subject">Subject</label>
<select name="subject" class="form-control" id="subject">
<option value="General Question">General Question</option>
<option value="Hire me!">Hire me !</option>
<option value="Partner with me!">Partner with me !</option>
</select>
</div>
<div class="form-group">
<label for="message">Message</label><textarea name="message" placeholder="Message" id="message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Send</button>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
If someone could point me in the right direction that would be much appreciated.
Try changing $("#submit_btn").click(function(event) to $("#submit_btn").one('click',function(event)
If that doesn't work, check that the JS is not being loaded twice