I've got a basic html form and a div under it called "response", the user enters a password, the script should check the database to find the username (works fine) then print the username in the "response" div under the form for further processing, but I cannot get the jQuery/Ajax bit working to submit the form and query to the database behind the scenes (I'm quite new to jQuery).
I've got this so far, can anyone help get it working please?
php (checkuser.php):
$pass = $_POST['password'];
echo $pass;
$con = new mysqli("--IP--", "--USER--", "--PASS--", "--DB--");
if (mysqli_connect_errno()) {
echo "A problem has occured, please come back later.";
exit();
}
if ($stmt = $con -> prepare("SELECT `username` FROM --DB-- WHERE `password`=?")) {
$stmt -> bind_param("s", $pass);
$stmt -> execute();
$stmt -> bind_result($user);
while ($stmt -> fetch()) {
echo "welcome ".$user;
}
return $user;
$stmt -> close();
}
$con -> close();
html:
<form id="pass_form" action="post">
<input id="form_pass" type="text" name="password" placeholder="Password Goes Here"><br><br>
<input id="form_submit" class="submit_btn" type="submit" value="Submit">
</form>
<div id="response"></div>
jQuery (in head):
$(function() {
$("#form_submit").click(function() {
$.ajax({
type: "POST",
url: "http://--SITE--/--FOLDER--/checkuser.php",
data: "password=" + $("#form_pass").val(),
success: function() {
// Not sure what to do here
}
});
});
});
You need to prevent the default form behavior and display the response from ajax request in the #response div
$(function() {
$("#form_submit").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "http://--SITE--/--FOLDER--/checkuser.php",
data: "password=" + $("#form_pass").val(),
success: function(result) {
$('#response').html(result);
}
});
});
});
Everything goes where you are Not sure what to do here.
success: function(response) {
alert(response);
}
Also, I am not sure why you have a return $user in your php. Comment that line out and test the above-mentioned code.
So response holds what the php echoed. You can now use that to do whatever you wish to do.
We rarely let the submit button do it's work. We kind of like to use it as a mere button while it is more than a button. So since you may be new let me introduce you to the submit button and event. The button is used to submit the form:
$(function() {
$("#pass_form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "http://--SITE--/--FOLDER--/checkuser.php",
data: "password=" + $("#form_pass").val(),
success: function(result) {
$('#response').html(result);
}
});
});
});
So we bind the a submit event handler to the form and the submit button takes it from there.
$("#form_submit").click(function(){
$("#response").show();
$.post( "http://--SITE--/--FOLDER--/checkuser.php", {
password: $("#form_pass").val(),
}).done(function( data ) {
$( "#response" ).html( data );
});
});
This will return whatever output your targeting page is going to output.
you don't really need a form to do this process
Related
I tried different code to have a favorite button who will change (image) when you click on it - favorite/unfavorite without refresh the page but it doesn't work. with this code when i click on favorite button, the page not reload but nothing change, the image (empty heart) doesn't change and nothing record in the data base...
// ************************* AJAX
<script type="text/javascript" src="https://ajax.googleapis.com. /ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("#refreshAjout").click(function(){
$.ajax({
type: "POST",
url: $("#refreshAjout").attr('action'),
success: function(retour){
}
});
return false;
});
});
$(function(){
$("#refreshSupp").click(function(){
$.ajax({
type: "POST",
url: $("#refreshSupp").attr('action'),
success: function(retour){
}
});
return false;
});
});
</script>
And this is my php code for the button and the function to add or remove data from DB
<?php
// If user not connected
if ($_SESSION['pseudo'] == NULL){
echo '<img src="../.. /images/empty-heart.jpg" class="ajouter"</img> ';
}
// If user connected
if (isset($_SESSION['pseudo']) && isset($_SESSION['pass'])){
// We check if the key exist in DB
$req="SELECT count(*) FROM favoris WHERE profil='".$test."'";
$res=mysql_query($req);
// if key not in DB we show empty heart button
if(mysql_result($res,0)==0 ) {
?>
<form method="post" action="">
<button type="image" id="refreshAjout" class="ajouter" value="" name="refreshAjout"></button>
</form>
<?php
// if key in DB we show pink heart
} else{ ?>
<form method="post" action="">
<button type="image" id="refreshSupp" class="supprimer" value="" name="refreshSupp"></button>
</form>
<?php
}
}
And finaly the function to put or remove the informations in DB
if (isset($_POST['refreshAjout']) ) {
$sql = "INSERT INTO favoris (id, client, profil, photo, prenom, reference, age, lien) VALUES('','$pseudo' ,'$pseudo$referenceBase','$photoBase','$prenomBase', '$referenceBase', '$ageBase','$lienBase')";
mysql_query($sql) or die('Erreur SQL ! '.$sql.'<br>'.mysql_error());
}
if (isset($_POST['refreshSupp']) ) {
$sql = "DELETE FROM favoris WHERE profil ='$pseudo$referenceBase'";
mysql_query($sql) or die('Erreur SQL ! '.$sql.'<br>'.mysql_error());
}
?>
You're not sending any parameters in your $.ajax calls, so $_POST will be empty. You need to use the data: option to send parameters.
You can combine both your submit buttons in a single call, since the can get the parameters from the element itself.
$(function() {
$("#refreshAjout, #refreshSupp").click(function() {
var newSrc = this.id == "refreshAjout" ? "../../images/pink-heart.jpg" : "../../images/empty-heart.jpg";
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: { [this.id]: this.value },
success: function(retour) {
$(".ajouter").attr("src", newSrc);
}
});
return false;
});
});
I am trying to make a form to insert data to database with jQuery, but there's no action happen and want to know where the problem is.
Here's the code I wrote, and I hope someone will help me find where the mistake is, and why there's no action on it.
index.html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="insert.js"></script>
</head>
<body>
<form id="form-search" method="post" action="index.html">
<input name="gov" id="gov" type="text" class="textinput required" maxlength="80" required><br>
<input name="area" id="area" type="text" class="textinput required" maxlength="80" required><br>
<button id="submit" type="button">insert</button>
</form>
</body>
</html>
insert.js code
$(document).ready(function(e) {
$('#submit').click(function() {
var gov =$('#gov').val() ;
var area =$('#area').val() ;
$.ajex({
type :'post' ,
data :{gov:gov,area:area},
url :"insert.php",
success :function(result) {
alert(result);
}
})
});
});
insert.php code
<?php
$con = mysqli_connect('localhost','user','pass','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
if($_REQUEST['gov']) {
$gov=$_REQUEST['gov'];
$area=$_REQUEST['area'];
$q="inser into gov values ('','$gov','$area')";
$query=mysqli_query($con,$q);
if($query){
echo "data insert " ;
}
}
?>
Look at the Networks' tab using the Developer Tools. Check if there's something happening when you press the submit button. Check for a status code.
This script (with your html) will submit the data (with console logs to the browser) to 'insert.php'. Please read the comments for explanations. If it still doesn't work, the problem probably lies in your PHP code (I don't work with PHP). The ajax is sending the data to 'insert.php', which should be coded to accept the data variables and return a json response back to the ajax function in the script.
// Remove the 'e' from .ready and place in the 'click' function - this is the 'event'
$(document).ready(function () {
$('#submit').click(function (e) {
// Stops the form from being submitted 'normally' (to index.html)
e.preventDefault();
// Check console in your browser (this can be removed when it works)
console.log('submit clicked');
// Define the data to be submitted with the ajax form
var submitData = { gov: $('#gov').val(), area: $('#area').val() };
$.ajax({
// Make sure your path to insert.php is complete - check console in browser to see if there is an error
url: 'insert.php',
// Make sure 'insert.php' accepts 'post' transactions
type: 'POST',
// This could be changed (when it works) to - data: { gov: $('#gov').val(), area: $('#area').val() },
data: submitData,
// Make sure 'insert.php' returns a json result
dataType: 'json',
success: function (result) {
// This can be removed when it works
console.log('ajax success');
},
beforeSend: function () {
// This can be removed when it works
console.log('ajax beforeSend');
// This can be removed when it works - this lists out the data submitted with the form
$.each(submitData, function (index, value) {
console.log('index: ' + index + ' value: ' + value);
});
},
complete: function () {
// This can be removed when it works
console.log('ajax complete');
},
error: function () {
// This can be removed when it works
console.log('ajax error');
}
});
});
});
I am having trouble recording a single data (deckName) from this form to my MySQL database. I read and tried all the solutions I found over the web, but I cannot get it to work. Doing the MySQL command from the PHPMyAdmin work fine.
I need to save in the deck table of the db (id, name, cards) the values.
Jquery/Ajax script:
<script>
$(document).ready(function(){
$(document).on('submit','.save',function(){
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: console.log('worked')
});
});
});
</script>
Form:
<div class="decklist">
<form method="post" id="decklist">
<input class="deck" id="deckN" type="text" value="Deck name"/>
<input class="save" type="submit" value="Save Deck"/>
</form>
<div class="list">
<ul class="d_list">
<li class='added_card' id='list_0'></li>
</ul>
</div>
</div>
submit.php:
<?php
if(isset($_POST["name"])&& strlen($_POST["name"])>0){
$deckName = $_POST["name"];
$cards = 0;
echo $deckName;
$conn = new mysqli("localhost:8080","root","","ken");
if($conn -> connect_errno){
die("Failed to connect: (". $conn->connect_errno. ")".$conn->connect_error);
}
$insert = $conn->query ("INSERT INTO `deck` (deck, cards) VALUES ($deckName, $cards)");
if ($insert){
echo 'Successfully saved '. $deckName;
$conn -> close();
}
}
?>
Also once I hit Save Deck for submit, the div get refreshed while I assume it shouldn't with ajax.
I tried using click instead of submit, and the console.log returned everything correctly from the ajax function and the div wasn't refreshing every time, but with submit logs don't show up anymore in console.
I don't get anything from the echo in submit.php, never.
Try using preventDefault; like so
$(document).on('submit','.save',function(e){
e.preventDefault;
Hope it solves your problem !
You have to put quotes around string values:
"INSERT INTO `deck` (deck, cards) VALUES ('$deckName', $cards)"
how about change js like this:
$(".decklist").on("click", ".save", function(){
$.post("submit.php", { name: deckName }).success(function(){
console.log('worked');
});
});
You need to bind on the form submit event :
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('.deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
$(document).ready(function(){
$("#decklist").on('submit',function(e){
e.preventDefault();
var deckName = $('#deck').val();
console.log(deckName);
$.ajax({
type: "POST",
url: "submit.php",
data: { "name": deckName},
success: function(response) {
console.log('worked')
}
});
});
});
it works form me, change $('#deck').val();
I am writing a website that needs to update a users credits so that it adds a javascript value to the existing credits in the database on a button click and I can't seem to find out how to do it (I'm very new to ajax so go easy...)
HTML:
<form method="post">
<input id="depositBtn" type="submit" value="Deposit">
</form>
jQuery
$( "#depositBtn" ).submit( function() {
$.ajax({
url: 'deposit.php',
dataType: 'json',
type: 'post',
data: {total: tot},
success: function(data) {
alert(data);
}
});
});
PHP
$db = new PDO('mysql:host='.$servername.';dbname='.$dbname.';charset=utf8', $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$getCredits = $db->prepare("SELECT credits FROM userinfo WHERE steamid = ? ");
$getCredits->bindParam(1, $steamid, PDO::PARAM_INT);
$credits = $getCredits->fetch(PDO::FETCH_ASSOC);
$allcredits = $credits['credits'];
$bank = $_POST['total'];
$result = array(
'success' => true,
'credits' => $bank+$allcredits
);
echo json_encode($result);
It seems like there is no much wrong with your coding, specially regarding the JavaScript which you have put!
But I suggest you the following:
(Assuming: that your alert box shows what is the response from the server in the success block.)
$( "#depositBtn" ).submit( function(e) {
e.preventDefault();
console.log('total : '+tot);
$.ajax({
url : 'deposit.php',
type : 'POST',
dataType : 'json',
data : {total: tot},
success : function(data) {
alert(data);
}
});
});
What my change to your code is:
1st Change:
$( "#depositBtn" ).submit( function(e) { // you catch the submit button click event.
e.preventDefault(); // you prevent the default event of the submit button
2nd Change:
console.log('total : '+tot); // which will print your 'tot' variable to web browser
// console before it is sent to your PHP Script.
3rd Change:
type : 'POST', // You have put 'post' for the type.
For further reading on preventing the default events read the following question thread!
Note:
Don't forget to check your JS Variables before you send them to the any server side scripts written in any lang. (PHP, Java, Rubi, ...)
Hope this helps!
Cheers!
What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});