Execute php script from onclick insert to database - javascript

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>

Related

Save insert from to file

I have a input form and want to save the data that I haved insert into a file. Should I use get and set for this? Anyone have any ideas on what I should do?
function myfunction() {
if (validation()) // Calling Validation Function
{
// Serializing Form Data And Displaying It In <p id="wrapper"></p>
document.getElementById("wrapper").innerHTML = serialize(document.forms[0]); // Serialize Form Data
document.getElementById("form").reset(); // Reset Form Fields
}
}
function validation() {
var name = document.getElementById("namn").value;
var number = document.getElementById("number").value;
}
<!DOCTYPE html>
<html lang="sv">
<head>
<title>Write</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://form-serialize.googlecode.com/svn/trunk/serialize-0.2.min.js" type="text/javascript"></script> <!-- For Serialization Function -->
<script src="hej.js"></script> <!-- Include JavaScript File Here-->
</head>
<body>
<div id="main">
<div id="login">
<hr/>
<form action="" method="post">
<label>Name:</label>
<input type="text" name="name" id="name" required="required" placeholder="fill in your name"/><br /><br />
<label>Number :</label>
<input type="text" name="number" id="number" required="required" placeholder="0876856"/><br/><br />
<input onclick="myfunction()" type="submit"id= "submit" value=" Submit " name="submit"/><br />
</form>
</div>
</div>
</body>
</html>
Thanks in advance!
If you use the normal $_POST you can access the data over $_POST and write it with fopen, fwrite to a file. Over ajax you have to send the Data to a PHP File and do the same there. You cant access the local filesystem over Javascript.
<?php
if(isset($_POST) && !empty($_POST){
// reformat your data here and format it
$yourDataToWriteInTheData = $_POST['firstname'] . '|' . $_POST['lastname'] . PHP_EOF;
// Open the file (or create it, read the fopen manual)
$fileHandler = fopen('file1.txt', 'a+');
fwrite($fileHandler, $yourDataToWriteInTheData);
fclose($fileHandler);
}

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="#"

Post the value of a form to php using ajax

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.

how to submit a form from loaded form into main page?

contact.php
... html form ...
$('#submit').click(function(){
$.post("mail.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
mail.php is a separate file (for sending mail), and everything works in this arrangement.
But I need to load contact.php into index.php
$('#divR').load('chapters/contact.php');
so corresponding js line becomes
$.post("chapters/mail.php", $("#contact").serialize(), function(response) {...
Submitting the form in this case response from mail.php is received, but POST array is empty, i.e. form doesn't send any data to mail.php !?
I wrote your code in 2 new pages to see what it actually does, and noticed a few things. A few small things such as calling the submit handler instead of click, since people can also press Enter to submit a form, but most important the data itself: A form doesn't need to be serialized, the browser will already do that for you. In this script I store the data in a new object and pass it to the $.post method.
<form method="post" action="" id="contact">
<div>
<input id="email" type="text">
</div>
<div>
<input id="submit" type="submit">
</div>
</form>
Script:
$("#contact" ).on("submit", function () {
var data = {
email: $("#email").val()
};
$.post("test.php", data, function (response) {
$('#success').html(response);
});
return false;
});
In test.php I simply do a print_r($_POST), which is also the response. It will output something like:
Array
(
[email] => test
)
Hope this helps.
I've made a simple test, trying to mimic your goal:
testLoad.php = index.php in your case:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(function(){
$('#testLoad').load('Test/testForm.php');
});
</script>
</head>
<body>
<div id="testLoad"></div>
<div id="success"></div>
</body>
</html>
testForm.php and testTarget.php are respectively - contact.php and mail.php and are situated in folder Test their code is as follows:
testForm.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form id="contact" method="post" action="">
<p>
<label for="textfield">Name:</label>
<input type="text" name="textfield" id="textfield">
</p>
<p>
<label for="textfield2">Address:</label>
<input type="text" name="textfield2" id="textfield2">
</p>
<p>
<label for="textfield3">Mail:</label>
<input type="text" name="textfield3" id="textfield3">
</p>
<p>
<label for="textfield4">Subject:</label>
<input type="text" name="textfield4" id="textfield4">
<br>
</p>
<p>
<label for="textarea">Message:</label>
<textarea name="textarea" id="textarea"></textarea>
</p>
<p>
<input type="button" name="submit" id="submit" value="Submit" onClick="sendForm();">
</p>
</form>
<script>
$('#submit').bind('click', function(){
//console.log($("#contact").serialize());
$.post("Test/testTarget.php", $("#contact").serialize(), function(response) {
$('#success').html(response);
});
return false;
});
</script>
</body>
</html>
and testTarget.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php print_r($_POST);?>
</body>
</html>
when testing in success div I receive the POST printed out.
Hope this helps.

jQuery/AJAX execution of PHP not working

I am trying to use jQuery/AJAX to run a PHP file on a server. This PHP simply adds a row with some constants to a database. Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit Application</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("http://.../submitApp.php");
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="javascript:doSomething()">
<p>
<label for="programName"></label>
<input type="text" name="programName" id="programName" />
</p>
<p>
<label for="greQuant"></label>
<input type="text" name="greQuant" id="greQuant" />
</p>
<p>
<label for="greVerbal"></label>
<input type="text" name="greVerbal" id="greVerbal" />
</p>
<p>
<input type="submit" name="submitApp" id="submitApp" value="Submit" />
</p>
</form>
</body>
</html>
Upon pressing the submit button on the above form, nothing seems to happen. I should mention I am running this locally via DreamWeaver. I know for a fact that the code is reaching the JavaScript method and that the PHP code is functional. Anyone know what's wrong?
Use POST instead of GET to do this work.
function doSomething() {
var programName = $('#programName').val();
var greQuant = $('#greQuant').val();
var greVerbal = $('#greVerbal').val();
$.ajax({
type: "POST",
url: "submitApp.php", //URL that you call
data: { programName: programName, greQuant:greQuant, greVerbal:greVerbal } //var in post: var from js
}).done(function(msg) {
alert(msg);//change to something to indicate action
}
});
and with your php, handle like this
<?php
$programName = $_POST['programName'];
$greQuant = $_POST['greQuant'];
$greVerbal = $_POST['greVerbal'];
//do something important
?>
this is just a simple example, you need apply some security to this php code

Categories

Resources