I am trying to get the current code to take the on or off value from the form and put it into an SQL database using a function call to a JS function that contains an AJAX request that then posts it to a PHP page that runs the actual query. I am not sure what I have done wrong and the API has been more confusing than helpful. I appreciate any help!
Current Page Code:
<?php require('../php/validation.php');?>
<?php require('../php/background.php');?>
<?php
if(isset($_POST['selectonoff'])){
$_SESSION['onoff'] = $_POST['selectonoff'];
$query = 'UPDATE onoff SET onoroff = $_POST["selectonoff"] WHERE ID = 1;';
$update = mysqli_query($db, $query);
}
?>
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>User Settings Dropdown Menu</title>
<link rel="stylesheet" href="../css/settings.css">
<script type="text/javascript">
function load() {
document.getElementById("selectonoff").value = '<?php echo $_SESSION['onoff'];?>';
}
</script>
<script src="jquery.js"></script>
<script>
function rel(id)
{
jQuery.ajax({
type: "POST",
data: 'id='+id,
url: "../php/update.php",
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
</head>
<body onload="load();">
<!-- <div id="wrap"> -->
<br><br><br><br>
<h1>Admin Settings Menu</h1>
<form method="post" action="adminconfig.php">
<p>Toggle BBQ Form</p>
<select id="selectonoff" name="selectonoff" onchange="this.form.submit(); rel();">
<option value="NONE">Select</option>
<option value="ON">Toggle ON</option>
<option value="OFF">Toggle OFF</option>
</select>
</form>
<form action="../index.php">
<input type="submit" value="Home" />
</form>
<script type="text/javascript">
</script>
</body>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src="../js/index.js"></script>
</html>
Current PHP Code:
<?php
require ('php/server.php');
$db = mysqli_connect('localhost', 'root', '', 'dedricks');
if(!$db){
die("Connection Failed: ".mysqli_connect_error());
}
$var = #$_POST['id'] ;
$query = 'UPDATE onoff SET onoroff = $var WHERE ID = 1;';
mysqli_query($db, $query);
?>
Few corrections needed here.
ERRORS
You are not reading the value of the select control anywhere in your code that needs to be sent in the ajax call
onchange for the selectonoff list is trying to submit the form and at the same time calling rel function (without any parameter). It seems like it needs to trigger the ajax call when the selectonoff selection is changed.
The jquery needs to be added once either via cdn or from local directory
It needs to be added before the script tag in the head.
TODO
Remove this.form.submit(); and rel from onchange. Rather remove the entire onchange
A code based on your page that is working and submitting the data to the php page is as below. You can make the changes according to your needs.
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>User Settings Dropdown Menu</title>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function rel(id){
var formData = {"id": id};
$.ajax({
type: "POST",
data: formData,
url: "../app/update.php",
cache: false,
success: function(response){
console.log("response", response);
alert("Record successfully updated");
},
error: function(error){
console.log("error", error);
}
});
}
$(document).ready(function(){
$("#selectonoff").change(function(){
var val = $("#selectonoff option:selected").val();
rel(val);
});
});
</script>
</head>
<body>
<!-- <div id="wrap"> -->
<br><br><br><br>
<h1>Admin Settings Menu</h1>
<form method="post" action="adminconfig.php">
<p>Toggle BBQ Form</p>
<select id="selectonoff" name="selectonoff">
<option value="NONE">Select</option>
<option value="ON">Toggle ON</option>
<option value="OFF">Toggle OFF</option>
</select>
</form>
<form action="../index.php">
<input type="submit" value="Home" />
</form>
</body>
</html>
NOTE
I have now tested the above code to be working and submitting the ajax request to a php script.
Related
I'm new to Web Development. I'm learning JavaScript now(JQuery) and I chose Simple Chat as a project to get started.
Unfortunately, I can't figure out how to prevent the page from refreshing after a message is sent.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Chat</title>
</head>
<body>
<h1>Chat room</h1>
<div id="status"></div>
<form id="send" class="ajax" action="action.php" method="POST">
<label for="fname">Type your message</label>
<input type="text" id="fname" name="myMessage">
<input id="upload" type="submit" name="myButton"value="Submit" />
</form>
<div id="result"></div>
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
name: $("#fname").val(),
};
var posting = $.post(url, {
name: $('#fname').val(),
});
/* So far, just listing whether the Form has managed to prevent its classic sending */
posting.done(function(data) {
$('#result').text('success');
});
$.ajax({
type: "POST",
url: "process.php",
data: formData,
dataType: "json",
encode: true,
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
</script>
</body>
</html>
PHP:
<?php
$path = 'messages.txt';
if (isset($_POST['myButton']) ) {
$fh = fopen($path,"a");
$string = $_POST['myMessage' ];
fwrite($fh,$string . PHP_EOL);
fclose($fh);
}
?>
I have created a text file messages.txt, where I want to save newly created messages using Ajax.
I would like the newly added message to be displayed on the page below the chat( in the div with id #result)
Thanks everybody for advices, this is how I have solved it
$("#send").submit(function() {
event.preventDefault();
var $messageSent = $("#send").serialize();
$.ajax({
type: 'POST',
url: 'action.php',
data: $messageSent,
});
});
To save data to file in PHP with this jquery ajax code, try this:
<?php
$path = 'messages.txt';
if (isset($_POST['name']) ) {
$fh = fopen($path,"w");
$string = $_POST['name']. PHP_EOL;
fwrite($fh,$string);
fclose($fh);
}
?>
In PHP I am Working on when form has been submitted the values should send to different files Using jquery. example if demo.php form has been submitted data should sent to both process1.php as well as process2.php simultaneously but Its not showing any error and not able to get output.
please help me through this code I have tried so far
Demo.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>main form</title>
</head>
<body>
<form action="multi.php" method="post">
Name:<input id ='myname'>
<input type="button" id="btn" value="send to all">
</form>
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function(){
$('#btn').click(function(){
var username = $('#myname').val();
/*first post*/
$.post('multi1.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
$.post('multi2.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
});
});
</script>
</body>
multi1.php
<?php
echo "this is process1";
echo"and you have posted:".$_POST['name'];
?>
multi2.php
<?php
echo "this is process1";
echo"and you have posted:".$_POST['name'];
?>
Something like this:
let formID = $("uFormId");
formID.submit(function(event) {
event.preventDefault(); // Stop to call URL
$.ajax({url: "multi1.php", data: formID.serialize() ,type: 'POST', success: function(data) {
console.log("Response from multi1 PHP: " + data);
//OR
$('#display').innerText = data;
}
$.ajax({url: "multi2.php", data: formID.serialize(),type: 'POST', success: function(data) {
console.log("Response from multi2 PHP: " + data);
}
}
But, there are several art to make this event with javascript and you can finde a lot of them hier jQuery AJAX submit form
The below code is working fine for me:
<!DOCTYPE html>
<html>
<head>
<title>main form</title>
</head>
<body>
<form>
Name:<input id ='myname'>
<input type="button" id="btn" value="send to all">
</form>
<div id="display"></div>
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
var username = $('#myname').val();
/*first post*/
$.post('multi1.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
/*second post*/
$.post('multi2.php',{name:username},function(result){
$('#display').append("<br>"+result);
});
});
});
</script>
</body>
</html>
multi1.php:
<?php
echo 'Posted on multi1.php - '.$_POST['name'];
?>
multi2.php:
<?php
echo 'Posted on multi2.php - '.$_POST['name'];
?>
When I put 'test' in the textbox and hit 'send to all' button, the output I'm getting is:
Posted on multi1.php - test
Posted on multi2.php - test
Check the file names you are posting to and I assume that you are trying to access the posted variable from other php page without storing it.
In general, if you make an HTTP request (in your case, it is POST), the browser will send that value to the other page and will forget it and when you try to access the value from other pages (like, process1.php) it will return an empty string as it didn't store the variable.
So, a solution is to store the value in localstorage using javaScript and try accessing the variable from the other page.
here is the updated code
$(function(){
$('#btn').click(function(){
var $username = $('#myname').val();
window.localStorage.setItem('username', $username);
});
});
and get the stored value with
var $userName = window.localStorage.getItem('username')
you can know about it here and here
I have a weird problem. I have a form that populates with a button click event. This all works fine, except that once the form populates, it clears itself. Even Firebug gets cleared. I have stripped everything down to its most basic level, and cannot figure out what the issue is.
HTML:
<?php
require_once('../hyperlink.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Shipment Assignment</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<link rel="stylesheet" href="book.css">
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<link rel="stylesheet" href="../css/tabletheme/style.css" type="text/css" id="" media="print, projection, screen" />
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>
<script type="text/javascript" src="../barcode/jquery-barcode.js"></script>
<script type="text/javascript" src="../js/tablesorter.min.js"></script>
<script src="book.js"></script>
</head>
<body>
<div id="header">
<?php display_user_hyperlinks(); ?>
<?php include ('../version.php'); ?> | Tip: Shipping Info</p>
</div>
<form>
<fieldset>
<legend>Shipping Assignments</legend>
Enter the PO that you would like to review: <input id="po"/><input type="submit" id="getPo" value="Retrieve"/>
</fieldset></form>
<form id="result">
<div id="hide">
<div id="cl" class="width border">
CL<input id="cl"/>
</div>
<div id="recv" class="width border">
REC<input id="rec"/>
</div>
<div id="pricePd" class="width border">
<input id="price" placeholder="Price Paid"/>
</div>
<div id="box" class="border">
<input id="title" style="width: 445px;" placeholder="Title"/><br>
<input id="isbn10" style="width: 445px;" placeholder="ISBN10"/><br>
<input id="isbn13" style="width: 445px;" placeholder="ISBN13"/><br>
</div>
</div></form>
<div id="remain"class="border">
Qty Rem: <input type="text" id="qtyRem"/>
</div>
</body>
</html>
book.js
$(document).ready(function() {
$("#getPo").click(function() {
$.ajax ({
type: "POST",
url: "poInfo.php",
async:false,
dataType: "json",
data: ({po: $('#po').val()}),
success: function(data){
console.log(data);
$("#isbn13").val(data.isbn);
$("#isbn10").val(data.isbn10);
$("#title").val(data.title);
}
}); //END OF AJAX
}); // END OF GETPO FUNCTION
});
poInfo.php:
<?php
ini_set('display_errors',"1");
require_once ('../db.php');
$conn = db_connect();
$i=0;
$po = 'JJD090969';
$result = $conn->query("select * from ship_assign where po = '$po'");
while ($row = $result->fetch_assoc()) {
$isbn10 = $row['isbn10'];
$isbn = $row['isbn13'];
$azLow = $row['azLow'];
$buyback101 = $row['Buyback101'];
$textRecycle = $row['textBookRecycle'];
$textRush = $row['textBookRush'];
$bookStores = $row['bookStores'];
$textBooks = $row['textBooks'];
$bookJingle = $row['bookJingle'];
$cash4Books = $row['cash4Books'];
$bookbyte = $row['bookbyte'];
$sellBack = $row['sellBack'];
$cheggBs = $row['chegg'];
$valore = $row['valore'];
$powell = $row['powell'];
$amzBuyBack = $row['amazonBuyBack'];
$collegeBooksDir = $row['collegeBooksDirect'];
$result2 = $conn->query("select title from book where isbn13 = '$isbn'");
$row1 = $result2->fetch_assoc();
$title = $row1['title'];
} //END OF WHILE STATEMENT
$guides= array('isbn10'=>$isbn10,'isbn'=>$isbn,'title'=>$title);
$conn->close();
echo json_encode($guides);
?>
Everything works as it should, except that the form clears once populated. I am hard coding in the po that I want to use instead of having to type it in every time, but the result is the same either way. Any ideas on how to fix this??
Try this:
$(document).ready(function() {
$("#getPo").click(function(event) {
event.preventDefault();
$.ajax ({
type: "POST",
url: "poInfo.php",
// async:false, deprecated
dataType: "json",
data: ({po: $('#po').val()}),
success: function(data){
console.log(data);
$("#isbn13").val(data.isbn);
$("#isbn10").val(data.isbn10);
$("#title").val(data.title);
}
}); //END OF AJAX
}); // END OF GETPO FUNCTION
});
I'm having a problem with bootstrap 3 and typeahead.js from github https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#datasets
I'm trying to get my data from ajax to appear to suggest to a user when he types in my input field.
My console keeps giving me a message that says "Uncaught TypeError: Cannot read property 'replace' of undefined "
any help?
<html>
<head>
<!-- Bootstrap framework -->
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css" />
</head>
<body>
<div class="well">
<input type="text" class="span3 typeahead form-control" id="players" data-provide="typeahead">
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- main bootstrap js -->
<script src="../bootstrap/js/bootstrap.min.js"></script>
<!-- bootstrap plugins -->
<script src="../js/bootstrap.plugins.min.js"></script>
<!-- typeahead-->
<script src="../lib/typeahead/typeahead.min.js"></script>
<script type="text/javascript">
$(function(){
$('#players').typeahead({
name: 'players',
remote: function(query, cb){
$.ajax({
url: 'ajax/search.php',
type: 'POST',
data: 'query='+query,
dataType: 'JSON',
async: true,
success: function(data){
cb(data);
}
})
}
})
});
</script>
Ajax data file (PHP):
<?
if(isset($_POST['query'])){
include 'connect.php';
$query = $_POST['query'];
$sql = mysql_query("SELECT * FROM players WHERE name LIKE '%{$query}%'");
$array = array();
while($row = mysql_fetch_assoc($sql)){
$array[] = $row['name'];
}
echo json_encode($array);
}
?>
not 100% sure this is the issue, but perhaps try changing
data: 'query='+query,
to
data: {"query" : query},
I was having this issue and it fixed my problem
I am using ajax to run a test id, but it does not work with code: 200 error.
And since ajax is not returning a value, it keeps getting error and prints "failed"
The id of add_user.html is checked in real time through the ajax of id_check.js.
However, memid_check.php, which sends data from id_check.js, does not seem to run.
to confirm
memid_check.php
echo "<script> alert('test!!!'); </script>";
.....
But did not run.
All files are in one folder, so the path seems to be fine
id_check.js
$(function(){
var id = $('.id_tbox');
var pwd =$('.pwd_tbox');
var name =$('.name_tbox');
var email =$('.email_tbox');
var idCheck = $('.idCheck');
$(".memcheck_button").click(function(){
console.log(id.val());
$.ajax({
type: 'post',
dataType: 'json',
url: "memid_check.php",
data:{id:id.val()},
success: function(json){
if(json.res == 'good'){
console.log(json.res);
alert("사용가능한 아이디");
idCheck.val('1');
}
else{
alert("다른 아이디 입력");
id.focus();
}
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
console.log("failed");
}
});
});
});
memid_check.php
<?php
echo "<script> alert('test!!!'); </script>";
include "db_c.php";
$id = $_POST['id'];
$sql = "SELECT * FROM add_user WHERE id = '{$id}'";
$res = $database -> query($sql);
if( res->num_rows >= 1){
echo json_encode(array('res'=>'bad'));
}
else{
echo json_encode(array('res'=>'good'));
}
?>
add_user.html
<?php
include "database.php";
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, target-densitydpi=medium-dpi">
<link rel="stylesheet" href="add_user_style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/default.js"></script>
<link href="https://fonts.googleapis.com/css?family=Nothing+You+Could+Do&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Cinzel|Permanent+Marker|Rajdhani&display=swap" rel="stylesheet">
<script type="text/javascript" src="id_check.js"></script>
</head>
<body>
<div class="aus_portrait"></div>
<div class ="aus_form" align ="center">
<div class="aus_box">Sign Up</div>
<form action="loginP.php" method="post">
<p class = "id">ID</p><input type="text" name="id" class="id_tbox">
<p class = "pwd">PASSWORD</p><input type="text" name="pwd" class="pwd_tbox">
<p class = "name">MAIL</p><input type="text" name="email" class="email_tbox">
<p class = "email">NAME</p><input type="text" name="name" class="name_tbox">
<input type="submit" class="sub_button" value="Submit">
<input type="button" class="exit_button" value="Cancel">
<input type="hidden" name="idCheck" class="idCheck">
<div class="memcheck_button">중복확인</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function() { $(".exit_button").on("click", function(){ location.href="login.html"});}); </script>