My Ajax code not refresh my favorite button - php

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;
});
});

Related

Form not saving data to MySQL database

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();

Update Mysql records using Ajax/Json isn't working

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);
}
}
});
});
});

Submit Basic Form Using jQuery Ajax

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

jQuery serialized data not being inserted into the database

I have three things going on.
I am sending information to jQuery using the following HTML form.
<div id="note_add_container">
<form id="note_add" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="location" placeholder="location" />
<button id="submit_note">Add note!</button>
</form>
</div>
This is the jQuery script that I am using to post such serialized information into the database.
$('button').click(function () {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(){
alert("Done");
}
});
});
This is the PHP that inserts the information into the database.
$name = $_POST['name'];
$location = $_POST['location'];
$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
This does not work. I click the button and nothing happens. The alert does not fire. Can anyone lead me the right direction as to why my code is not working?
This does not work. I click the button and nothing happens. The alert
does not fire
Are you totally sure that click handler works? You must ensure that it works firstly, like,
$('button').click(function () {
alert('It works');
});
If it works, then you can move on. Otherwise check if its inside DOMReady $(function(){ ... }) and that jquery.js is loaded.
Assuming that it works,
How do you know what your PHP script returns? You simply assume that it "should work", here:
success: function(){
alert("Done");
}
success() method actually holds a variable that is response that comes from the server side. It should be rewritten as,
success: function(serverResponse){
alert(serverResponse);
}
As for PHP script,
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
You only handling failure by 'echoing' error messages. You do not handle a situation when mysqli_query() returns TRUE. You should send something like 1 that indicates success.
And finally your code should look like this,
$('#submit_note').click(function() {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(serverResponse) {
if (serverResponse == "1") {
alert('Added. Thank you');
} else {
// A response wasn't "1", then its an error
alert('Server returned an error ' + serverResponse);
}
}
});
});
PHP:
$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die(mysqli_error($connection));
} else {
die("1"); // That means success
}
/**
* Was it $connection or $link?! Jeez, you were using both.
*
*/
The callback function that you specified in your $.ajax call will only fire when a response is received from the server. Since you never send anything back to the client from the server after the data is inserted into the database, the client never calls alert("Done");. Add a line to your PHP file that sends a response to the client after a successful SQL insertion. The response can be as simple as a JSON object that says {'status': 'success'}.
You should apply a better way to handle your form. The serialize() helps, but it is better to work the data into a JSON string. When using JSO you will also need to set the dataType in the ajax call.
$('#note_add').submit(function (event) {
event.preventDefault();
var formdata = $('#note_add').serializeArray();
var formobject = {};
$(formdata).each(function (event) {
formobject[formdata[event].name] = formdata[event].value;
});
var data = {
action: "formsend",
json: JSON.stringify(formobject)
};
//* * send with ajax * *
function sendajax(data) {
var deferred = $.ajax({
method: "post",
url: "ajax.php",
dataType: "json",
data: data
});
return deferred.promise();
}
sendajax(formdata).done(function (response) {
console.log(response);
if (response.success == true) {
alert("Done!");
}
})
});
catch with PHP
if(isset($_POST['action']) && $_POST['action'] == 'formsend') {
$data = json_decode($_POST['json'];
// here you can now access the $data with the fieldnames
$name = $data->name;
$location = $data->location;
// Write to the database
$sql = "INSERT INTO get (name, location) VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
die('Error: '.mysqli_error($link));
}
if (mysqli_affected_rows($connection) > 0) {
echo json_encode(array("success" = > true, "message" = > "data is submitted"));
} else {
echo json_encode(array("success" = > false, "message" = > "an error occurred"));
}
}
Add the following lines to your php file to send the response back:
HttpResponse::setCache(true);
HttpResponse::setContentType('text/html');
HttpResponse::setData("<html>Success</html>");
HttpResponse::send();
flush();
change the ajax call as follows to see the result:
$('#submit_note').click(function () {
$.ajax ({
type: "POST",
url: "post.php",
data: $('#note_add').serialize(),
success: function(respData) {
console.log('Response:', respData)
alert("Done");
}
});
});
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<title></title>
</head>
<body>
<div id="note_add_container">
<form id="note_add" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="location" placeholder="location" />
<button id="submit_note">Add note!</button>
</form>
</div>
<div id="response"> </div>
</body>
<script type="text/javascript">
$("#submit_note").click(function() {
var url = "post.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#note_add").serialize(), // serializes the form's elements.
success: function(data)
{
$('#response').empty();
$('#response').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</html>
post.php
// Insert here your connection path
<?php
if((isset($_REQUEST['name']) && trim($_REQUEST['name']) !='') && (isset($_REQUEST['location']) && trim($_REQUEST['location'])!=''))
{
$name = addslashes(trim($_REQUEST['name']));
$location = addslashes(trim($_REQUEST['location']));
$sql = "INSERT INTO get (name, location) VALUES ('".$name."', '".$location."')";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($link));
}
echo "1 record added";
}
?>

cannot send data by using ajax

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}

Categories