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();
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;
});
});
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);
}
}
});
});
});
I have a button which calls a modal box to fade into the screen saying a value posted from the button then fade off, this works fine using jquery, but I also want on the same click for value sent from the button to be posted to a php function, that to run and the modal box to still fade in and out.
I only have this to let my site know what js to use:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
I'm still new so sorry for a rookie question, but will that allow ajax to run, or is it only for jquery?
The current script I'm trying is: (Edited to be correctly formed, based on replies, but now nothing happens at all)
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.ajax
({
url: 'reservebook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
Though with this the modal box doesn't even happen.
The php is, resersebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
and to be thorough, the button is:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>"><button>Reserve Book</button></div>
I'm new to this and I've looked at dozens of other similar questions on here, which is how I got my current script, but it just doesn't work.
Not sure if it matters, but the script with just the modal box that works has to be at the bottom of the html body to work, not sure if for some reason ajax needs to be at the top, but then the modal box wouldn't work, just a thought.
Try this. Edited to the final answer.
button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button class="reserve-button">Reserve Book</button>
</div>
script:
<script>
$('.reserve-button').click(function(){
var book_id = $(this).parent().data('id');
$.ajax
({
url: 'reservebook.php',
data: {"bookID": book_id},
type: 'post',
success: function(result)
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
reservebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['bookID']))
{
$bookID = $_POST['bookID'];
$result = mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
if ($result)
echo "Book #" + $bookId + " has been reserved.";
else
echo "An error message!";
}
?>
PS#1: The change to mysqli is minimal to your code, but strongly recommended.
PS#2: The success on Ajax call doesn't mean the query was successful. Only means that the Ajax transaction went correctly and got a satisfatory response. That means, it sent to the url the correct data, but not always the url did the correct thing.
You have an error in your ajax definitions. It should be:
$.ajax
({
url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
You Ajax is bad formed, you need the sucsses event. With that when you invoke the ajax and it's success it will show the response.
$.ajax
({
url: 'reserbook.php',
data: {"book_id":book_id},
type: 'post',
success: function(data) {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
}
Edit:
Another important point is data: "book_id="+book_id, that should be data: {"book_id":book_id},
$.ajax
({
url: 'reservebook.php',
data: {
jqbookID : book_id,
},
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
Try this
i need in sert data by ajax , i have two pages, once is form that have icon that i click on it and send me to other page and insert new data
here the ajax code
<script type="text/javascript">
$(function() {
$("#dialog1").click(function() {
$('#welcome').slideToggle('#loginhandle');
$('#loginhandle').show("slow");
var name = $("input#ausers_ID").val();
var dataString = 'ausers_ID='+ ausers_ID ;
$.ajax({
type: "POST",
url: "OpenCashier.php",
data: dataString,
success: function(msg) {
$('#loginhandle').slideToggle('#msgreturn');
$('#msgreturn').show("slow");
$('#msgreturn').html(msg)
.hide()
.fadeIn(1500, function() {
});
}
});
return false;
});
});
</script>
when i click this bottom
<input type="submit" id="dialog1" name="dialog1" value="Insert" />
we must call this page
<? session_start();
include("sec.php");
include("../include/connect.php");
include("../include/safe.php");
if($_POST["dialog1"]){
// Every thing is OK
$ausers_ID=$_POST["ausers_ID"];
$cashiers_CashierOpenDate=date('Y/m/d');
$query="INSERT INTO `cashiers` ( `cashiers_CashierID` , `cashiers_CashierOpenDate` , `cashiers_User` , `cashiers_Status` , `cashiers_Delete` ) VALUES ('', '$cashiers_CashierOpenDate', '$ausers_ID', '0','0');";
mysql_query($query);
$num=mysql_affected_rows();
if($num==1)
$message="Account was added successfully";
else
$message=$_POST["dialog1"]." Account is already exists in database";
}
?>
but data cannot insert why !!!
You missed to include the "dialog1" parameter used in your PHP code.
I would suggest to change your data to sent to :
var dataString = {ausers_ID : ausers_ID, dialog1 : true}
Ok, so I have this search box in which people typein a food item. When they press the button I need that input to be send to a .php file. That php file will look op the calories of that food item (thats in my database) and output the food item name and calories. All this need to be done without reloading the page so I started figuring out how JQuery works.
However I am stuck, I don't know what to put in the data field of the jquery function and how I can 'catch' that data in the .php file. Can someone give me an idea? thanks a lot! (see the ??????'s for things i don't understand). Also, the data that comes back needs not to be in an alert box in the end, but update some table on my page, how can i do this? which JSON (?) Jquery function do I need?
what I have up until now:
in head:
<script type="text/javascript">
function contentDisp()
{
$.ajax({
type: 'POST',
url: 'getFood.php',
data: '????????',
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
and in body:
<form autocomplete="off">
<p>
Product:
<input type="text" name="food" id="food" class="food_name_textbox" onmouseover="javascript: this.className='food_name_textbox_mouseover';" onmouseout="javascript: this.className='food_name_textbox';" / >
</p>
<button id="zoek" type="button" onClick="contentDisp();">Zoek</button>
</form>
and in getFood.php:
<?php
require_once "config.php";
$id = "??????"
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
$.ajax({
type: 'POST',
url: 'getFood.php',
data: {'foodnametextbox' : $('#food').val() },
datatype: "json",
success: function(data){
$('#table').html(data);
}
});
<?php
require_once "config.php";
$id = $_POST['foodnametextbox']; //escape and validate this input before using it in a query
$result = mysql_query("SELECT * FROM voedingswaarden WHERE voedsel='$id'");
$row = mysql_fetch_array($result);
echo json_encode($row);
?>
<script type="text/javascript">
function contentDisp()
{
var textSearch = $("#myText").text();
$.ajax({
type: 'POST',
url: 'getFood.php',
data: textSearch,
success: function(data){
alert("Data Loaded: " + data);
}
});
}
</script>
PHP:
$id = $_POST['textSearch'];