i manage to prevent my modal form from closing after submiting value using
ajax jQuery without page refreshing,
but now my problem is when i fill in my modal form and click submit to update the data inside my database is not updating.
i think there's something wrong of my ajax code.
hope you can help me. thanks.
here is my code:
<form class="needs-validation " id="contact-form" action="index13.php" method="post" novalidate >
</form>
here is my index13.php code:
<?php
include_once ('connection.php');
if(isset($_POST['submit1']))
{
$username2 = $_POST['username2'];
$password1= $_POST['password1'];
$time=date("H:i:s");
$sql = "select * from visitor_att where uname = '$username2' and pass = '$password1'";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
if ($count == 0) {
echo "No Results";
} else{
while ($row = mysqli_fetch_array($result)) {
$username2 = $row['uname'];
$password1 = $row['pass'];
$fname=$row['fname'];
$lname=$row['lname'];
$InsertSql = "Update visitor_att set timeout = '$time' where uname = '$username2' and pass = '$password1'";
$res = mysqli_query($conn, $InsertSql);
}
}
}
?>
here is my ajax jQuery code:
<script>
$(function() {
var frm = $("#contact-form");
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr("post"),
url: frm.attr("action"),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
});
</script>
when i run it on console it shows Submission was successful.
but no data is inserted in database.
Looks like you need to add the id attribute to your form as your ajax call is bound to it...
<form id="contact-form" class="needs-validation" action="index13.php" method="post" novalidate >
Related
I want to stay same modal after submitting this form
generateBarcode.php:
<form action="savegenarateBarcode.php?id=<?php echo $d1; ?>" method="post">
savegenerateBarcode.php:
<?php
try {
session_start();
include('../connect.php');
$d1 = $_GET['id'];
$b = $_POST['serialnumber'];
$sqlm = "select *from product_item where serialnumber='".$b."'";
$query = $db->prepare($sqlm);
$user_array = $query ->execute();
}
How can I stay same generateBarcode.php(modal) after submitting this form?
I think you should use ajax because the form submit method reload the page.
var id = '<?php echo $d1; ?>';
$("#submit").click(function(){
$.ajax({
type: 'GET',
url: "savegenarateBarcode.php",
data:`id=${id}`
success:function(data){
alert(data);
}
});
return false;
});
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 got a simple ajax live search script that works fine when I type the keyword in my url and visit the php file. But for some reason when I type the keyword in my input field, nothing happens.
What am I doing wrong?
My input field on products.php:
<input type="search" name="keyword" class="producten-icon divider" placeholder="Zoeken..." id="s_search">
And further down the page I got my result div:
<div id="results"></div>
My ajax script:
<script>
$(document).ready(function () {
$("#s_search").on('keyup',function () {
var key = $(this).val();
$.ajax({
url:'includes/fetch_results.php',
type:'GET',
data:'keyword='+key,
beforeSend:function () {
$("#results").slideUp('fast');
},
success:function (data) {
$("#results").html(data);
$("#results").slideDown('fast');
}
});
});
});
</script>
My fetch_results.php:
<?php
include 'connection.php';
$conn = new Connection;
if($_GET['keyword'] && !empty($_GET['keyword']))
{
// Results names
$results = "SELECT `naam` FROM `producten` WHERE `naam` LIKE '%".$_GET['keyword']."%'";
$resultscon = $conn->query($results);
$resultscr = array();
while ($resultscr[] = $resultscon->fetch_assoc());
$eend = #array_map('current', $resultscr);
// echo '<pre>';
// print_r($eend);
// echo '</pre>';
$resultsoverzicht .= '<div style="height:100%;border:10px solid red;">';
foreach($eend as $result){
$resultsoverzicht .= '
<p>'.$result.'</p>';
}
$resultsoverzicht .= '</div>';
echo $resultsoverzicht;
};
?>
When I use the network inspector I don't see anything posted when typing in the input field. Which should be the case with keyup right?
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;
I am currently attempting to send form data via ajax to a php function but it does not appear to be sending it.
This is the HTML Form:
<form onSubmit="return registration();" id="registration_form">
<input type="email" id="email_address" name="email_address" class="inputTextFooter">
<input src="images/go.png" alt="Go" type="submit">
</form>
The AJAX:
function registration(){
if(!$('#email_address').val()){
alert("Empty");
}
else {
$.ajax( {
type: "POST",
url: "includes/registration_check.php",
data: $('#registration_form').serialize(),
success: function( response ) {
alert( response );
}
});
}
return false;
};
Finally the PHP:
$user_id = NULL;
$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';
$distinct_query = "SELECT distinct user_email FROM user_emails";
$result=mysql_query($distinct_query, $connection);
$rows = mysql_num_rows($result) - 1;
$distinct_result_array = array();
while($fetched_array = mysql_fetch_assoc($result))
{
$distinct_result_array[] = $fetched_array;
}
for ($loop = 0; $loop <= $rows; $loop++) {
if (in_array($user_email, $distinct_result_array[$loop])) {
echo "Email taken.";
break;
}
else{
}
}
$query = "INSERT INTO user_emails (user_id, user_email) VALUES ('".$user_id."', '".$user_email."')";
mysql_query($query, $connection);
echo "You have successfully registered and will be checked by administration.";
When I send the form it adds to the database but the email field is blank.
Replace
$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';
With
if(empty($_POST['email_address']))
{
echo "error";
exit;
}
else
{
$user_email = $_POST['email_address'];
}
And I advice you Use mysqli instead of mysql, also validate user input before inserting into database.
your function should have event.preventDefault() to restrict default form submit action
then only your ajax request get triggerred.
function registration(){
event.preventDefault();
if(!$('#email_address').val()){
alert("Empty");
}
else {
$.ajax( {
type: "POST",
url: "includes/registration_check.php",
data: $('#registration_form').serialize(),
success: function( response ) {
alert( response );
}
});
}
return false;
};
I think you might need to use PHP's parse_str() function to get serialized data
http://php.net/manual/en/function.parse-str.php