ajax output in textbox is not available in post method of submit - php

I have a select dropdown, from that I'm calling an ajax function onchange event. Posting the result in a text input. This much is working perfectly. But when I submit the form the text input value is not submitting.
This is the ajax code. teachername dowpdown and teachercode text input
$("#teachername").change(function(){
var name = $(this).val();
var dataString = "name="+name;
$.ajax({
type: "POST",
url: "get-teachercode.php",
data: dataString,
success: function(result){
$("#teachercode").val(result);
}
});
});
this is the form
<form action="insert-assign-classes.php" method="post">
<select class="form-control" name="teachername" id="teachername" required>
</select>
<input type="text" disabled style="background-color:#fff;" class="form-control" name="teachercode" id="teachercode" required>
getting the value in insert-assign-classes.php file.
$teachercode= $_POST['teachercode'];//not working

Related

Auto fill multiple text fields using Ajax and jQuery

I have a form, which I have divided in to there parts using tabs, in my second tab I'm using a select option and then try to auto fill 2 text box's and one text area using Ajax ,but although console log shows that ajax return the object but it doesn't fill the required fields.
tab
<div class="tab-pane fade " id="package_details">
select option
<select name="package" id="packageid" >
<option selected > Select a Package </option>
#foreach($package as $c)
<option value="{{$c->id}}">{{$c->tour_name}}</option>
#endforeach
</select>
Text fields i need auto filling
<input type="number" name="no_of_days" id="no_of_days" class="form-control"
placeholder="Days" >
<input type="number" name="cost" id="cost" class="form-control"
placeholder="Price" >
<textarea rows="4" cols="50" class="form-control" id="description" name="description" placeholder=" Package Details" ></textarea>
my Ajax code
$(document).on('change', '#packageid', function(e) {
e.preventDefault();
var pkid = $(this).val();
$.ajax({
type:'POST',
url: "{{ route('package.tour') }}",
dataType: "json",
data:{
'_token':$('input[name=_token]').val(),
'selectedid': pkid
},
success: function(data){
// console.log(data);
$('#description').val(data.description);
$('#no_of_days').val(data.no_of_days);
$('#cost').val(data.cost);
}
});
});
Function in my controller
public function getPackage(Request $request)
{
$data = packages::where('id', $request->selectedid)->get();
return response()->json($data);
}
what is wrong with my Ajax / JQuery code ?
check using like this in ajax response :
$("textarea#description").val(data.description);
$("input#no_of_days").val(data.no_of_days);
$("input#cost").val(data.cost);
I finally figured out ,since response is an array i had to use $("#description").val(data[0].description); and it works !

How do i automatically hit a submit button in jquery

i have a ScanField. In this field i'm scanning a barcode. After that i'm cutting the last four character of the bardcode-string and give it to the hiddenField. And from that hidden field when i click on the search button i pass it to the php site via ajax.
for example: i'm scanning a barcode: TWRG000000009102 in the hiddenfield shows 9102 and after that im passing the value to ajax.
Everthing works fine but i would like to do it automatically. When the hidden inputField was filled it should fire an event and pass the value to ajax.
my code:
<label for="myType">
<select id="myType" name="myType" size="5">
<option value="01">B&C</option>
<option value="02">James Nicholson</option>
<option value="F.O.L">Fruit Of The Loom</option>
<option value="TeeJays">TeeJays</option>
</select>
</label>
<br>
<label for="hiddenField">hiddenField:</label>
<input type="text" name="hiddenField" style="width:300px"><br>
<label for="myScan">Scanfield:</label>
<input type="text" name="myScan" style="width:300px" autofocus>
<button type="submit">Search</button>
<div id="result"></div>
<script>
$(document).ready(function(){
$('input[name=myScan]').on('keypress', function(e){
if(e.which == 13) {
var scanField = $(this).val();
console.log(scanField);
var lastFour = scanField.substr(scanField.length - 4);
$('input[name=hiddenField]').val(lastFour);
}
});
$('button').on('click', function(){
var postForm = {
'myType' : $('#myType').val(),
'myScan' : $('input[name=hiddenField]').val()
};
$.ajax({
url: "index.php",
type: "POST",
data: postForm,
dataType: "text",
success: function(data){
$('#result').html(data);
}
});
});
});
here the html example: https://jsfiddle.net/froouf9f/
Once you save value to hidden field, you can trigger button click event using:
$("button").trigger("click");
Try this:
$('input[name=myScan]').on('keypress', function(e){
if(e.which == 13) {
var scanField = $(this).val();
console.log(scanField);
var lastFour = scanField.substr(scanField.length - 4);
$('input[name=hiddenField]').val(lastFour);
$("button").trigger("click");
}
});

AJAX stay on same page after submit, output on same page

I have some drop downs looks like this in my HTML form:
<form name="fee" method="POST" action="">
<p><span class="title">Number of artists:</span>
<select name="Number">
<option value="" rel="none" selected disabled>Please select an option..</option>
<option value="one" rel="one_art">One artist only</option>
<option value="more" rel="more_arts">More than one artists</option>
</p>
A table of summery will be generated after I click the submit button.
<input type="submit" value="Calculate">
My question is: Whenever I click the button, the previously selected option will be reset. And only the summery show up at the end of the page. Is there a way to output the summery on the same page without the previously selected option gets cleared?
Thanks in advance!!
I think your best option is to use AJAX POST to post the form data, and JQuery to keep the same option selected:
$(document).ready(function() {
$("#fee").on('submit',(function(e) {
e.preventDefault();
var selectedOption = $( "#Number option:selected" ).text();
$.ajax({
url: "here put the url to the php page handling your form data",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function ()
{
$("#Number").val(selectedOption);
}
});
}
});

Sending Multiple data to PHP page without reloading page

Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});

CodeIgniter and AJAX form submit

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});

Categories