jQuery serialized data not being inserted into the database - php

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";
}
?>

Related

My Ajax code not refresh my favorite button

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

Ajax request shows complete but data not submitted

I have a simple modal window containing an input field. I am using jquery ajax to validate as well as submit data to database using php. The ajax request shows status code 200 ok but data doesnt get inserted and no success function executes. Does anyone notice any error? Need help
<script type="text/javascript">
$(document).ready(function() {
$("#add_location").click(function() {
var inputDiv = $('#inputDiv').val();
var dataString = 'location=' + inputDiv;
if (inputDiv == '') {
$('#error_message').html("Please enter a location");
} else {
$.ajax
({
type: "POST",
url: "add_location.php",
data: dataString,
success: function(data)
{
$("#error_message").empty();
$("#error_message").html(data);
}
});
}
return false;
});
});
</script>
add_location.php
<?php
$location = new dbhandler();
$ran_id = mt_rand(45287,98758);
if(isset($_POST)) {
$locationData = $_POST['location'];
try{
$location->create('shop_locations', array(
'r_id' => $ran_id,
'location' => $locationData,
));
echo "Location successfully added";
}catch(Exception $e){
die($e->getMessage());
}
}
create() is a method for inserting data
create($tableName, $fields = array());
You can try something
//js file
$.ajax({
url: "You_url",
type: "POST",
data: $("#form_name").serialize(),
headers: {
'Authorization' : 'JWT ' + token
}
})
.done(function (data) {
console.log(data);
})
.fail(function (data) {
console.log(data);
});
And echo post data in php file if you get anything. I was using JWT so I have used JWT here and token is the variable where I am storing my token
I think you're referring the wrong the DOM id. You probably have this formation.
<div id="inputDiv">
Location <input type="text" id="myInput"><br>
</div>
In this case inputDiv = $('#inputDiv').val() will be different with inputDiv = $('#myInput').val()

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

AJAX call not sending

I am trying to create my first AJAX call. All I am trying to do is send a message to my database that will hold a user_id, message, and date.
As of now nothing is even happening when I hit the submit button. Why is this not submitting and I'm not sure if I am creating the ajax call correctly.
What am I doing wrong?
My ajax call
$(document).ready(function () {
$("#submit_announcement").on("click", function () {
$user = this.value;
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: "username=" + $user,
success: function (text) {
if (text == "Error!") {
alert("Unable to get user info!");
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Payment Status Changed!');
$('.announcement_success').delay(5000).fadeOut(400);
alert(data);
} else {
var txtArr = text.split('|');
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
}
});
});
});
The Form
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<textarea rows="4" cols="50" id="announcement_message " name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<input type="button" class="contactButton" value="Add Announcement" id="submit">
</label>
</form>
PHP file insert_announcements.php
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('isi', $announcement_user_id, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
You have the jquery selector for your button wrong, change it to:
$("#submit").on("click", function(){
You are triggering the click for an element with id #submit_announcement which is different from the id of your form submit button. Change $("#submit_announcement").on("click", function(){
to
$("#submit").on("click", function(){
In your PHP you cannot echo between } and else
}
echo "Announcement was added successfully!";
else
Use one of below event bind method :
$(document).ready(function(){
$("#submit").on("click", function(){ console.log('reached'); /* code here */ });
$('#insert_announcements').on('submit',function(){ /* code here */ })
})
One of above approach should work . Your ajax code looks fine . just use one of above event bind wrapper and let the magic happen .
Update
check working fiddle here : https://jsfiddle.net/hfddcop0/
Mistakes you were making
1) specifying wrong submit button id . it is submit_announcement instead of #submit
2) Unknown variable defined called usermessage . I have replaced it with string value in fiddle .
payload should be like
data : {'message':message,'anothermessgae':another} , You were mentioning like data : {'message':message;} which is a syntax error .
Because you're not creating the function when the submit button is clicked. The button id is submit
So try:
$(document).ready(function(){
$("#submit").on("click", function(){
$user = this.value;
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: "username="+$user,
success: function(text){
if(text == "Error!"){
alert("Unable to get user info!");
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Payment Status Changed!');
$('.announcement_success').delay(5000).fadeOut(400);
alert(data);
} else {
var txtArr = text.split('|');
}
},
error: function(xhr, textStatus, errorThrown){
alert(textStatus + "|" + errorThrown);
}
});
});
});
You are not sending user_id, message, and date to server to get the response.
first get inputted values and then send.Like below:
var announcement_message = $("#announcement_message).val();
and instead of type,it should be method.Type in ajax is to define data type.
In html, remove method="post",define method only once.
$("#submit").on("click", function(){
var usermessage = $("#announcement_message).val();
var username = "ralph"; // let say you get the username value;
var date_now = Date.now();
$.ajax({
url:"insert_announcements.php",
method:"POST",
data:{
"user_id":username,
"message":usermessage,
"date":date_now
}
success:function(data){
console.log(data); // data object will return the response when status code is 200
},
error:function(){
console.log("error");//otherwise error if status code is other than 200.
}
});
});

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