Ajax form duplicating on submit - javascript

I have 3 selectboxes the value of each selectbox gets populated based on the selection of the selectbox before it:
selectbox1 =>populates => selectBox2 => populates selectBox 3:
Now when user clicks submit I want to use the values from the selectboxes to query my database
My Problem
When I click submit:
The Whole Form Gets Duplicated (see image below)
So in short the variables are being passed correctly to my php code but the form duplicates on submit...
Code for sending form data
I believe the problem is somewhere in this code
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {$('#resultForm').append(data); }
});
}
});
</script>
HTML
<form method="post" id="resultForm" name="resultForm">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
include('connect.php');
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>

You're appending the result.
If you don't want to duplicate then replace the new content with old one.
Just change this
success: function(data) {$('#resultForm').append(data); }
to
success: function(data) {$('#resultForm').replaceWith(data); }
or even
success: function(data) {$('#resultForm').html(data); }
See more details about replacewith here

Related

Splice method in codeigniter drop down

I have some locations that are stored in my database separated by a comma and I have a dropdown that gets that information. The user selects a location to populate another drop down based on this chosen location.
Here is my php code:
<label for="select-service">
<strong>Enter a Location:</strong>
</label>
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
?>
<option value="<?php echo $location->notes ?>"><?php echo $location->notes ?></option>
<?php
}
?>
</select>
Here is my javascript code:
$(document).ready(function() {
FrontendBook.initialize(true, GlobalVariables.manageMode);
GeneralFunctions.enableLanguageSelection($('#select-language'));
$('#select-provider').html('');
$('#select-location').change(function() {
$('#select-provider').html('');
var selected_location = $(this).val();
$.ajax({
url: '<?php echo site_url('appointments/getProviderByLocation'); ?>',
type: 'POST',
data: {
csrfToken: GlobalVariables.csrfToken,
'selected_location': selected_location,
},
dataType: 'json',
success: function(data) {
var options = '';
$.each(data, function(key,val) {
console.log(val.id);
options += '<option value="'+val.id+'">'+val.first_name+" " +val.last_name +'</option>'
});
$('#select-provider').html(options);
}
});
});
and here is a screenshot of the location how it is currently:
So what i want to achieve is to have Randburg as one option, Greenside as another option and Rosebank as another option.
You have different type string in your array so for this particular problem in your loop you should explode your string like this and another loop to print separated string
<select class="form-control" id="select-location" class="col-xs-12 col-sm-4 form-control" required>
<option value="">Select Location</option>
<?php
foreach($appointment_locations as $location) {
$LocationsArray = explode(",", $location->notes);
foreach($LocationsArray as $singleLocation):
?>
<option value="<?=$singleLocation ?>"><?=$singleLocation ?></option>
<? endforeach;
};?>

Editable select box do not get refresh on ajax call in Codeigniter

I am using editable select to show drop down list.Depend on search if values is not present in table which initially generates dropdown then I check if values are present in other table and if yes then I want to reload drop down with new values.
Select in view is
<select tabindex="2" id="port_of_loading" name="port_of_loading" onkeyup="port_search()">
<option value=""></option>
<?php if(!empty($port_list))
{
foreach($port_list as $d)
{
?>
<option value="<?php echo $d->port_id; ?>"><?php echo $d->port_name; ?></option>
<?php } } ?>
</select>
and ajax is
var search_val = $("#port_of_loading").val();
$.ajax({
type:'POST',
cache:false,
async:false,
data: { 'search_val' : search_val },
url: 'URL',
success: function(data)
{
$("#port_of_loading").html(data);
}
});
I am refreshing it from controller.
consloe.log(data) output is
<select tabindex="2" id="port_of_loading" name="port_of_loading" onkeyup="port_search()">
<option value=""></option>
<option value="26">value1</option>
<option value="9">value2</option>
</select>

Ajax Post request not working?

I am trying to build a form where the user fills information in and clicks submit. Upon clicking, the page will never refresh. Form processing and data handling will happen after the user clicks.
I am trying to use jQuery and Ajax to accomplish this, so far this is what I have:
HTML
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle"> <br>
<label>Article URL: </label>
<input type="text" name="articleUrl"> <br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<?php echo $message;?> //For Debugging
<input type="submit" name="article_info_btn" value="Submit">
</form>
PHP
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
$message = "Success!"; //For debugging
}
Ajax
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
success : function(data) {
alert("Success!");
}
})
})
Upon clicking the submit button, the success window popup alert is shown.
Though, the $message variable never prints out "success!" This means that its not processing the PHP $_POST.
How do I make it so that Ajax sends the information to the PHP $_POST?
$( ".article_information_form" ).on( "submit", function( event ) {
event.preventDefault();
$.post(window.location , $( this ).serialize() , function(result){
alert(result);
});
});
You didnt attach the data payload!!
Since you wanted the entire thing to be on a single page, this would be a possible way:
Full code for easy understanding:
<?php
//exececuted only if POST request as in the ajax below.
if($_SERVER[ 'REQUEST_METHOD']==='POST' ){
//your processing here
header( 'Content-Type: application/json');
//lets set the receivedToServer property to what data we got
$data = array();
$data['receivedToServer'] = $_POST;
//output data as json
echo json_encode($data);
//kill the page once the data is displayed
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
</head>
<body>
<form class="article_information_form" action="" method="POST">
<label>Title </label>
<input type="text" name="articleTitle">
<br>
<label>Article URL: </label>
<input type="text" name="articleUrl">
<br>
<p>Number of pages</p>
<select name="numPages">
<option value="" selected></option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</select>
<br>
<input type="submit" name="article_info_btn" value="Submit">
</form>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$('.article_information_form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '',
data: $(this).serialize(),
success: function(data) {
//the processed data available as data variable.
//lets log the data received at server property we set before
console.log(data.receivedToServer);
alert(data.receivedToServer.articleTitle);
}
});
})
</script>
</html>
You are not pass data to your method so it is not working. So first you will check how many argument have in method, then you send same number of string in params.
You should note one thing about argument are same name as use in method argument name.
$(document).on('submit', '.article_information_form', function(e)
{
e.preventDefault();
$.ajax({
type : 'POST',
url : '',
params : {articleTitle: 'Titlename', articleUrl : 'URLName',numPages : 'PagesNo'}
success : function(data)
{
alert("Success!");
}
})
});
On your form add an ID, in our case I put an id="form_submit" and action="action.php", you need to replace it with your own path where the action should do.
<form id="form_submit" class="article_information_form" action="action.php" method="POST">
also this line of the form,
<input type="button" id="submit" name="article_info_btn" value="Submit">
change the type type="bumit" to type="button" to prevent default submission.
and the jquery,
$('#submit').click(function() {
var submit_url = $(this).parent('form').attr('action');
$.ajax({
type : 'POST',
url : submit_url,
data : $('#form_submit').serialize(),
dataType : 'json',
success : function(data) {
alert("Success!");
}
})
})
This line var submit_url = $(this).parent('form').attr('action'); get the path on the action="" and use that path to passed data.
You need to add data to your ajax call:
$(document).on('submit', '.article_information_form', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
//url: '', by default is the current page url.
data: $('.article_information_form').serialize(),//This line
success: function(data) {
$('.article_information_form type["submit"]').before("<div>"+data+"</div>")
}
})
})
PHP:
if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
echo "Success!"; //For debugging
exit();
}
Like the others have said, you need to add a data parameter to your $.ajax() call.
Your other question - reading the comments - is about how you can get the PHP $message variable to show up without a page load.
That is, unfortunately, impossible without a page-refresh because PHP is rendered on the server side.
What I would suggest, is creating another PHP file that handles the logic that you're trying to create, and then using AJAX to throw the response back onto the current page. Achieving what I believe you want to do.
So! Example time.
first.php
<!doctype html>
<html>
<head><title>First</title></head>
<body>
<form id="myForm">
<input name="email" type="email" />
<button>Go!</button>
</form>
<div id="message"></div>
<script>
$('#myForm').on('submit', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
data: $().serialize(); // send the form data to..
url: 'second.php', // your new PHP page
complete: function(xhr, status){
console.log('xhr', xhr);
console.log('status', status);
$('#message').text(status);
}
});
});
</script>
<body>
</html>
second.php
<?php
if (isset($_POST["email"]) {
echo "Success!";
} else {
echo "Error!";
}
?>
1- Your Ajax Code :-
<script>
$(function() {
$(".article_information_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: "process_page.php",
type: "post",
data: $(this).serialize(),
success: function(html) {
$('#msg').html(html);
}
});
});
});
</script>
2- To print AJAX response add the following "div" under the "body" tag :-
##<div id='msg' ></div>
3- Create a PHP page "process_page.php" to receive the submitted data and then send the result
<?php
$numPages = $_POST['numPages'];
echo $numPages; //anything you echo here will be displayed in the <div id='msg'> at the main page
?>
good luck

Select on change/submit inside Ajax

I have a form that gets submitted via ajax, inside that form there are two selects. these two selects get data from mysql using php.
I want is to show the second select only when the first select has been chosen, I've tried onchange and onsubmit but didn't get it to work. ajax script keeps preventing that! i even tried passing the value of the first select vie js to php, didn't work too.
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<?php
$s1= "<script>document.writeln(recMarque());</script>";
echo $s1;
?>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
<?php
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
</select>
Static html:
<select class="form-control" name="sel1" onchange="recMarque();" required>
<option value="" hidden selected>Choose</option>
<option value="AAA">AAA</option>
<option value="BBB">BBB</option>
</select>
<script language="Javascript">
function recMarque(){
var p1 = $("select[name=sel1]").val();
alert(p1);
return p1;
}
</script>
<script>document.writeln(recMarque());</script>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>
I appreciate your help
Why are you using inline javascript while you are already loading the huge file of jQuery? Use jQuery change event and wrapp your hole code inside a jQuery DOM ready event. Additionnaly why are you mixing PHP with markup and javascript, this goes in contradition of AJAX purposes and of your goal descrption. You want to show the second select after selection from first select and the content depends on selected value (which require server side fetching) then send an XMLHTTPRequest to a separate (small) file and get the response.
$('select[name=sel1]').change(function(e) {
e.preventDefault();
var value = $('select[name=sel1] option:selected').val();
var text = $('select[name=sel1]',this).text();
var urlForSelect2 = $('select').attr('data-url');
// make an AJAX call and send value, text, and all your needed variable alongside
$.ajax({
type: "GET",
url: urlForSelect2,
dataType: 'html',
data: ({value: value, text: text}),
success: function(data){
$('select[name=sel1]').append(data);
});
return false;
});
And seperate the the php responsible for creating into another file with another url (urlForSelect2 in this case):
<option value="" hidden selected>Choose</option>
<?php
// Get the values sent along AJAX request using PHP $_GET, let's say $s1
if(!empty($s1)){
$r=$conn->query(sprintf("select * from table where x='$s1'")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel2))?($d[0]==$sel2)?'selected':null:null) .'>'.$d[0].'</option>';
}
}
?>
And the markup is becoming smaller and readable like:
<select class="form-control" name="sel1" data-url="recMarque();" required>
<option value="" hidden selected>Choose</option>
<?php
$r=$conn->query(sprintf("select * from stock")) or die(mysqli_error($conn));
while ($d=$r->fetch_assoc()){
echo '<option value="' . $d[0] . '"'. ((!empty($sel1))?($d[0]==$sel1)?'selected':null:null) .'>'.$d[0].'</option>';
}
?>
</select>
<select class="form-control" name="sel2" required>
<option value="" hidden selected>Choose</option>
</select>
Here is my solution
In the first select i've put onchange="selChange", the function is as follows:
<script type="text/javascript">
function selChange(){
var val = $("#sel1").serialize();
$.ajax({
type: "POST",
url: "select.php",
data: val,
success: function(data) {
$('#sel2').html(data);
}
});
return false;
}
</script>

Submit a form with JavaScript when the onchange event of an dropdown is fired

I have a dropdown with a submit button, but I would like to eliminate the button, and send the form via Ajax, when the user selects an option from the dropdown.
Here's the code:
<select name="pin" id="pin" class="search_box" >
<option value="">Zip Code</option>
<?php
include("conn.php");
$pin=$_REQUEST[pin];
$city=$_REQUEST[city];
$kk="select * from zip order by zip";
$jj=mysql_query($kk);
while($mm=mysql_fetch_array($jj))
{
?>
<option value="<?php echo $mm[zip]?>"<?php if($mm[zip]==$pin){echo "selected";}?>>
<?php
echo $mm[zip]
?>
</option>
<?php } ?>
</select>
<input type="button" id="findbutton" name="search_button" value="Go" />
Ok here is a version using jquery.
$('#pin').on('change', function(e){
e.preventDefault();
var form = this.form;
var data = $(form).serialize();
$ajax({
data: data,
url: form[0].action
})
})

Categories