jQuery ajax not posting values to php script - javascript

I am having a problem with posting a value to my php script via jQuery/ajax. I have searched around looking for a solution but cannot seem to figure it out why i am not getting the value posted.
here's my code.
page.html
<body>
input message:<p><input type="text" id="note" name="note" placeholder="enter something that made you feel this way"></p><br />
<p><button name="submitMessage">submit</button></p>
<script src="../js/jquery-3.1.1.js"></script>
<script src="../js/welcomeScript.js"></script>
<script> $( document ).ready(function() {
$('[name=submitMessage]').on('click', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../php/post-note.php',
data: {data: $('#note').attr('val')},
success: function(){
alert('added your note, you will now go to main app!');
window.location.href = "../home.php";
}
});
});
});
</script>
</body>
post-note.php
session_start();
$note = $_POST['data'];
if(isset($note) && isset($_SESSION['username'])){
$username = $_SESSION['username'];
$sqlMessage = "UPDATE mt_tbl SET note = '$note' WHERE userName = '$username'";
mysqli_query($conn, $sqlMessage);
echo "note: ".$note. " added to the dB!";
}

Instead of $('#note').attr('val') use $('#note').val()
Why? the reason is given below:-
console.log($('#note').attr('val'));
console.log($('#note').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "note" value = "2">

Related

Send dynamic data to php session after page has loaded

I'm just starting with php and I want to save the value of an HTML input to the php session.
i have tried achieving this using
<html lang="en">
<head>
<title>Log In</title>
</head>
<body>
<?php
session_start();
?>
<input id='email' type='text' placeholder='Email'>
<input type='submit' onclick='logIn()' value='Log In'>
</body>
<script>
function logIn() {
var email = document.getElementById('email')
<?php
$_SESSION['email'] = email;
?>
}
</script>
</html>
but php does not have access to the email variable i created in JavaScript.
I just want to save to the PHP session, data that was entered into an input field of a html site
Use Ajax how suggest from #Jeremy Harris
Script:
function logIn() {
var email = document.getElementById('email');
$.ajax({
url: "session.php",
type: "POST",
data: {
email:email
},
success: function(data){
window.location.href = WHERE YOU WANT;
}
}); }
PHP (session.php):
$email=$_POST['email'];
$_SESSION['email'] = $email;

How to call PHP function without reloading?

In my test work, I want to send data to DB by pressing "Save" button and stay at the same page. But this button after sending data to DB opens /file.php and shown "Success".
I tried to solve the task by JS I found, but it doesn`t work.
$('#sub').click( function() {
$.post( $('myForm').attr('action'), $('#myForm :input').serializeArray(), function(info){ $('result').html(info);} );
clearInput();
});
$('myForm').submit(function() {
return false;
});
function clearInput() {
$('#myForm :input').each( function() {
$(this).val('');
});
}
<html>
<head>
<title>
OneTwoThree
</title>
</head>
<body>
<form id='myForm' action="db.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<button id="sub">Send</button>
</form>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script/myjs.js" type="text/javascript"></script>
</body>
</html>
Callable PHP file:
<?php
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('mytestbd');
$name = $_POST['name'];
$age = $_POST['age'];
$q = "INSERT INTO `post`(`number`, `sometext`) VALUES ('$age','$name')";
if(mysql_query($q))
echo "Success";
else
echo "Fail";
?>
Try this block of js which includes some changes and adjustments (noted below):
$(document).ready(function() { // ready wrapper (was missing in your code)
$('#sub').click( function(e) { // added 'e'
e.preventDefault(); // added to stop buttons default behavior
$.post( $('#myForm').attr('action'), // added '#' to id locator
$('#myForm').serialize(), // reduced to just serialize the form data
function(info){
$('#result').html(info); // added '#' to id locator
clearInput(); // moved clear form into success callback
}
);
});
$('#myForm').submit(function() { // added '#' for id locator
return false; // this submit handler is most likely
}); // not needed, but doesnt hurt
function clearInput() {
$('#myForm :input').each( function() {
$(this).val('');
});
}
});
PS Once you get the submission process working, you will want to switch your use of mysql_* functions to either mysqli or PDO (as mysql_ is depreciated in php 5.5x, and removed in php7+).
Then after you switch, look into Prepared Statements to safeguard from sql injection attacks.
Just use a include statement.
if(mysql_query($q))
echo "Success";
include('yourFileWithTheForm.php');
else
echo "Fail";
?>

save data from javascript form

***********EDIT ************
This is now my code:
<script>
$(document).ready(function(){
$("#btn").click(function(){
$(".div2").append("<div class='tekst2'><div id='green'></div><textarea rows='8' cols='30' id='tekst' name='tekst' class='tekst'></textarea></div><br/>");
});
$("#btn2").click(function(){
$(".div3").append("<div class='tekst'><div id='red'></div><input class='nummer' id='nummer' type='text' name='nummer'></div><br/>");
});
var ele = new Array();
$("#btn1").click(function(){
$('.tekst').each(function(){
$('.nummer').each(function(){
ele.push($(this).val());
}); });
var send = ele.join(',')
request = $.ajax({
url: "form.php",
type: "post",
data: ele
//you can use this request object to know what's the status of your response
});
});
});
</script>
And this is the code for set the data to the database
<?php
require_once'config.php';
$tekst = $_GET['tekst'];
$query = "INSERT INTO draaiboek (tekst)
VALUES ('$tekst')";
$result = mysqli_query($mysqli, $query);
if($result) {
}
else {
}
Only i get empty rows in the database. Whats gone wrong?
**********END EDIT**************
I made a site to fill things in on an form. I have two buttons to get an extra form field on the screen. I want to save the data using the exact same markup somewhere. In a mysql database or locally. Does anyone know how you can store data and can later read out again with the same format? This is the code for get an extra form field:
$(function() {
$('#btnAddtoList').click(function(){
var newDiv = $('<div class="tekst2"><div id="green"></div><input class="formtijd" placeholder="Tijd" id="tijd" type="text" name="tijd"><textarea rows="6" cols="50" id="tekst" name="tekst" class="tekst"></textarea></div><br/>');
//newDiv.style.background = "#000";
$('body').append(newDiv);
});
$('#btnAddtoList2').click(function(){
var newDiv = $('<div class="tekst"><div id="red"></div><input class="formtijd" placeholder="Tijd" id="tijd" type="text" name="tijd"><input class="formtekst" id="nummer" type="text" name="nummer"></div><br/>');
//newDiv.style.background = "#000";
$('body').append(newDiv);
});
});
And this is the code for show on the screen:
<button id="btnAddtoList" class="btn btn-success">Nieuw tekst veld</button>
<button id="btnAddtoList2" class="btn btn-danger">Nieuw nummer veld</button><br/><br/>
<div id="tekst"></div>
<div id="tekst2"></div>
When I click on the button, there shows an new field. So it looks like:
May be not an efficient one but this is what I could write in short time
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
$("div").append("<input type='text' class='funfoo' placeholder='Fill me'/> <br/><br/>");
});
var ele = new Array();
$("#btn1").click(function(){
$('.funfoo').each(function(){
ele.push($(this).val());
});
var send = ele.join(',')
request = $.ajax({
url: "/form.php",
type: "post",
data: ele
//you can use this request object to know what's the status of your response
});
});
});
</script>
</head>
<body>
<button id="btn">Add fields</button>
<button id="btn1">Submit fields</button>
<div></div>
</body>
</html>
In this approach, you can simply append input values and then get all the values in them. Join all the values with comma and then dump in any single column (will save lot of other effort and you just need one column for all the values).
Now to display these values in the same format what you can do is, simply get the field value form DB, split them and add input fields for individual values. (you can do it in a loop I'll show you a demo).
--------------------------your display page --------------
//this is a pseudo code
<?php
$val = query to get that value (comma separated)from db
$val2 = $val.split(',');
for($i =0; $i<val2.lenght; $i++)
{
<input class='' value='<?php echo $val2[i] ?>'/>
}
?>
Hope this would help you :)

Accessing the PHP Variable in javascript

Good day to all of you Ma'am and Sir
I have a problem to my project (never mind the name of the project because it is for privately use and it is for security of the website).
The problem is I can not access or forward the PHP Variable value to the external javascript file.
this is the code in insert.php
<?php
$username = $_POST['username'];
?>
<input type="text" id="code"/>
<button id="con_btn"/>Continue</button>
this is the code in insert_auth.js
$(document).ready(function(){
$("#con_btn").click(function(){
var code = $("#code").val();
$.ajax({
method: "post",
url: "post.php",
data:{
code:code,
},
success: function(data){
$("#insertresult").html(data);
}
});
});
});
I just want to get the value of the $username from php file. Thanks in advance!
I take it as you already have the POST value : $_POST['username'];. So, I'd suggest you to store this value as a hidden input field.
<?php $_SESSION['username'] = $_POST['username']; // Store username in session ?>
<input type="text" id="code"/>
<button id="con_btn"/>Continue</button>
Now, in your JS, you can access this hidden field value:
$(document).ready(function(){
$("#con_btn").click(function(){
var code = $("#code").val();
var username = "<?php echo $_SESSION['username']; ?>" // Read username from session
$.ajax({
/* Other code */
});
});
});

How to send data via ajax?

I'm trying to learn how does Ajax work and how I can send data by Ajax. I'm getting no error and nothing is being echoed.
index.html
<input id="name" type="text" /><input id="button" type="button" value="Load" />
<div id="feedback"></div>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
page.php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
}
?>
ajax.js
$('#button').click(function(){
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: 'name='+name,
success: function(data){
$('#feedback').html(data);
}
});
});
I appreciate any help
You are missing an echo in your page php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
echo $name;
}
?>
also in your javascript send an object like this
data : { name : name}
should work
data : { name : 'John'}
you can check the success method is invoked or not invoked.
Also you need to echo something from php.
echo $name

Categories

Resources