I am really new to AJAX/jQuery and PHP, and im trying to work on a little project that writes your daily weight to a Db which then is displayed later on with graphs etc.
I would like when the user submits the form for his or her weight that it displays a pop up message but for whatever reason, the AJAX/Jquery script doesn't seem to be doing anything with the php file therefore no info gets added into the database.
Here is the HTML Form: (index.html)
<form id="ajax-form" method="post" action="connection.php">
<div class="columns field">
<div class="column control is-half is-offset-one-quarter">
<input
class="input"
id="weight"
name="weight"
type="text"
placeholder="Enter your weight for the day"
/>
</div>
</div>
<div class="center-test">
<div class="field">
<div class="control">
<span class="select">
<select name="person">
<option value="Ayush">Ayush</option>
<option value="Sheri">Sheri</option>
</select>
</span>
</div>
</div>
</div>
<input type="date" name="weightdate" id="weightdate" />
<div class="field column is-half is-offset-one-quarter">
<button
type="submit"
id="submit"
name="submit"
class="button is-primary"
>
Submit
</button>
</div>
</form>
<div id="error_message" class="text-danger"></div>
<div id="success_message" class="text-success"></div>
AJAX/jQuery: (inside index.html )
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
var weight = $("#weight").val();
var person = $("#person").val(); // You miss this
var weightdate = $("#weightdate").val(); // You miss this
if (weight == "" || person == "" || weightdate == "") {
$("#error_message").html("All Fields are required");
} else {
$("#error_message").html("");
$.ajax({
url: "connection.php",
method: "POST",
data: {
weight: weight,
person: person, // Add this
weightdate: weightdate, // Add this
},
success: function (data) {
$("form").trigger("reset");
$("#success_message").fadeIn().html("data");
setTimeout(function () {
$("#success_message").fadeOut("Slow");
}, 2000);
},
});
}
});
});
PHP: (connection.php)
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
include_once 'dbconnect/db_info.php';
$weight = $_POST['weight'];
$person = $_POST['person'];
$date = $_POST['weightdate'];
$formatDate = date("d/m/y", strtotime($date));
//echo $formatDate;
if(date("m", strtotime($date)) == date("01")) {
$sql = "INSERT INTO WeightTracker (person, kg, weight_date, date_month) VALUES ('$person', '$weight', '$formatDate', 'January');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
elseif(date("m", strtotime($date)) == date("04")) {
//echo working;
$sql = "INSERT INTO WeightTracker (person, kg, weight_date, date_month) VALUES ('$person', '$weight', '$formatDate', 'April');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
else {
$sql = "INSERT INTO WeightTracker (person, kg, weight_date) VALUES ('$person', '$weight', '$date');";
#$result = mysqli_query($conn, $sql);
$result = mysqli_query($conn, $sql);
}
Does anyone have any ideas? When I remove the AJAX/jQuery code, the form successfully submits and the connection.php writes to the database with no issues.
Most of the problem was resolved in comments. The problem (as described in the comments) was a PHP error Undefined index on this line:
$person = $_POST['person'];
As I mentioned in an earlier comment: your person input is missing the expected person ID. That means this Javascript:
var person = $("#person").val();
Is actually undefined, so there is no person field POSTed to your PHP, so when you try to use it as $_POST['person'], you'll get an error.
To fix that, just add the id your Javascript is using to find the person:
<select name="person" id="person">
The data you give for the POST request is just weight, there is no person and weightdate data.
var weight = $("#weight").val();
var person = $("#person").val(); // You miss this
var weightdate = $("#weightdate").val(); // You miss this
if (weight == "" || person == "" || weightdate == "") {
$("#error_message").html("All Fields are required");
} else {
// Your code :)
}
And the data,
$.ajax({
url: "connection.php",
method: "POST",
data: {
weight: weight,
person: person, // Add this
weightdate: weightdate // Add this
},
success: function(data) {
$("form").trigger("reset");
$("#success_message")
.fadeIn()
.html("data");
setTimeout(function() {
$("#success_message").fadeOut("Slow");
}, 2000);
}
});
Your Problem lies here.
include_once 'dbconnect/db_info.php';
Change it to something like
realpath('__DIR__'.'/dbconnect/db_info.php');
Hopefully it will solve your problem.
Related
I was making like button with php and ajax/jquery and it wont be reload when you click it will just reload the div but it reload the div but the number of like don't add
here my code.
<div id="Post-ImVi-Action">
<script>
$(document).ready(function () {
$('#Post-ImVi-Action-Like').click(function (e) {
e.preventDefault();
var name = $('#Like_Poster_name').val();
var email = $('#Like_Post_1').val();
$.ajax
({
type: "POST",
url: "php-SocialMedia-Posting-Like.php",
data: { "Poster_name": name, "Post_1": email },
success: function (data) {
$("#Post-ImVi-Action-Like").html(data);
}
});
});
});
</script>
<input type="Hidden" name="Poster_Name" id="Like_Poster_name" value="<?php echo $Post_Row["Poster_Name"];?>">
<input type="Hidden" name="Post_1" id="Like_Post_1" value="<?php echo $Post_Row["Post_1"];?>">
<input type="Hidden" name="ID" id="Like" value="<?php echo $Post_Row["ID"];?>">
<button id="Post-ImVi-Action-View">158K</button>
<button id="Post-ImVi-Action-Like" type="button" name="Like_Button" >
<?php
$Post = $Post_Row["Post_1"];
$Sql_like_count = "SELECT * FROM `likes` WHERE post = '$Post'";
$Result_like_Count = mysqli_query($conn, $Sql_like_count);
while ($ROW_LIKE = mysqli_fetch_array($Result_like_Count)) {
echo $ROW_LIKE['Likes'];
}
?>
</button>
<button id="Post-ImVi-Action-Share">815</button>
<div id="Post-ImVi-Action-Face"></div>
</div>
Here is php-SocialMedia-Posting-Like.php
<?php
include"php-MAIN-Info.php";
include"php-MAIN-SignUp+Database.php";
$Post = $_POST['Post_1'];
$Poster_Name = $_POST['Poster_Name'];
$Sql = "SELECT* FROM Likes WHERE Post = '$Post' AND Poster_Name = '$Poster_Name'";
$Like_Result = mysqli_query($conn, $Sql);
while ($Like_Row = mysqli_fetch_array($Like_Result)) {
$Like_Add = $Like_Row['Likes'] + '1';
$Sql_Like_Add = "UPDATE Likes SET Likes = '$Like_Add' WHERE Post = '$Post' AND Poster_Name = '$Poster_Name';";
$Like_Result_Add = mysqli_query($conn, $Sql_Like_Add);
if ($Like_Result_Add) {
echo $Like_Add;
}
}
update:
i found a error
php-Home-MSOHome.php:352 Uncaught ReferenceError: data is not defined
please try to help cause i'm new to this web.Thanks
why is no one answering my question you k i'm still looking for the answers
I did it its a php error udfinde Poster_name its Poster_Name
What I'm trying to do is make a search page where the result would be on the same page. My concept is to first show all data and then there will be one textbox and one submit button. Below that, I will show the result which is paginated. How do I achieve that?
<input type ="text" placeholder = "search" name = "search">
<input type ="submit" name = "submit">
<?php
if(isset($_POST['submit']))
$search = $_POST['search'];
{
$query = "SELECT * FROM table WHERE search = '$search' ";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
//echo my result here.
}
}
Take a look at jquery and ajax. I did something similar as a test awhile back:
var request = $.ajax({
type: "GET",
url: url,
data: $(".form-wrapper").serialize()
});
request.done(function(data) {
if (data.search("No results") == -1) {
$("#result").show();
$("#result").html(data);
} else {
$('#result').html('').hide();
}
});
request.fail(function(jqXHR, msg) {
alert(msg);
});
<form class="form-wrapper cf">
<input type="text" id="text" name="q" placeholder="" required>
<button type="submit" disabled>Search</button>
</form>
<div id="result"></div>
hello i have a little bit of a trouble finding a specific answer so .. i hope this is not a repost, i have the following login.php code
function loginBackUser($arr){
global $link;
extract($arr);
$msg = '';
$pass = md5($pass);
$pass = md5($pass);
$pass = sha1($pass);
$pass = md5($pass);
$pass = md5($pass);
$pass = sha1($pass);
$pass = sha1($pass);
$pass = sha1($pass);
$sql = "SELECT * FROM `table` WHERE `email`='$email' AND `pass`='$pass'";
$sqlEmail = "SELECT * FROM `table` WHERE `email`='$email'";
$resEmail = mysqli_query($link,$sqlEmail) or die("SQLEmail gresit");
$res = mysqli_query($link,$sql) or die("SQL gresit");
if(mysqli_num_rows($res) == 1){
$row = mysqli_fetch_assoc($res);
session_start();
$id=$row['id'];
$_SESSION['id'] = $row['id'];
$_SESSION['name'] = $row['name'];
$sqlEmptyAttempts = "UPDATE `table` SET `attempts` = '0' WHERE `id` = '$id'";
$resEmptyAttempts = mysqli_query($link,$sqlEmptyAttempts) or die("SQLEmptyAttempts gresit");
header('Location:/oproit/index.php?pag=dash_homepage');
}else if(mysqli_num_rows($resEmail) == 1){
$row2 = mysqli_fetch_assoc($resEmail);
$id=$row2['id'];
$sqlVerifyAttempts = "SELECT `attempts` FROM `table` WHERE `id` = '$id'";
$resVerifyAttempts = mysqli_query($link,$sqlVerifyAttempts) or die("SQLVerifyAttempts gresit");
$row3 = mysqli_fetch_assoc($resVerifyAttempts);
if($row3['attempts']<3){
$attempts = $row3['attempts']+1;
$sqlSetNewAttempts = "UPDATE `table` SET `attempts` = '$attempts' WHERE `id` = '$id'";
$resSetNewAttempts = mysqli_query($link,$sqlSetNewAttempts) or die("SQLSetNewAttempts gresit");
echo "wrong password";
}else{
$sqlEmptyAttempts = "UPDATE `table` SET `attempts` = '0' WHERE `id` = '$id'";
$resEmptyAttempts = mysqli_query($link,$sqlEmptyAttempts) or die("SQLEmptyAttempts gresit");
echo "dude be serious"; // here will be some mail function but for now i just want it to work with ajax
}
}else{
echo "your email is not in our data base";
}
$thread_id = mysqli_thread_id($link);
mysqli_kill($link,$thread_id);
mysqli_close($link);
}
i would like it to be accessed by axaj, and my "echos" to be inside a previously empty div, the login form html page
<form id="loginUser" method="post" action="login.php" onsubmit="return false;">
<input type="text" id="email" name="email" class="textField" value="email" />
<input type="password" id="pass" name="pass" class="textField" value="" />
<input type="submit" id="loginUserSubmit" onclick="isSession('loginUser','resultShow')" name="loginUserSubmit" value="Da Bah!" /></form><div id="resultShow">sas</div>
my so far javascript is
function isSession(selector,responseElement) {
var e = document.getElementById(selector);
if(!e){
alert('there is no element with the id='+selector);
}
var b = document.getElementById(responseElement);
if(!b){
alert('there is no element with the id='+responseElement);
}
$(e).submit(function (event) {
$.ajax({
type: $(e).attr('method'),
url: $(e).attr('action'),
data: $(e).serialize(),
success: function(data){
$(b).html(data);
},
error: function() {
alert("Error occured")
}
});
event.preventDefault();
});
}
but it does nothing .. i need when the user clicks the login button and gets only the pass wrong .. to let him be wrong for three times .. but at every turn tell him . in that empty div .. that he was wrong...
Do you know what i mean?
The problem is on your PHP (login.php).
You should remove the function loginBackUser: you're not calling that method.
And change the extract method on login.php to extract($_POST).
e.g.:
<?php
if (isset($_POST['pass']) && isset($_POST['email'])) {
global $link;
extract($_POST);
...
}
EDIT
This isn't the best way to make a login system, I hope you are just studying/testing :)
so ... in stead of using ajax which i don't know that well, i made something that might be called unprofessional by others, which is <div id="resultShow">
<?php
if(isset($_POST['loginUserSubmit'])){
require_once('/path/to/Class.BackUser.php');
$bkUser = new BackUser();
$bkUser->loginBackUser($_POST);
}
?>
</div>
and this way .. whatever the method loginBackUser() echos, is in the place that i wanted it to be, but i would still like with your help, if you will, to find a way to skip that refresh php needs to do everything :D
I'm not sure how you handle the server side validation but I simplified your code just to make a small demonstration of ajax get/post on same page. This is just an example and can be done in many other ways.
From .serialize() documentation:
No submit button value is serialized since the form was not submitted
using a button.
Here's the full code I came up with
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<?php
if(isset($_POST["email"]) && isset($_POST["pass"]))
{
echo "Email:".$_POST["email"]."<br/>Password:".$_POST["pass"];
}
else
{
?>
<form id="loginUser" method="post" action="login.php">
<input type="text" id="email" name="email" class="textField" value="email" />
<input type="password" id="pass" name="pass" class="textField" value="" />
<input type="submit" id="loginUserSubmit" name="loginUserSubmit" value="Da Bah!" />
</form><div id="resultShow"></div>
<script>
$(document).ready(function(){
$("#loginUser").submit(function (event) {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data){
$("#resultShow").html(data);
},
error: function() {
alert("Error occured")
}
});
event.preventDefault();
});
});
</script>
<?php
}
?>
</body>
</html>
You should make a reference to jQuery library with
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Always better to wrap your script in $(document).ready() function like this
$(document).ready(function()
{
//your code here
}
);
In your case, it's as follows
$(document).ready(function(){
$("#loginUser").submit(function (event) {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data){
$("#resultShow").html(data);
},
error: function() {
alert("Error occured")
}
});
event.preventDefault();
});
});
On server-side there are many ways to see if the form was posted or not. Simply use
if(isset($_POST["email"]) && isset($_POST["pass"]))
and wrap your logic in it. If the form was not submitted do something else.
Give this a try and if that works, implement the validations along with extras on the working version.
and thank you in advance for reading this. I'm new in php and jquery. I've managed to do few forms in php that worked, and now feel a big need (because of how my webpage is shaping) to make them work with jquery. I'm trying but something is not right. This is the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method ="post" id="form_Add">
<br>
<div class="Add_field" id="title_div">Title:<input typee="text" class="Add_text" maxlength="100" name="title" id="title"></div>
<br>
<div class="Add_field">Discription:<input typee="text" class="Add_text" maxlength="1000" name="discription" id="discription"></div>
<br>
<div class="Add_field" id="content_div">Content:<textarea class="Add_text" maxlength="65535" name="content" id="content" rows="5" cols="15"></textarea></div>
<br>
<div class="Add_field"><label for="shortstory"><input typee="radio" name="prose" class="" id="shortstory" value="1">Short story</label></div>
<div class="Add_field" id="prose_div"><label for="chapter"><input typee="radio" name="prose" class="" id="chapter" value="2">Chapter</label></div>
<br>
<div class="Add_field" id="typey">type:
<select name="type1">
<option value="1" selected="selected">Fantasy</option>
<option value="2">Action</option>
<option value="3">Romance</option>
</select>with elements of
<select name="type2" id="type2">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>and
<select name="type3" id="type3">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>
</div>
<div class="Add_field"><input typee="submit" name="Add_story" class="Add_button" id="submit_story" value="Add story"></div>
</form>
<div id="response">Something</div>
That is script:
<script>
$('#form_Add').on('submit', function (e) {
e.preventDefault();
checkAdd();
});
var selectType = function(){
var type2 = $('#type2').val();
if(type2 === ""){
$('#type3').attr('disabled', 'disabled');
$('#type3').val("");
}
else{
$('#type3').removeAttr('disabled');
}
}
$(selectType);
$("#type2").change(selectType);
function checkAdd(){
var title = $('#title').val();
var content = $('#content').val();
if(title === ""){
$('#titleErr').remove();
$('#title_div').append("<p id='titleErr'>Please add the title.</p>");
}
else{
$('#titleErr').remove();
}
if(content.replace(/ /g,'').length <= 18){
$('#contentErr').remove();
$('#content_div').append("<p id='contentErr'>Content needs to be at least 19 characters long.</p>");
}
else{
$('#contentErr').remove();
}
if($("#shortstory").not(":checked") && $("#chapter").not(":checked")){
$('#proseErr').remove();
$('#prose_div').append("<p id='proseErr'>Check one of the above.</p>");
}
if($("#shortstory").is(":checked") || $("#chapter").is(":checked")){
$('#proseErr').remove();
}
if($("#titleErr").length == 0 && $("#contentErr").length == 0 && $("#proseErr").length == 0){
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', { // when using this bit of script I get 403 Forbidden in Firebug console
title: $('#title').val(),
discription: $('#discription').val(),
content: $('#content').val(),
prose: $('input[name=prose]:checked').val(),
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
}, function(d){
alert(d);
console.log(d);
$('#response').html(d);
});
}
/*
var postData = $("#form_Add").serialize(); // when using this bit of script instead of one on top, I get alert fail and ReferenceError: data is not defined in Firebug console
var formURL = $("#form_Add").attr("action");
$.ajax(
{
url : formURL,
typee: "POST",
data : postData,
datatypee: 'json',
success:function(data, textStatus, jqXHR)
{
alert("success");//data: return data from server
console.log(data.error);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("fail");
console.log(data.error);
}
});
}
*/
};
</script>
And here is php code:
<?php
session_start();
if(isset ($_SESSION['arr'])){
$arr = $_SESSION['arr'];
$uid = $arr['id'];
}
$title = $discription = $content = $prose ="";
if (isset($_POST["Add_story"])) {
$title = stripslashes($_POST["title"]);
$title = mysqli_real_escape_string($connection , $title);
$discription = stripslashes($_POST["discription"]);
$discription = mysqli_real_escape_string($connection , $discription);
$content = stripslashes($_POST["content"]);
$content = mysqli_real_escape_string($connection , $content);
$prose = stripslashes($_POST["prose"]);
$prose = mysqli_real_escape_string($connection , $prose);
$type1 = $_POST["type1"];
$type2 = $_POST["type2"];
$type3 = $_POST["type3"];
$pQuery = "INSERT INTO prose (u_id, data, title_s, discription_s, content_s, prose_s, type1_s, type2_s, type3_s, shows_s)
VALUES ('{$uid}', CURDATE(), '{$title}', '{$discription}', '{$content}', {$prose}, '{$type1}', '{$type2}', '{$type3}', 0)";
$resultP = mysqli_query($connection, $pQuery);
if ($resultP) {
$title = $discription = $content = $prose ="";
}
else {
die("Query failed." . mysqli_error($connection));
}
}
?>
Php code is on the top of the document. Source is on bottom and form is in the middle (I'm using jquery-1.11.1.min.js - source is added in main page, as this one is included in it). I've also tried putting php in separate file and pointing to it through form action instead of <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> but without any joy. I'm guessing my problem is with post data. It probably has to be in an array or object (and I'm doing it wrong) and when it reaches processing there is some sort of incompatibility. Probably using select and radio buttons complicates the process.
Any tips you can share I will greatly appreciate. Thank you for your time.
You have a serious typo in your submit button
<input typee="submit" name="Add_story"
^ extra "e"
which should read as
<input type="submit" name="Add_story"
Your code's execution relies on your conditional statement:
if (isset($_POST["Add_story"])){...}
Plus, you've made the same typo for all your other inputs typee="xxx"
Change them all to type
A simple CTRL-H (typee/type) in a code editor such as Notepad++ even in Notepad will fix that in a jiffy.
I noticed you have given id's to both <select name="type2" id="type2">
and <select name="type3" id="type3"> but not for <select name="type1">, so that could also be another factor that could affect your code's execution, seeing that you have:
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
Edit:
You've also put a commented message which I only saw now and should have been made clear in your question:
// when using this bit of script I get 403 Forbidden in Firebug console
over to the right of
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', {
so I didn't see that.
Try changing it to either, and in single quotes only:
$.post('<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>', {
or
$.post('your_file.php', $(this).serialize(), function(data){
This page may help:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
It contains an example in there that you can base yourself on.
which contains
$.ajax({
type: 'POST',
url: 'post_receiver.php',
data: $(this).serialize()
})
and may need to be added to your script.
You commented out url : formURL, - try using url: 'your_PHP_file.php', in its place, that being the PHP/SQL file that you're using.
If none of this helped, than let me know and I will simply delete this answer.
im quite bad at javascript, and i am trying to make a AJAX call, but i get my value from a form feild, and it just refreshes the page, cant even observe if the AJAX call is succesfull.
Here is my HTML:
<form class="form-horizontal" id="subscribe-form" name="subscribe-form" onSubmit="return subscribe();">
<fieldset>
<p>
Subscribe
</p>
<div class="input-prepend input-append">
<input name="subscribwEmail" class="span2" id="InputEmail" type="email" placeholder="Email">
<input type="submit" class="btn btn-inverse" />
</div>
</fieldset>
</form>
JS:
function subscribe() {
var emailForm = $('#subscribwEmail').val();
$('#subscribe-form').hide(); // hide email form
$('#subscribeDiv').prepend('<img id="process" src="http://www.mydomain.com/assets/img/process.gif" />')
$.ajax({
type: "POST",
url: "../../actions/ajax-subscribe.php",
data: {
email: emailForm
},
dataType: "json",
success: function (data) {
if (data[0] == 1) { // test if response was 1 or 2
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>Thank you for subscribing!</p>');
} else {
$('#process').hide(); // hide img
$('#subscribeDiv').append('<p>There was an error subscribing the email.</p>');
}
}
})
};
ajax-subscribe.php
<?php
include ('phpfunctions.php');
$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('ERROR WITH SQL CONNECTION CONTACT ADMIN');
$email = cleanString($con, $email);
$query = "INSERT INTO `subscribers` (`email`, `ip`) VALUES ('$email', '$ip');";
if ($result = mysqli_query($con, $query)) {
echo json_encode(1); // all ok inserted
} else {
echo json_encode(0); // failed
}
?>
You do not cancel the click event so the form submits.
Add return false; to the end of your subscribe method.
You have to return false from your subscribe method
Also you can validate the email, if it is invalid, you can stop sending subscribe by return false
You can also disable your submit button. (formObj comes with subscribe parameter)
formObj.submit.disabled = true;
formObj.submit.value = 'Log In...';
But you have to enable it if something goes wrong.