I am curious to know if it's possible that I can have a div reload like a window does. The reason for this is I have a forum but I don't want a full page reload after four is completed. So I was wondering if just the elements that are in that div or forum section could do a background reload or just load by them self when the submit button is pressed.
This is in a file called forum where the information gets typed in. I want it to not reload the page but stay on that forum and still send the data to the database.
<html>
<body>
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input type="submit" value="Submit" />
</form>
<div id = "load_results"></div>
</body>
</html>
This is sending the information to the database but I want it to be done discreetly.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['firstname'];
$sql = "INSERT INTO MyGuests (firstname) VALUES ('$value')";
if ($conn->query($sql) === TRUE) {
echo "<a href=https://twitter.com/angela_bradley>My Twitter</a>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Yes, there is a way. It is called AJAX - but, not to worry, it's pretty simple.
Your code will look something like this:
HTML:
<form action="demo.php" method="post" />
<p>Input 1: <input type="text" name="firstname" /></p>
<input type="submit" value="Submit" />
</form>
js/jQuery:
$(function(){
$('form').submit(function(evt){
//next line stops form submission from sending you to `demo.php`
evt.preventDefault(); //evt stands for "event" - can be anything. I use e.preventDefault()
var fn = $('[name=firstname]').val();
$.ajax({
type: 'post',
url: 'demo.php', //send data ONLY to demo.php -- page stays as it is
data: 'first='+fn,
success: function(d){
if (d.length) alert(d);
}
}); //END ajax
}); //END document.ready
demo.php
<?php
$fn = $_POST['fn'];
//Do your database insert here
//If you wish, you can return some data to the AJAX's success function:
echo 'You submitted: ' .$fn;
Here are some posts with simple AJAX examples:
AJAX request callback using jQuery
Related
I want to run insert.php query if button name with "addUser" is submitted i don't know how to pass addUser name parameter using AJAX to insert.php file where it check if button is submitted or not .
if i remove if statement in insert.php file this is inserting users to database but if directly visit insert.php its inserting empty records in table
i want to prevent entry of empty records in table if i visit insert.php directly .
index.html
<form method="post" id="addForm">
Username :<input type="text" name="username" id="userName" />
Passkey :<input type="password" name="passkey" id="passKey"/>
<br/>
<input type="submit" name="addUser" id="submitBtn" value="Inser New User"/>
</form>
<script>
$("#addForm").submit(function(e){
let userNameZ = $("#userName").val();
let passKeyZ = $("#passKey").val();
$.ajax({
url:'insert.php',
type:'POST',
data: {userName:userNameZ,passKey:passKeyZ},
success: function(resp) {
if(resp == "inserted") {
$("#addForm").trigger("reset");
alert("New user inserted");
} else {
alert("Something went wrong");
}
}
});
});
</script>
insert.php
<?php
$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");
if(isset($_POST['addUser'])){
$userName = trim($_POST['userName']);
$passKey = trim($_POST['passKey']);
$query = "INSERT INTO users (username,passkey) VALUES (:userName,:passKey)";
$stmt = $conn->prepare($query);
$stmt->execute(array(':userName'=>$userName, ':passKey'=>$passKey));
if($stmt) {
echo "inserted";
} else {
echo "not inserted";
}
}
?>
Change this if(isset($_POST['addUser'])){
to
if(isset($_POST['userName']) && isset($_POST['passKey'])){
OR in ajax, change
data: {userName:userNameZ,passKey:passKeyZ,addUser:1},
Notice: ,addUser:1
Adding answer to your comment
what if i have more than 10 values to be submit
.
You can use $("#addForm").serialize() and pass directly to data. Like
data: $("#addForm").serialize(),
I'm unable to make a call to an ajax function, shown below (index.php):
<script type="text/javascript">
$('.show_more').on('click',function (e){
$.ajax({
type:'POST',
url:'gallery_controller.php',
success:function(html){
$('.content').append(html);
}
});
});
my button click is here (index.php):
<form action="" method="post">
<button type="submit" class="show_more" name="next">Next</button>
</form>
this is my php script (gallery_controller.php):
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password, "dbgallery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT imagefile FROM tbl_images ORDER BY id DESC LIMIT 10 OFFSET 0");
while($row = $result->fetch_assoc()) {
echo '<h1>'.$row["imagefile"].'</h1><hr />';
}
?>
it seems to simply do nothing, i've tried a few things and nothing appears to work.. im wondering if ajax even works at all on my server.. i am a complete noob.
Do you need a form for that button?
If you wrapped the button into a form for W3C validity issues it's ok, you can simply change your button type attribute from type="submit" to type="button".
Please check the following complete code. I think "e.preventDefault();" is missing in your code.
<html>
<head>
<title>Test</title>
</head>
<body>
<form action="" method="post">
<button type="submit" class="show_more" name="next">Next</button>
</form>
<div class="content">
</div>
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<script>
$('.show_more').on('click',function (e){
e.preventDefault();
$.ajax({
type:'POST',
url:'gallery_controller.php',
success:function(html){
$('.content').append(html);
}
});
});
</script>
</body>
</html>
Hi there am a beginner in php and ajax, was trying to create a simple admin page which only submit a message and the message get stored in a mysql database. (via ajax ) however it seems that the no data is being parse through when I hit the submit button(I coded it so that when the submit button is pressed, the message would be send without the page refreshing).
Could someone check to see where my error could be? thank you
admin.php
<!DOCTYPE html>
<html>
<head> <!--inseart script here -->
<script type= "text/javascript" src="js/jquery.js"></script>
</head>
<body>
Message: <input type="text" name="message" id= "message_form"><br>
<input type="submit" id= "submit_form" onclick = "submit_msg()">
<script type= "text/javascript" src="js/func_submit_msg.js"> </script>
</body>
</html>
I have created a separate function file called func_submit_msg.js
//this is a function file to submit message to database
$(document).ready(function submit_msg(){
alert('worked');
$.ajax({
type: "POST",
url: "submit_data.php"
data: { message: message_form},
})
}
a connect.php file is created to connect to mysql database
<?php
$host = "localhost";
$user = "root";
$pass = ""; // phpMyAdmin mysql password is blank ? i believe
$database_name = "test"; //
$table_name = "test_table_1"; //table that will be accessing
//connect to mysql database
$db = new mysqli($host, $user, $pass, $database_name);
//check connection?
if ($db -> connect_error) {
die("error mysql database not connected: " . $db -> connect_error);
}
else {
echo "connected successfully" ;
}
?>
a submit_data.php file is created to submit to database
<?php
include "connect.php";
$insert_data=$db-> query ("INSERT INTO test_table_1(message) VALUES ('$message_form')");
if ($db->query($insert_data === TRUE) ){
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
error checking code to check whether database was inserted correctly doesn't even echo out whether it is successful or not.
Updated
submit_data.php as per # Maximus2012 suggestion
<?php
include "connect.php";
$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ($_POST['message_form'])");
if ($insert_data === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
No error display but there isn't any data being recorded in the database still.
You should start by adding your success callback to your Ajax: (if you havent already)
$(document).ready(function(){
$('#submit_form').on('click', function(e){
e.preventDefault();
message_form = $('#message_form').val();
$.ajax({
type: "POST",
url: "submit_data.php",
data: {message: message_form},
success: function(data) {
$('#result').html(data);
},
error:function(err){
//handle your error
alert('did not work');
}
});
});
});
Here we use .on() as the preferred method of attaching an
event handler function
We then use .val() to get the value of the message input field
and store it in a variable to be used for POSTing to the submit_data.php script
e.preventDefault() is used so that the default event is cancelled
when click the submit button
In your html, add an element that the result can be returned to: (#result)
<html>
<head>
<script type= "text/javascript" src="js/jquery.js"></script>
<script type= "text/javascript" src="js/func_submit_msg.js"></script>
</head>
<body>
<form action="" method="POST">
Message: <input type="text" name="message" id="message_form"><br>
<input type="submit" id="submit_form">
</form>
<div id="result"></div>
</body>
</html>
Here we wrap your input in a form with the method and action
properties to ensure that the name attributes are able to be used in
POST requests
In your PHP (submit_data.php) you need to assign a value to $message_form before using it:
<?php
include "connect.php";
$message_form = $_POST['message'];
$insert_data=$db->query("INSERT INTO test_table_1(message) VALUES ('$message_form')");
if ($insert_data === TRUE ){
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $cdb->error;
}
$db->close();
?>
If all goes well, you should get some kind of result from this.
I am making a question/status posting system using JQuery and Ajax however an error is being displayed "Notice: Undefined index: status in C:\xampp\htdocs\deadline\data.php on line 5" which is my line of code "$var = $_POST['status']; "
My system works as you have to log in to post a question(using sessions) BUT the issue is with my JQuery/AJAX script as the data that I have on homepage.php is not being sent to data.php (from my understanding which is why my index 'status' is undefined).
MY CODE
<?php
include("connection.php");
session_start();
if(isset($_SESSION['user_id']) && $_SESSION['user_id'] != "") {
}
else {
header("location:login.php");
}
$sid = $_SESSION['user_id'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM `users` WHERE id='{$sid}'";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
$fname = $result['fname'];
$lname = $result['lname'];
$time = time();
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = 'status='+status;
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
</head>
<body>
<div id="global">
<form action="" onsubmit="return false">
<textarea id="status"></textarea>
<button id="postbutton">POST</button>
LOGOUT
</form>
<br/>
<br/>
<div id="allstatus">
<!-- SKELETON -->
<div id="status">
<div id="statuspic">
</div>
<div id="statusinfo">
<div id="statusname">JOnathan</div>
<div id="statustext"> this is the question</div>
<div id="statusoption"><button id="likestatus">LIKE</button></div>
<div id="statusoption"><button id="commentstatus">COMMENT</button></div>
<div id="statusoption"><button id="sharestatus">SHARE</button></div>
<div id="statusoption"><button id="statustime">TIME</button></div>
</div>
</div>
<!-- SKELETON -->
</div>
</div>
</body>
</html>
<?php
$var = $_POST['status'];
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'forum';
//connecting
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
} else {
echo " success";
}
$sql = "INSERT INTO `question`(id, question) VALUES ('', '{$var}')";
$result = $conn->query($sql);
if($result) {
echo "inserted successfuly";
}
else {
echo "failed: " . $conn->error;
}
echo " the text: " .$var. " has been added to database.";
?>
HOW IT SHOULD WORK
I want to use JQuery/AJAX on my homepage.php to send data to data.php and that data gets returned back to homepage.php. On success to be displayed in my div #statustext.
Meaning when i write a question in textarea input field the data gets stored in database and retrieved and displayed in my div on the browser.
Please help me thanks..
you should change your script like below. Ajax sends data to url in a serialize manner either you have to use form serialize which will send all the fileds info to your php url other wise if you have to send only one field value then you can do this change
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
//children code
var status = $("textarea#status").value();
if(status == "") {
return false;
}
var data = {'status='+status};
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").html(data);
}
});
});
});
</script>
First of all use .val() not .value() when you getting value of your message. Second mistake - is using two id = "sattus". Id of elements must be unique or use class = "" for ident your class of elements.
Don't give same id to more then 1 html element !
In your code :
<textarea id="status"></textarea>
and
<div id="status">
both contains same id ! Please correct it first.Also In your code as Spencer mentioned in his answer that add name attribute with value "status". No doubt as you are using jQuery selector it should pick up correct one,though you can just alert it before sending the request using AJAX.
also set data variable as var data = {status : status};
POST uses name and not id so change this:
<textarea id="status"></textarea>
To this:
<textarea name="status"></textarea>
For the data make sure it's the data for your form, and add method="post" to it so it can send POST data. For example if you gave your form an id of yourForm:
HTML
<form action="" method="post" id="yourForm" onsubmit="return false">
JS
$.ajax({
...
data: $("#yourForm").serialize(),
...
});
Is there anyway to load the newly inserted rows to the database without refreshing the page using jQuery? I am able to send the data to the database without refreshing using jquery but I am stuck at showing that data back without refreshing the page. How do I display the data from the table without refreshing page and make it appear under the table in index.php which I have to display the retrieved data? Thanks
This is my index.php
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
$.ajax({
type: "POST",
url: 'send.php',
data: "user=" + $('#user').val() + "&comment=" + $('#comment').val(),
success: function(data){
$('input[type=text]').val('')
$('#status').html(data);
}
});
});
});
</script>
</head>
<body>
<div>
<input type="text" name="user" id="user">
<input type="text" name="comment" id="comment">
<input name="submit" type="submit" id="submit">
<div id="status"></diV>
</div>
<br>
<?php
$con=mysqli_connect("localhost","root","","user");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM comments");
echo "<table width='640' >
<tr>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr >";
echo "<td style='vertical-align:text-top'>" . $row['user'] . "</td>";
echo "<td><br><br><br>" . wordwrap($row['comment'], 90, '<br>',true) . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
And here is my send.php which submits the data to the table.
<?php
$mysqli = new mysqli("localhost", "root", "", "user");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$username = $_POST["user"];
$comment = nl2br($_POST['comment']);
$stmt = $mysqli->prepare("INSERT INTO comments (user, comment) VALUES (?,?)");
$stmt->bind_param('ss', $username, $comment);
$stmt->execute();
echo"comment posted successfully";
?>
This is a brief example for fetching data from a mysql database using JQuery AJAX and php. JQuery AJAX allows us to update a page's content without reloading the page:
http://openenergymonitor.org/emon/node/107
http://viralpatel.net/blogs/jquery-ajax-tutorial-example-ajax-jquery-development/
make send.php send you back the data you need to load the newly inserted row.
Let's say you inserted a comment that says "Hello world". If nothing goes wrong, send.php could, for instance, echo the content of the comment (Hello world in this case), and you could make use of that in the success function (from the data parameter).
look at the first answer in this question, might be useful.
You should append the new comment to the table with jquery in the success callback function of your ajax request.
To append:
$("table").append("<tr><td style='vertical-align:text-top'>"+$('#user').val()+"</td><td><br><br><br>"+$('#comment').val()+"</td></tr>");
Keep the thing you want to append in one line of code and make sure you don't clear the values of #user and #comment before you include them to the append string.