Making a search of course/teacher with Ajax and jQuery - php

I have a jQuery Ajax problem.
I have a select tag with options of courses, the select holds div id="course". I have a button with id of "go" and an empty div with id of "courseInfo". I need to make it so that when a course number is selected, the teacher name in my php file that goes with it is displayed on the page. I have all my Ajax written, everything is linked, but it wont work and no error when I debug.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
Form:
<form action="" method="post">
<select name="course" id="course">
<option value="420-121">420-121</option>
<option value="420-122">420-122</option>
<option value="420-123">420-123</option>
<option value="420-221">420-221</option>
<option value="420-222">420-222</option>
<option value="420-223">420-223</option>
<option value="420-224">420-224</option>
</select>
Select a course to see the course name and teacher assigned<br><br>
<input type="button" id="go" value="go!">
</form>
<br><br>
<div id="courseInfo"></div>

Assuming that the PHP side is working properly, the code below should fix the issue.
$(document).ready(function(){
findCourse = function(){
var file = "Course.php?course="+$("#course").val();
console.log(file);
$.ajax({
type: "GET",
url: file,
datatype : "text",
success : function(response) {
$("#courseInfo").html(response);
}
});
}
clear = function(){
$("#courseInfo").html("");
};
$("#course").click(clear);
$("#go").click(findCourse);
});
You miss the = in var file.
Yours was
var file = "Course.php?course"+$("#course").val();
It should be
var file = "Course.php?course="+$("#course").val();

Related

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");
}
});

Reset ajax data when button clcik using jquery

I have scenario form like this
if option selected it will come out a new field i named "hah" i call it using ajax script like this
$('#bahan').change(function() {
var id = $('#bahan').val()
var datana = 'id=' + id
var urlna = "<?=base_url()?>controller/food/getdetailstok";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
success: function(data) {
$('#hah').html(data);
}
})
return false;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<select class="form-control select2" name="bahan" id="bahan">
<option value="">-- Choose One --</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
</div>
<div id="hah"></div>
How to reset "hah" if i click button save. hah in reset because the value field options again become null
$('#hah').empty() will do the trick.
.empty() will remove every element from the DOM. In your case every element in your #hah div.
$('#bahan').change(function() {
$('#hah').html("");
var id = $('#bahan').val()
var datana = 'id=' + id
var urlna = "<?=base_url()?>controller/food/getdetailstok";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
success: function(data) {
$('#hah').html(data);
}
})
return false;
})

jQuery - Serialize Form Post Values

How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal&param2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.

HTML PHP show form submit results on same page

I am trying to make a set of webpages that will display a unique graph based on a simple form that only has a selector box and a submit button. Basically what I want to happen is when the user changes the month in the selector and presses submit, a new chart set will render on the same page.
Here is the HTML initial page:
<HTML>
<HEAD>
<SCRIPT src="http://code.jquery.com/jquery-1.10.1.min.js"></SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FORM ID="form1" METHOD="post" ACTION="">
<SELECT NAME="monthSelector">
<OPTION VALUE="0">Select Month...</OPTION>
<OPTION VALUE="1">January</OPTION>
<OPTION VALUE="2">February</OPTION>
<OPTION VALUE="3">March</OPTION>
<OPTION VALUE="4">April</OPTION>
<OPTION VALUE="5">May</OPTION>
<OPTION VALUE="6">June</OPTION>
<OPTION VALUE="7">July</OPTION>
<OPTION VALUE="8">August</OPTION>
<OPTION VALUE="9">September</OPTION>
<OPTION VALUE="10">October</OPTION>
<OPTION VALUE="11">November</OPTION>
<OPTION VALUE="12">December</OPTION>
</SELECT>
<INPUT TYPE="submit" VALUE="Show Charts">
</FORM>
<DIV ID="response"></div>
<SCRIPT>
function submit()
{
$(function()
{
var month = 3;
var formdata = "month=" + month;
$.ajax({
type: 'POST',
url: 'showCharts.php',
data: formdata,
success: function(data) {
$("#response").html(data);
}
});
});
}
</SCRIPT>
</CENTER>
</BODY>
</HTML>
and here is showCharts.php:
<?php
include("../FusionCharts/FusionCharts.php");
include("../DBConnect.php");
$month = $_POST['month'];
echo $month;
//insert complex queries and fusioncharts code that already works!
?>
Someone please help me, I've been staring at this for hours and can't make any progress.
You can also use the .load method of jQuery:
function submit()
{
var month = 3;
var formdata = month;
$('#response').load('showCharts.php?month='+formdata);
}
Also, you will need to set:
$month = $_REQUEST['month'];
Another way to do it would be:
$('select').change(function() {
var formdata = { month: document.getElementsByName('monthSelector')[0].value };
$('#response').load( 'showCharts.php', formdata);
});
Try replacing
<FORM ID="form1" METHOD="post" ACTION="">
for
<FORM ID="form1" METHOD="post" ONSUBMIT="submit(); return false;">
It should work.
In the part of jQuery, put this:
function submit()
{
var month = $('select[name="monthSelector"]').val();
$.ajax({
type: 'POST',
url: 'showCharts.php',
data:{'month':month},
success: function(data)
{
$("#response").html(data);
}
});
}
One more thing: try to improve the HTML code, it will give a better image to your webpage.
Are you sure the submit function is even called? Do you bind the form's submit event at all?
I would do something like $("#form1").submit(submit);
Also, you should return false at the end of submit() to block the default form action (which is refresh the current page I believe)
Try to update the variable formdata to make it a json object rather than a string.
<SCRIPT>
function submit()
{
$(function()
{
var month = 3;
var formdata = {'month': month}; //change made here
$.ajax({
type: 'POST',
url: 'showCharts.php',
data: formdata,
success: function(data) {
$("#response").html(data);
}
});
});
}
</SCRIPT>
Your jQuery code should be as follows:
$(function() {
var month = 3;
var formdata = { month: month };
$('#response').load( 'showCharts.php', formdata );
$('#form1').submit(function( e ) {
e.preventDefault();
var formData = { month: this.monthSelector.value };
$('#response').load( 'showCharts.php', formData);
});
});
When using the ajax .load() method, here is what you should be aware of:
Request Method
The POST method is used if data is provided as an object; otherwise,
GET is assumed.
Therefore, with the above jQuery code, your PHP script need not be changed.

php variable in jquery.ajax request

I have a form in a php file that takes user entered values and sends the data into a .txt file.
Now it works fine when the form is filled, the 'submit' button is clicked and the user is sent to a 'confirmation/completed' page, whilst the data received is put into a .txt file.
What i want to do is use ajax and jquery to have the form => completed/confirmation without being sent to the other page.
The problem is the user data is not being transmitted now to the .txt file.
PHP: (confirmation.php)
<?php
$color = $_POST['color'];
$fp = fopen('userdata.txt', 'w');
$valstring = "What Color: " . $color . "\r\n";
fwrite($fp, $valstring);
fclose($fp);
?>
AJAX/JQUERY: (button clicked from form.php)
$(document).ready(function() {
var cir = {
load: $('<div />', { class: 'loading' }),
contain: $('#contain')
}
$('input[type="submit"]').on('click', function(e) {
e.preventDefault();
$.ajax({
url: 'confirmation.php',
type: 'POST',
beforeSend: function() {
cir.contain.append(cir.load);
},
success: function(data) {
cir.contain.html(data);
}
});
});
});
When using the ajax above the userdata.txt file only has the What Color: entered into it. The $color value that the user selected has not been recognised.
I know the code works without the ajax, but i would like to have the ajax (no page refresh) method, if possible.
Thanks in advance for any help.
You must set the data parameter in your ajax call, something like this should work:
<form>
<select name="color" id="color">
<option value="Red">Red</option>
<option value="Green">Green</option>
</select>
<select id="age">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" id="name" />
<input type="submit" value="SEND" />
</form>
$('input[type="submit"]').on('click', function(e) {
$.ajax({
url:'confirmation.php',
type:'POST',
// get the selected values from 3 form fields
data:'color=' + $('#color').val() +
'&age=' + $('#age').val() +
'&name=' + $('#name').val(),
success:function(data) {
// ...
}
});
return false;
});
You should probably read more about jQuery.ajax
you are not sending any data in your ajax post, for this reason the variable $color it's empty in the confirmation.php
try changing this:
$.ajax({
url: 'confirmation.php',
type: 'POST',
beforeSend: function() {
cir.contain.append(cir.load);
},
success: function(data) {
cir.contain.html(data);
}
with:
var formColor = $("#colorId").val(); //where ColorId it's the color input type ID
$.ajax({
url: 'confirmation.php',
type: 'POST',
data: { color: formColor },
beforeSend: function() {
cir.contain.append(cir.load);
},
success: function(data) {
cir.contain.html(data);
}

Categories