Post the value of a form to php using ajax - javascript

I am trying to post the value of a form to php using ajax, I would like to stay on the current page when the form is submitted.
I have tried various methods but am unsure what to do next.
Curently when i click one of the radio values the data gets submitted but the page changes to the php script.
<!doctype html>
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
</script>
<meta charset="utf-8">
<title>TEST</title>
</head>
<body>
<h1>Scores Page</h1>
<form action="updatescore.php" method="post">
<form>
<input type="radio" name="newScore" value="1" >1
<br>
<input type="radio" name="newScore" value="2" >2
<br>
<input type="radio" name="newScore" value="3" >3
<br>
<input type="radio" name="newScore" value="4" >4
<br>
<input type="radio" name="newScore" value="5" >5
<br>
</form>
</body>
<script type='text/javascript'>
$(document).ready(function() {
$('input[name=newScore]').change(function(){
$('form').submit();
});
});
</script>
</html>

$('input[name=newScore]').change(function(){
var xyz = $(this).val();
$.post('updatescore.php', {xyz:xyz}, function(data){
//any operation after submitting data;
});
});
Handle xyz using $_POST['xyz'] in updatescore.php file.

Related

Simple Calculator with javascript

I am getting back into javascript for a job I am going to start soon. for some reason i forgot how to do a simple calculator. I dont understand why my even onclick is null when it is a button. I am sure this is a very simple answer I just cant see it.
if(document.getElementById("add").onclick == true){
alert("hey");}
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src= "script.js"> </script>
</head>
<body>
<h3> Calculator: </h3>
<input type="text" name="a">
<input type="text" name="b">
<input type="button" value="+" name="add">
</body>
</html>
To get you started I made minor changes to your code, go through the changes and understand the use of each change.
function sum(){
var a = document.getElementById("a");
var b = document.getElementById("b");
alert(Number(a.value) + Number(b.value));
}
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src= "script.js"> </script>
</head>
<body>
<h3> Calculator: </h3>
<input type="text" name="a" id="a">
<input type="text" name="b" id="b">
<input type="button" onClick="sum()" value="+" name="add">
</body>
</html>

Execute php script from onclick insert to database

I have created a working example that inserts the value of a radio button to a database using a submit button but now i'm looking at ways to insert without the use of a submit button.
I have a javascript function that when a radio button is clicked it should execute the php.
I have looked at why i can't get it to function but i'm unsure if its even possible or if there's a better way to do this. Below is my code
<html>
<head>
<title>survey</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="test.css" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
</head>
<div class="cc-selector">
<form class="cc-selector" id="form-id" method="POST">
<label><input id="happy" type="radio" name="radioAnswer" onclick="doSomething();"></label>
<label class="drinkcard-cc happy" for="happy"></label>
<label><input id="sad" type="radio" name="radioAnswer" onclick="doSomething();"></label>
<label class="drinkcard-cc sad"for="sad"></label>
</form>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("sample2.php");
return false;
}
</script>
</body>
</html>
And my php sample2.php
<?php
$con = mysqli_connect("localhost","root","","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['radioAnswer'])){
$radioAnswer = $_POST['radioAnswer'];
mysqli_query($con,"INSERT INTO survey (radioAnswer) VALUES ('$radioAnswer')");
}
?>
Use onchange. and an opening body tag.
<html>
<head>
<title>survey</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="test.css" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div class="cc-selector">
<form class="cc-selector" id="form-id" method="POST">
<label><input id="happy" type="radio" name="radioAnswer" onchange="doSomething();"></label>
<label class="drinkcard-cc happy" for="happy"></label>
<label><input id="sad" type="radio" name="radioAnswer" onchange="doSomething();"></label>
<label class="drinkcard-cc sad"for="sad"></label>
</form>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("sample2.php");
return false;
}
</script>
</body>
</html>
You are preforming database insert in a GET request,
First, this is very bad practice.
Second, it won't work as expected because GET request could be cached by browser or proxies,
Btw, your PHP is reading $_POST
The $.get() method requests data from the server with an HTTP GET request.
what you want to do is send data from the server using an HTTP POST request.
i suggest you use :
$.post("sample2.php",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
or even better :
$.ajax({
url : 'sample2.php',
type : 'POST',
data : 'email=' + email + 'content=' + content,
dataType : 'html'
});
find more details about $.ajax in https://www.w3schools.com/jquery/ajax_ajax.asp
send requests using ajax javascript
function doSomething() {
$.ajax(
{
type: 'GET',
data: {'radio1': $('#happy').is(':checked'), 'radio2': $('#sad').is(':checked')}
url: '/your_php_file_name.php',
success: function(data){
console.log("here is the result : " + data);
}
}
);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cc-selector">
<form class="cc-selector" id="form-id" method="GET>
<label><input id="happy" type="radio" name="radioAnswer" onclick="doSomething();"></label>
<label class="drinkcard-cc happy" for="happy"></label>
<label><input id="sad" type="radio" name="radioAnswer" onclick="doSomething();"></label>
<label class="drinkcard-cc sad"for="sad"></label>
</form>
</div>
in your your_php_file_name.php file
<?php
// your javascript radio button 1 value;
$happy = $_GET('radio1');
// your javascipt radio button 2 value ;
$sad = $_GET('radio2');
echo 'success';
?>
Figured out how to execute my Php using the onclick method to insert into sql database answer below.
<form name="form" action="sample2.php" class="cc-selector" method="post" >
<label class="label">
<input type="image" name="Opinion" value="Positive" src="happy.png" onclick="document.getElementById('form').submit();"/>
</label>
<label class="label">
<input type="image" name="Opinion" value="Negative" src="sad.png" onclick="document.getElementById('form').submit();"/>
</label>
</form>

Php search form shows results without pressing the search button when it should wait until the button is pressed to show them

As the title suggests I'm trying to show the results of a query and it works properly, but it shows the results automatically beneath the search button, when it should wait for the button to be pressed and then reload the page and show the results. I'm kind of sure that it's a problem with the code but I cannot find where. I know it's a stupid question but all help is appreciated.
Here is my code:
<?php
mysql_connect('localhost', 'root', 'Passw0rd') or die(mysql_error());
mysql_select_db("cvtool") or die(mysql_error());
include("include/session.php");
$username = $_SESSION['username'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!--The viewport tag is used in order to scale the page properly inside any screen size -->
<meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>CV Tool</title>
<link rel="shortcut icon" href="images/favicon.ico" />
<link rel="stylesheet" href="css/main.css"/>
<!--Import JQuery from stored file -->
<script src="js/jquery-1.11.1.min.js"></script>
<!--Import JQuery from Google's Content Delivery Network -->
<!--<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">-->
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="js/menu.js"></script>
<script type="text/javascript" src="js/backToTop.js"></script>
</head>
<body>
<!--Big wrapper contains the whole site (header,navigation menu,....,footer-->
<div id="big_wrapper">
<header id="top_header">
<img src="images/cvlogo.png">
</header>
<br>
<nav class="clearfix">
<ul class="clearfix">
<li>Home</li>
<?php
/**
* User has already logged in, so display relavent links, including
* a link to the admin center if the user is an administrator.
*/
if($session->logged_in){
echo "<li>Search</li>"
."<li>My CV(s)</li>"
."<li>My Account</li>"
;
echo "<li>Logout</li>";
}
else
?>
</ul>
Menu
</nav>
<section id="main_section">
<?php
/**
* User not logged in, display the login form.
* If user has already tried to login, but errors were
* found, display the total number of errors.
* If errors occurred, they will be displayed.
*/
if($form->num_errors > 0){
echo "<font size=\"2\" color=\"#ff0000\">".$form->num_errors." error(s) found</font>";
}
?>
<form action="search.php" method="GET" >
<h1>Search for an CV</h1>
<h3>Department</h3>
<br/>
<select id="dropDown">
<option value="">Choose a department</option>
<option value="Comp">Computer Science</option>
<option value="Bus">Business Studies</option>
<option value="Psy" >Psychology</option>
<option value="Eng">English Studies</option>
</select>
<br/>
<h3>Skills</h3>
<br/>
<div id="Comp"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Java
<input type="checkbox" name="whatever" />
AI
<input type="checkbox" name="whatever" />
Web Development
</div>
<div id="Bus"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Business 1
<input type="checkbox" name="whatever" />
Business 2
<input type="checkbox" name="whatever" />
Business 3
</div>
<div id="Psy"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
Psychology 1
<input type="checkbox" name="whatever" />
Psychology 2
<input type="checkbox" name="whatever" />
Psychology 3
</div>
<div id="Eng"class="drop-down-show-hide">
<input type="checkbox" name="whatever" />
English Studies 1
<input type="checkbox" name="whatever" />
English Studies 2
<input type="checkbox" name="whatever" />
English Studies 3
</div>
<script>
$(document).ready();
$('.drop-down-show-hide').hide();
$('#dropDown').change(function () {
$(this).find("option").each(function () {
$('#' + this.value).hide();
});
$('#' + this.value).show();
});
</script>
</form>
<form action="search_result.php">
<input type="submit" name="search" id="search" value="Search" />
<div id="search"></div>
<script>
$(document).ready(function(){
$("#dropDown").change(function(){
var data = $(this).val();
$.ajax({
type:'POST',
data:'search_value='+data,
url:'search_result.php',
success:function(data){
$("#search").html(data);
}
});
});
});
</script>
</form>
</section>
<footer id="the_footer">
City CV Tool 2014
</footer>
</div>
</body>
</html>
it's because of this line
$("#dropDown").change(function(){
add a submit button in the form if that's what you want then run the function off that
<input type="submit" value="Submit" />
Edited after rwacarter's correct comments below about accessability
Add an Id to the form tag
<form id="searchformSubmit"
then do
$("#searchformSubmit").on('submit',function(){
this should also work if the user presses the enter key to submit rather then the button provided you have only the one form on the page
The reason why the page is reloading is because any <button> or or <input type='submit'> inside a HTML form will reload the page, unless you have onClick='return false;' on them. I think you need to add:
onClick="startsearch();return false;"
on the submit button. You'll also have to send the form data with it. To do this, make a variable with this:
var form_data = $('#form').serialize();
and send it with:
$.post('search_result.php', {form: form_data}, function(data) {$("#search").html(data);})
Your ajax call (result search) is called when your dropdown change (click, user input, ...), but you should bind the action to your form click
$(document).ready(function(){
$("#search").click(function(){
var data = $("#dropDown").val();
$.ajax({
type:'POST',
data:'search_value='+data,
url:'search_result.php',
success:function(data){
$("#search").html(data);
}
});
});
});
In addition, this is not necessary to specify the action in your form however it will trigger the form action and redirect you to the page search_result.php, I suggest you to update it and set action="#"

Focus on input field not working with ID

I am trying to highlight an input field in my form when a particular radio buttons is selected. While I have accomplished this, I do not understand why my particular solution works.
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<meta charset="UTF-8">
<script type="text/javascript" src="script.js"></script>
<title>Testing jQuery on Forms</title>
</head>
<body>
<div id="form">
<h3>The form</h3>
<form name="main_form">
<fieldset style="width: 300px;">
<legend>General Information</legend>
<p>Do you have a name?</p>
<input style="float: left" name="name_or" id="name_or_yes" type="radio" value="yes">
<legend for="name_or_yes">Yes</legend>
<input style="float: left" name="name_or" id="name_or_no" type="radio" value="no" checked="checked">
<legend for="name_or_no">No</legend>
<br/>
Name: <input type="text" name="name" id="#name_field">
</fieldset>
</form>
<button id="submit_form">Submit</button>
</div>
<div id="results"></div>
</body>
</html>
Here is the JS:
$(document).ready(function() {
$('#name_or_yes').click(function() {
$('input[name=name]').focus();
});
$('#submit_form').click(function() {
var toAdd = $("input[name=name]").val();
$('#results').append("<p>"+toAdd+"</p>");
});
});
I don't understand why focus() does not work on the name input field when I use it's id (#name_field'). It only works when i use the input[name=name] method. This is doubly confusing because the following works perfectly well:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#txtfocus").focus();
});
</script>
</head>
<body>
<input type="text" id="txtfocus2"><br/>
This text box is set focused: <input type="text" id="txtfocus">
</body>
</html>
Any help or advice is appreciated!
Look at the id here:
<input type="text" name="name" id="#name_field">
Try it like this:
<input type="text" name="name" id="name_field">
The # is the id selector, but should not appear in the HTML.
Thank you both!
These are the kind of mistakes which happen when you spend too much time looking at the same piece of code!
I would like to upvote you however, I do not have sufficient reputation points to do so. :(
input's ID should be "name_field" instead of "#name_field":
<input type="text" name="name" id="name_field">

java script/ jquery not working in IE

I have some code which works perfectly in Firefox, but not in IE. The desired solution is that after a user selects a radio button, a dropdown would show up containing options related to the radio button category. However, currently when using IE, when a user selects a radio button it will show the drop down but would have all the options including the ones related to the radio button that is not selected
here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tools</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.chained.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="infratool.js"></script>
</head>
<body class="oneColFixCtrHdr">
<div id="container">
<div id="header" style="background-color:#7BD12E">
<h1 align="Center" style="color:#FFF;"></h1>
<!-- end #header --></div>
<form id="form1" name="form1" method="post" action="">
<table width="392" border="0">
<tr>
<td align="center">
<label><input name="Radio1" type="radio" id="Radio1" value="Radio1" onclick="showSelect();" />Radio1</label>
<label><input name="Radio2" type="radio" id="Radio2" value="Radio2" onclick="showSelect();" />Radio2</label>
<input type="radio" name="Radio3" id="Radio3" value="Hidden" style="display:none" checked="checked" />
</td>
</tr>
<tr>
<td align="center"> </td>
</tr>
</form>
<div id="div-id" align="center"><select name="Category" id="Category" class="hide">
<option value=" Radio1 Radio2" selected="selected">--</option>
<option value="1 Radio1">1</option>
<option value="2 Radio1">2</option>
<option value="3 Radio1">3</option>
<option value="4 Radio2">4</option>
<option value="5 Radio2">5</option>
<option value="6 Radio2">6Domain</option>
</select><input type="submit" value="Go" id="submit"/>
</div>
</table>
</div>
</body>
</html>
while here are my java scripts
//Show Select option after clicking Radio button:
function showSelect() {
var select = document.getElementById('Category');
select.className = 'show';
}
//Select option, separates the link from Class
$(function(){
var select = $('#Category'),
options = select.find('option');
$('[type="radio"]').click(function(){
var visibleItems = options.filter('[value*="' + $(this).val() + '"]').show();
options.not(visibleItems).hide();
if(visibleItems.length > 0)
{
select.val(visibleItems.eq(0).val());
}
});
});
$(function() {
$("#submit").hide();
$("#Category").change(function() {
window.location = $(this).val().split(" ")[0];
if(loc)
window.location.href = loc;
})
});
I've tried to use the IE developer tools, but to no avail.
You can't just show/hide <option> elements. You have to actually remove them from the drop-down.
Personally I would suggest cloning the select box when the page loads, and then using that as a base to repopulate the re-filter the original dropdown.
IE will not just let you hide options.
Perhaps you could instead disable the option using:
.prop('disabled', true);

Categories

Resources