I would like to know how a button submit can interact with AJAX to SELECT FROM data as a MySQL query without refreshing the page . I already have a text box interacting with AJAX so that the page does not refresh when the user inputs the text and presses enter but have no idea how to make the button do it my code below shows how im getting the text box to insert data without refreshing
Here is my script for the textbox
<div id="container">
About me<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
Here is the action
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$name = $_POST['name'];
$name= mysqli_real_escape_string($con, $name);
$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_COOKIE[$cookie_name]."'");
while($row = mysqli_fetch_assoc($q)){
//echo $row['id'];
$id = $row['id'];
}
$result=$con ->query=("REPLACE INTO about_user (about_me,number) VALUES ('".$name."','".$id."')");
$insert = $con->query($result);
echo "About Me Updated";
}
?>
Now all I need to do is have the below example of a button do something similar but instead of INSERTING just SELECT , how can i change the above script to allow a button to handle the action please?
<form
action="action_mail_view.php" method="post">
<input type="submit" class="button" name='msubmit' value="View Mail"/>
</form>
function callServer() {
$('#mail-button').on('click', function() {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {
name: info
},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
});
}
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
$('#mail-button').trigger('click');
};
});
});
<form action="action_mail_view.php" method="post">
<input type="submit" class="button" id="mail-button" name='msubmit' value="View Mail" />
</form>
You haven't showed us how you tried to make your button work so how can we give you feedback? Basically you want a similar ajax call that calls action_mail_view.php using the GET method
Ajax
$.ajax({
method: "GET",
url: "action_mail_view.php",
data: {},
success: function(results) {
var userinfo = JSON.parse(results);
//Todo: do what you want with the user's info
}
});
On the PHP side, you should first authenticate the user (not shown here), then SELECT her info from the DB and return it
action_mail_view.php
//Todo: authenticate
//this works with your setup, but it's a bad idea to trust
//a cookie value or anything else coming from the
//browser without verification
$username= mysqli_real_escape_string($con, $_COOKIE[$cookie_name]);
//get the user's info from your DB. By using a JOIN, we can execute
//just one query instead of two.
$sql = "SELECT t2.* FROM tbl1 as t1 "
."LEFT JOIN about_user as t2 "
."ON t1.id = t2.number"
."WHERE t1.username = $username";
//Todo: execute query. see what results you get and refine
// the SELECT clause to get just what you want
if($q = mysqli_query($con,$sql)):
$userinfo = mysqli_fetch_assoc($q);
//tell the browser to expect JSON, and return result
header('Content-Type: application/json');
echo json_encode($userinfo);
else:
//Todo: error handling
endif;
Related
I am trying to implement a message system in my project by using AJAX, but I have got some problems because I am new to AJAX.
The code below is able to send input data from the MsgMain.php file to MsgInsert.php perfectly. But when I try to get $_POST['msgSend'] from MsgMain.php on MsgInsert.php it fails.
AJAX Code is on MsgMain.php
$(document).ready(function(){
$("#chatBtn").click(function(){
$("#msgBtn").val("chat");
});
$("#pmBtn").click(function(){
$("#msgBtn").val("pm");
});
});
$(function() {
$("#msgBtn").click(function() {
var textcontent = $("#msgInput").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#msgInput").focus();
}
else
{
$.ajax({
type: "POST",
url: "msg/MsgInsert.php",
data: dataString,
cache: true,
success: function(response){
document.getElementById('content').value='';
$("#msgBtn").focus();
}
});
}
return false;
});
});
MsgMain.php file code just for the HTML form
<form action="MsgInsert.php" id="frmBox" name="msgSend" method="POST" onsubmit="return formSubmit();">
<div class="input-group ">
<input type="text" class="form-control" name="msgBox" id="msgInput" title="Enter your message" required>
<div class="input-group-btn">
<button class="btn btn-success w3-hover-white w3-hover-text-green" type="submit" id="msgBtn" title="Send your message" value="chat"><i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
</form>
MsgInsert.php file code, which works well when I remove the if statement of $_POST['msgSend']
<?php
if(!isset($_SESSION['login_user'])){
header("location: ../index.php"); // Redirecting To Home Page
}
if (isset($_POST['content'])) {
if (isset($_POST['msgSend'])) {
$conn = mysqli_connect("localhost", "root", "", "msg");
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$content=$_POST['content'];
mysqli_query($conn, "INSERT INTO `msgpm`(`id`, `msgFrom`, `msgTo`, `msg`) VALUES ('','bob','ram','$content')");
}
}
?>
Sorry if this type of question has already been asked.
You are not sending the msgSent attribute, according to this line in your JS:
var dataString = 'content='+ textcontent;
I can see only the content which you will be able to use via $_POST['content'].
Try this:
var dataString = 'content='+ textcontent + '&msgSent' + '<?php echo $_POST['msgSent']; ?>';
You have to pass the msgSend Parameter according to your implementation of MsgInsert.php like so:
$("#msgBtn").click(function () {
var textcontent = $("#msgInput").val();
if (textcontent == '') {
alert("Enter some text..");
$("#msgInput").focus();
}
else {
var dataString = 'content=' + textcontent + '&msgSend=1';
$.ajax({...});
}
});
Always think of escaping your content via i.e. prepared statements when saving user generated content into your database to avoid sql injection!
I have made a simple search bar in which on every .keyup() event,an asynchronous request goes to a php file which then fills the data in the bootstrap popover.
The problem is that in the popover,the data is filled only once,i.e.,when I type the first character,after that the same data is shown even after multiple .keyup() events.
Here is the code:
HTML:
<input type="text" data-placement="bottom" id="search" name="search1" class="search-box" placeholder="Search..." title="Results"/>
AJAX:
$("#search").keyup(function(){
console.log('erer');
//var searchString = $("#search").val();
var data = $("#search").val();
console.log(data);
var e=$(this);
//if(searchString) {
$.ajax({
type: "POST",
url: "do_search.php",
data: {search:data},
success: function(data, status, jqXHR){
console.log('html->'+data+'status->'+status+'jqXHR->'+jqXHR);
e.popover({
html: true,
content: data,
}).popover('show');
},
error: function() {
alert('Error occured');
}
});
//}
});``
PHP:
$word = $_POST['search'];
//echo $word;
//$word=htmlentities($word)
$sql = "SELECT FName FROM user WHERE FName LIKE '%$word%' ";
//echo $sql;
// get results
//$sql = 'SELECT * FROM Profiles';
$end_result = '';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
#$end_result.='<li>'.$row["FName"].'</li>';
#$_SESSION['fnamer'] = $row['Fname'];
#$end_result.='<li>'.'<a href =view_search.php>'.$row["Fname"].'</a>'.'</li>';
echo '<a href =view_search.php>'.$row["FName"].'</a>';
}
#echo $end_result;
}
Even though in the success parameter of the $.ajax,the data is being printed fine,i.e.,it changes as I enter different alphabets,but the popover content does not change.
Please provide some suggestions to resolve this problem.
The popover is already shown. This is not the correct way of changing the popover content dynamically.
Your code: https://jsfiddle.net/gsffhLbn/
Instead, address the content of the popover directly:
var popover = e.attr('data-content',data);
popover.setContent();
Working solution
Fiddle: https://jsfiddle.net/gsffhLbn/1/
I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with
I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.
I want show the result of my server page in the "result" div.
This is my scheme:
home.php
<script src="myscripts.js"></script>
<div id="loginform">
<div id="result"></div>
<?php include_once 'core.login.php'; ?>
</div>
myscripts.js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
core.login.php
<?php
// stuff about $db variable e other stupid things like $tool = new Tools etc...
$email = $_POST["email"];
$password = $_POST["password"];
// Initializing login process
if (isset($email) or isset($password)) {
$tool->decode($email, $password, $db);
}
?>
<form action="core.login.php" method="POST" id="login">
<fieldset>
<legend>Data login:</legend>
Email:<input id="email" type="email" name="email" placeholder="someone#example.com" required>
<br>
Password:<input id="password" type="password" name="password" required>
<br>
<input type="submit" value="Submit">
</fieldset>
</form>
class.php
public function decode($email, $password, $db) {
if ($stmt = $db->prepare("SELECT password FROM users WHERE email = ?")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($password_db);
$stmt->fetch();
if ($stmt->num_rows == 1) {
if ($password == $password_db) {
echo "Success";
} else {
echo "Error";
}
} else {
echo "Email didn't found!";
}
}
}
Without AJAX if i start the code normally it work, it give me the correct echo result ( success or error ) but when i use AJAX, nothing happen.
UPDATE
Ok guys the problem was the action url, my core file is in the folder core/core.login.php, now it display the page in the result div, but the page core show me this now:
Fatal error: Call to a member function decode() on a non-object in website on line 9
Maybe ajax don't pass the variables like object?
Try this js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $("#login").serialize(), // get the form data
type: $(#login).attr('method'), // GET or POST
url: $(#login).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
Try with that in your js file:
(Or Document)
$('#loginform').on('submit', '#login', function() {
//AJAX etc..
})
instead of :
$('#login').submit(function() {
//AJAX etc..
}