I have a problem with a jQuery,the problem is when i do the submit, when i press the button, the website dosen't stay on the same html page but switch to the "insert.php" page, to avoid that in the script, as you can see I put a return false "$("#myForm").submit(function(){ return false;});" but that does not work.
Here it is the html form:
<form id="myForm" action="insert.php" method="post">
PERSONE:
<select id="persona" name="perselect">
<!-- these option come from the database by a jquery -->
<option value=""></option>
</select>
<br>
AUTO:
<select id="auto" name="autselect">
<!-- these option come from the database by a jquery -->
<option value=""></option>
</select>
<br><br>
INIZIO:<br>
Ora:
<select id="oraInizio" name="oraInizio">
<option value="00">00</option>
<!-- all the hours -->
<option value="23">23</option>
</select>
<br>
Minuto:
<select id="minutoInizio" name="minutoInizio">
<option value="00">00</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
</select>
<br>
Data:
<input type="Date" name="dataInizio"/><br>
<br><br>
FINE:<br>
Ora:
<select id="oraFine" name="oraFine">
<option value="00">00</option>
<!-- all the hours -->
<option value="23">23</option>
</select>
<br>
Minuto:
<select id="minutoFine" name="minutoFine">
<option value="00">00</option>
<option value="15">15</option>
<option value="30">30</option>
<option value="45">45</option>
</select>
<br>
Data:
<input type="Date" name="dataFine"/><br>
<br><br>
Note:<br>
<input type="text" name="note"><br>
<button id="sub">salva</button>
<!--<input type="submit"/>-->
<span id="result"></span>
And This is the script code:
$(document).ready(function(){
fetchData();
});
$("#sub").click(function(){
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"), data, function(info){
$("#result").html(info); });
});
$("#myForm").submit(function(){
return false;
});
function fetchData()
{
var personeOp;
$.getJSON("fetchPersona.php", function(data){
$.each(data.result, function(i,persona){
personeOp +="<option value='"
+persona.id+
"'>"
+persona.nome+" "+persona.cognome+
"</option>";
});
$('#persona').html(personeOp);
});
var autoOp;
$.getJSON("fetchAuto.php", function(data){
$.each(data.result, function(i,auto){
autoOp +="<option value='"
+auto.id+
"'>"
+auto.nome+
"</option>";
});
$('#auto').html(autoOp);
});
}
You are defining the submit handler inside a click handler, so it won't start listening for submit events until you've clicked once.
If you move this code:
$("#myForm").submit(function(){
return false;
});
...outside of the click handler, it should work.
I'd also recommend a slight change to how you do it:
$("#myForm").submit(function(e){
e.preventDefault();
});
Copy the callback function for the click in the callback function for the submit and add a preventDefault on event on the submit callback. Also, try to format your code before posting:
$("#myForm").submit(function(e){
e.preventDefault();
var data = $("#myForm :input").serializeArray();
$.post( $(this).attr("action"), data, function(info){
$("#result").html(info);
});
});
Related
I am a newbie with a localstorage issue. I have a few dependent dropdowns that are loaded via ajax from a server. When the user makes a selection the localstorage stores the wrong value...the last value. From my research I thought that .map() may be a solution to my problem but being a newbie I am not familiar with the syntax and I have not been able to get it to work. Can anyone figure out what is causing this problem? Is .map() the correct solution? Here is a photo of what I am having an issue with.
Here is the code
$('.country').on('change', function () {
var countryId = $(this).val();
var state_select = $(this).closest('form').find('.state');
var city_select = $(this).closest('form').find('.city');
if (countryId) {
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'ajaxData3.php',
data: {
country_id: countryId
},
success: function (r) {
console.log('States', r);
$(state_select).html('<option value="" selected="selected">State</option>');
$(city_select).html('<option value="" selected="selected">City </option>');
if (r.status) {
r.data.forEach(function (state) {
$(state_select).append(`<option value="${state.id}">${state.name}</option>`);
$('.state').each(function(r) {
var stateList = $(state);
var thisSelection = $(this);
var thisId = thisSelection.attr('id');
var storageId = 'state-' + thisId;
var storedInfo = JSON.parse(localStorage.getItem(storageId));
thisSelection.change(function(i) {
var selectedOptions = []; // create an array to hold all currently selected options
thisSelection.find('option:selected').each(function(i) {
var thisOption = $(this);
selectedOptions.push(thisOption.val());
});
localStorage.setItem(storageId, JSON.stringify(state.name));
})
})
})
} else {
$(state_select).html('<option value="" selected="selected">Unavailable </option>');
$(city_select).html('<option value="" selected="selected">Unavailable </option>');
}
}
})
};
Here is the markup
<form id="form1" autocomplete="off">
<select id="country1" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state1" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city1" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form2" autocomplete="off">
<select id="country2" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state2" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city2" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
<form id="form3" autocomplete="off">
<select id="country3" class="country" name="country">
<?php include("countryAjaxData.php"); ?>
</select>
<select id="state3" class="state" name="state">
<option value="" selected="selected">Select state</option>
</select>
<select id="city3" class="city" name="city">
<option value="" selected="selected">Select city</option>
</select>
</form>
I decided to post the answer so others can see. Hopefully someone here on stackoverflow will take the time to help me next time. This 'voting', 'points' and 'badge' thing gets in the way of actual learning.
The forEach() reiterates the function each time it is called. So the last entry will be where the reiteration completes. The localStorage.setItem needs to be moved into a .change() function or .on('change', function()) and the value needs to be .text() to simply read the text that was displayed.
localStorage.setItem('yourkeyhere', JSON.stringify($(this).text()));
I have a page that dynamically creates multiple forms and js code (20+). When the user selects an item from a select dropdown, (change trigger) it posts data to another script via ajax.
Form names are like: form1, form2, form3, etc.
Is there a way to specify which field input data to pass based on which select was changed?
For example, with: adId: $('input[name$="ad_id"]').val()
Need to specify which form to select from to obtain the desired data.
If changeCat2 select changed, pass the ad_id value from that specific form (form2).
EDIT - More code:
<script type="text/javascript">
$(document).ready(function() {
$('select.changeCat2').change(function(){
$.ajax({
type: 'POST',
url: 'cat_update.php',
data: {selectFieldValue: $('changeCat').val(), mlsId: $('input[name$="mls_id"]').val(), adId: $('input[name$="ad_id"]').val(), imageId: $('input[name$="image_id"]').val(), photoUrl: $('input[name$="photo_url"]').val()},
dataType: 'html'
});
});
});
</script>
<form method="post" action="" name="form2">
<input type="hidden" name="mls_id" value="W7631557">
<input type="hidden" name="ad_id" value="107">
<select name="changeCat2">
<option value="Living Room">Living Room</option>
<option value="Dining Room">Dining Room</option>
<option value="Family Room">Family Room</option>
<option value="Den/Office">Den/Office</option>
<option value="Kitchen">Kitchen</option>
<option value="Exterior">Exterior</option>
<option value="Bedrooms">Bedrooms</option>
<option value="Bathrooms">Bathrooms</option>
<option value="Pool/Patio">Pool/Patio</option>
<option value="Great Room">Great Room</option>
<option value="Balcony/Porch/Lanai">Balcony/Porch/Lanai</option>
</select>
<input type="hidden" name="image_id" value="2">
<input type="hidden" name="photo_url" value="http://myimages/">
</form>
It's hard to tell exactly what you want from the question, but the answer is yes, you can micromanage the data you send with your ajax call in whatever way you want.
The recipient of the ajax call may expect certain data, but that's out of the scope of the question. The example below should give you an idea of how to do any manipulations you want.
$(document).ready(function() {
$('select[name="changeCat2"]').change(function(){
// stop here - you can define your own data,
// and access whatever you need from the current state of the form
var myData = { // start with what you need for sure
'mls_id': $('input[name="mls_id"]').val(),
};
var category = $('select[name="changeCat2"]').val();
// optionally add some data
if (category === 'Living Room') {
myData['changeCat2'] = category;
myData['ad_id'] = $('input[name="ad_id"').val();
}
console.log(myData);
return; // just for this example so the ajax doesn't really run
$.ajax({
type: 'POST',
url: 'cat_update.php',
data: myData, // only the data you chose to include
dataType: 'html'
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" name="form2">
<input type="hidden" name="mls_id" value="W7631557">
<input type="hidden" name="ad_id" value="107">
<select name="changeCat2">
<option value="Living Room">Living Room</option>
<option value="Dining Room">Dining Room</option>
<option value="Family Room">Family Room</option>
<option value="Den/Office">Den/Office</option>
<option value="Kitchen">Kitchen</option>
<option value="Exterior">Exterior</option>
<option value="Bedrooms">Bedrooms</option>
<option value="Bathrooms">Bathrooms</option>
<option value="Pool/Patio">Pool/Patio</option>
<option value="Great Room">Great Room</option>
<option value="Balcony/Porch/Lanai">Balcony/Porch/Lanai</option>
</select>
<input type="hidden" name="image_id" value="2">
<input type="hidden" name="photo_url" value="http://myimages/">
</form>
I'm trying to send data from a HTML select to a PHP file using jQuery. Unfortunately it does not work. I have looked at all the solutions proposed here and it's still not working. Here is the code:
<select id="city" name="city" >
<optgroup label="Popular Cities">
<option selected style="display:none;color:#eee;">Entire country</option>
<option value="city1">city 1</option>
<option value="city2">city 2</option>
<option value="city3">city3</option>
<option value="city4">city4</option>
<option value="city5">city5</option>
</select>
$("#city").change(function() {
$.ajax({
url: 'post.php',
type: 'POST',
data: { city: $(this).val() },
success: function(data) {
alert(data);
window.location.replace("post.php");
window.location.reload("post.php");
}
});
});
$city = isset($_POST['city']) ? $_POST['city'] : false;
echo "".$city."";
The alert() works but I still have no data received in post.php. I have tried with the code below as well but still can't have it.
$.post("post.php", { city: $(this).value }, function(data) {
alert(data);
window.location.reload("post.php");
window.location.replace("post.php");
});
Any help?
You need to use form for this as said in comments
<form action="post.php" method="get" id="frmForm">
<select id="city" name="city" >
<optgroup label="Popular Cities">
<option selected style="display:none;color:#eee;">Entire country</option>
<option value="city1">city 1</option>
<option value="city2">city 2</option>
<option value="city3">city3</option>
<option value="city4">city4</option>
<option value="city5">city5</option>
</select>
</form>
Then use jquery to submit form on city selection
$(document).ready(function() {
$("#city").change(function() {
$('#frmForm').submit();
});
Then you can find city name with $_GET['city'];
It's not how you're meant to use Ajax. What your PHP file should be doing would be to handle the data sent in the Ajax request, and return a content which will be handled by the Ajax success callback.
What you're trying to do here is to:
Post data to post.php, which is working fine,
Then, go on post.php, which doesn't have the data previously sent, since you're making a completly new HTTP request.
What you should be doing would be to submit the form when your select changes, which would redirect you to post.php using HTML, not JavaScript.
Maybe this suits what you want:
HTML file:
<form action="post.php" method="POST">
<select id="city" name="city" >
<optgroup label="Popular Cities">
<option selected style="display:none;color:#eee;">Entire country</option>
<option value="city1">city 1</option>
<option value="city2">city 2</option>
<option value="city3">city3</option>
<option value="city4">city4</option>
<option value="city5">city5</option>
</select>
</form>
Then in post.php have the same code as current.
I have a html form where a select field and input box exist and I am using 2 class for that which is work_phone_class and work_phone_class_input.
I am calling ajax by trigger a save button with a class when select field value is changed or any option selected AND again calling ajax when user complete typing on input box. So that I am using following jQuery code :
$(".work_phone_class").change(function() {
$(".save_phone_class").trigger('click');
});
$(".work_phone_class_input").change(function() {
$(".save_phone_class").trigger('click');
});
Now I want to trigger the save button with the class when select field value is selected AND user completed typing on input box.
Update :
Html form is look like this. I think I have to use $(this) but not sure.
<select class="work_phone_class">
<option value=""></option>
<option value="1"></option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1"></option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1"></option>
</select>
<input type="text" class="work_phone_class_input">
I am no so clear about your requirement.... but i think this will help you
$(".work_phone_class,.work_phone_class_input").change(function() {
$(".work_phone_class_input").each(function(){
if($(this).val() == ""){
//// Validation goes here for input
return false;
}
})
$(".work_phone_class").each(function(){
if($(this).val() == undefined){
//// Validation goes here for input
return false;
}
//// trigger your save button click here
})
});
please let me know if it helps by marking it as an answer
You just have to add a test before send your ajax..
UPDATE
$(".save_phone_class").click(function(){
var allFilled = true;
$(".work_phone_class").each(function(){
if($(this).val()=="")
allFilled =false;
});
$(".work_phone_class_input").each(function(){
if($(this).val()=="")
allFilled =false;
});
if(allFilled)
{
//AJAX
}
});
$(".work_phone_class_save").click(function(){
var allFilled=true;
$(".work_phone_class_input").each(function(){
if($(this).val()=="")
allFilled=false;
});
$(".work_phone_class").each(function(){
if($(this).val()=="")
allFilled=false;
});
if(allFilled)
{
alert("Ajax sent");
}
else
alert("All input are not filled");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="work_phone_class">
<option value=""></option>
<option value="1">1</option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1">1</option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1">1</option>
</select>
<input type="text" class="work_phone_class_input">
<button class="work_phone_class_save">Save</button>
How can I maintain the value of the form when I submit it?
<select name="Year">
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
</select>
<input type="submit" value="Filter"/>
If you use jquery (you tagged it): Submit your form via $.post to your php script. Something like
$("form").submit(function() {
$.post("URL/TO/FORM.PHP", $(this).serializeArray(), function(data) {
console.log(data);
});
return false;
});
So you submit your form to your script but the site don't refresh because you set the return to false. You can get the url to your script from your action="" like this
$("form").attr("action")
if you are using php then:
<select name="Year">
<option value="2013" <?php if($_REQUEST['Year']=='2013'){echo "selected"}?>>2013</option>
<option value="2014" <?php if($_REQUEST['Year']=='2014'){echo "selected"}?>>2014</option>
<option value="2015" <?php if($_REQUEST['Year']=='2015'){echo "selected"}?>>2015</option>
</select>
<input type="submit" value="Filter"/>