Why do I keep getting NULL returned? - javascript

I am creating a booking system for a university project and I am trying to add an author to the table 'authors' for some reason when I add a field it returns as NULL in my database and undefined on my html page? Can anyone help me with this I have shown my HTML, Javascript and php code below.
Can anyone help me with this and guide me in the right direction. I have a feeling it is something to do with my names eg. authors or author
Thanks in advance.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="w3.js"></script>
<script src="https://scm.ulster.ac.uk/zhiwei.lin/js/jquery.tmpl.min.js"></script>
</head>
<body>
<div id="authors">
<ul id="authors_list"></ul>
</div>
<div class="mainArea">
<label>Author:</label>
<input type="text" id="author" name="name" required>
<button id="btnSave">Save</button>
<button id="btnUpdate">Update</button>
</div>
<p>Click Here to Delete Last Author
<button id="btnDelete">Delete</button></p>
</body>
</html>
Js
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "json",
url: "api.php/authors",
success: showAllAuthors,
error: showError
});
});
function showAllAuthors(responseData) {
$.each(responseData.authors,function(index,authors){
$("#authors_list").append("<li type='square'> author:"+authors.author+"");
$("#authors_list").append("</li>");
});
}
function showError(){
alert("Sorry, there was a problem!");
}
$(document).ready(function(){
$("#btnSave").click(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: "api.php/authors",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: showResponse,
error: showError
});
});
});
function authors(Author){
this.author=Author;
}
function showResponse(responseData) {
console.log(responseData);
}
function showError() {
alert("Sorry, there was a problem!");
}
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "json",
url: "api.php/authors/12",
success: showResponse,
error: showError
});
});
$(document).ready(function(){
$("#btnUpdate").click(function(){
$.ajax({
type: 'PUT',
dataType: "json",
url: "api.php/authors/12",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: alert("Updated!")
});
});
});
$(document).ready(function(){
$("#btnDelete").click(function(){
$.ajax({
type: 'DELETE',
dataType: "json",
url: "api.php/authors/13",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: alert("Deleted!")
});
});
});
PHP
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app=new Slim();
$app->get('/authors','getAuthors');
$app->post('/authors','addAuthor');
$app->get('/authors/:id','getAuthor');
$app->put('/authors/:id','updateAuthor');
$app->delete('/authors/:id', 'deleteAuthor');
$app->run();
function deleteAuthor($id) {
$sql = "DELETE FROM authors WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
responseJson("Deleted",200);
}catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function updateAuthor($id) {
$request = Slim::getInstance()->request();
$body = $request->getBody();
$authors = json_decode($body);
$sql = "UPDATE authors SET author=:author WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("author", $authors->author);
$stmt->bindParam("id", $id);
$stmt->execute();
$db = null;
responseJson("Updated",200);
} catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getAuthor($id) {
$sql = "SELECT * FROM authors WHERE id=:id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$authors = $stmt->fetchObject();
$db = null;
responseJson(json_encode($authors),200);
} catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getAuthors(){
$sql = "select * FROM authors ORDER BY id";
try {
$db = getConnection();
$stmt = $db->query($sql);
$authors = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
responseJson('{"authors":'.json_encode($authors).'}',200);
}catch(PDOException $e){
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function addAuthor(){
$request = Slim::getInstance()->request();
$authors=json_decode($request->getBody());
$sql= "INSERT INTO authors (author)
VALUES (:author)";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("author", $authors->author);
$stmt->execute();
$authors->id=$db->lastInsertId();
$db = null;
responseJson(json_encode($authors),201);
}catch(PDOException $e) {
responseJson('{"error":{"text":'.$e->getMessage().'}}',500);
}
}
function getConnection(){
$dbhost="localhost";
$dbuser="B00657229";
$dbpass="9wz7Fr9J";
$dbname="B00657229";
$dbh= new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser,$dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function responseJson($responseBody,$statusCode){
$app = Slim::getInstance();
$response = $app->response();
$response['Content-Type']='application/json';
$response->status($statusCode);
$response->body($responseBody);
}
?>

There seems to be a mistake in your js code:
$(document).ready(function(){
$("#btnSave").click(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: "api.php/authors",
data:{author: $("#author").val()},
data:JSON.stringify(authors),
success: showResponse,
error: showError
});
});
you set data two times, one time with
{author: $("#author").val()} and other time with JSON.stringify(authors) i don't think you need the second one, but I did not test this.

Related

How to make this AJAX (login) request to be secured

I'm making a login system to my website, but the browser says it is not secured: the browser's message
Heres is my html:
<div id="loginform">
Bejelentkezés
<input type="text" placeholder="E-mail" id="email"></input>
<input type="password" placeholder="Jelszó" id="password"></input>
<button id="loginbutton">Bejelentkezés</button>
<div id="errormsg"></div>
</div>
Here is my Ajax:
$("#loginbutton").click(function(){
var user ={
email: $('#email').val(),
password: $('#password').val()
};
$.ajax({
url: 'login.php',
type: 'POST',
dataType: "json",
data: {"user": JSON.stringify(user)},
success: function(data){
if(data.success){
alert(data.user_id);
}
else{
document.getElementById("errormsg").innerHTML = "A bejelentkezés sikertelen";
}
}
});
});
And my PHP:
<?php
session_start();
$conn = mysqli_connect("localhost", "root", "", "getpet");
$results = array(
'success' => false,
'user_id' => "azaz",
'fname' => "",
'lname' => ""
);
if(isset($_POST['user'])){
$user = json_decode($_POST['user']);
$email = $user->email;
$password = md5($user->password);
$sql= "SELECT * FROM users WHERE email = '".$email."' AND password = '".$password."'";
$rowsql = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($rowsql, MYSQLI_BOTH);
if(mysqli_num_rows($rowsql) == "1"){
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['fname'] = $row['fname'];
$_SESSION['lname'] = $row['lname'];
$results['success'] = true;
$results['user_id'] = $row['user_id'];
$results['fname'] = $row['fname'];
$results['lname'] = $row['lname'];
}
}
else{
$results['user_id']= "VAnbaj";
}
echo json_encode($results);
?>
It works, but i don't know how to make it safe.
I'd be glad if somebody can help me.
I you want to get rid of that warning message, you have to serve your site over https with a valid certificate.

Inline CKEditor save to MySQL using AJAX/PHP

I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'

Retrieve parts of jquery response to populate inputs and selects

I send a jQuery request (incorporating a business_id) to a php file to retrieve all values in the database to populate the fields and selects that are in my form and correspond to this id. However, how am I able to retrieve the response from the database in pieces? So that I can provide the fields and selects that are in the form with the values from the database. My javascript function looks as follows:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response);
}
});
}
});
},
My businessdata.php looks as follows:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID ='$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo $row['uitgevoerd_door_naam'];
echo $row['hoev_gev_stof_score'];
}
}
mysqli_close($mysqli);
?>
What I want to achieve is:
$("#uitgevoerd_door_naam").val() == $row['uitgevoerd_door_naam'];
$("#hoev_gev_stof_score").val() == $row['hoev_gev_stof_score'];
etc.....
Fix:
Use json encode:
function:
businessselect: function(){
$('#busselect').change(function() {
opt = $(this).val();
if (opt=="new_bus") {
location.reload();
}
else
{
businessid = $(this).children(":selected").attr("id");
$.ajax({
url : "businessdata.php",
method : "post",
dataType: "json",
data : "business_id="+businessid,
success: function(response) {
$("#uitgevoerd_door_naam").val(response.a);
$("#riskpot_scorefield3").val(response.b);
}
});
}
});
},
php file:
<?php
$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($_POST)
{
$result = $mysqli->query("SELECT * from form WHERE ID = '$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
echo json_encode(array("a" => $row['uitgevoerd_door_naam'], "b" => $row['hoev_gev_stof_score']));
}
}
mysqli_close($mysqli);
?>

AJAX - JSON Error

When I am trying to receive data from the server side, error I am getting:
06-30 11:23:57.119: I/chromium(7486): [INFO:CONSOLE(50)] "{"readyState":4,"responseText":"","status":404,"statusText":"Not Found"}", source: file:///android_asset/www/js/index.js (50)
JS file:
$j.ajax({
type: 'POST',
url: 'http://www.myrandomurl.com/SupportData/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
//alert(JSON.stringify(response));
//console.log(JSON.stringify(response));
if (response.success) {
myApp.alert("you're logged in");
//window.localStorage["email"] = e;
//window.localStorage["password"] = p;
console.log(window.localStorage["email"]);
//localStorage.removeItem('email');
mainView.router.loadPage('main.html');
} else {
myApp.alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
//myApp.alert('Could not connect to the database' + error);
console.log(JSON.stringify(error));
//window.location = "index.html";
}
});
PHP side:
$sql = "SELECT login_id, email_id, password FROM login WHERE email_id='$myusername' and password='$mypassword'";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$row = mysql_fetch_array($result);
if($num_rows == 1) {
$response['success'] = true;
}else {
$response['success'] = false;
}
echo json_encode($response);

Add value to database with ajax and php

I want to add value 'Nova parcela' to database in table zemljiste so I write first ajax code:
<script>
var nova_parcela = 'Nova parcela';
$("#dodaj").click(function() {
$.ajax({
url: "insert.php",
type: "POST",
async: true,
data: { name:nova_parcela}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
});
</script>
after that I write php code: INSERT.php is:
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (!$_POST['name']!='Nova parcela') {
echo "<p>Popunite sva polja</p>";
exit;
} else {
try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO zemljiste (naziv) VALUES (:name)");
$STH->bindParam(':name', $_POST['name']);
$STH->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
echo "<p>Data submitted successfully</p>".$_POST['ajdi'];
}
}
$DBH = null;
but nothing happend , what can be a problem here?
try change that
if (!$_POST['name']!='Nova parcela') {
to
if (!isset($_POST['name'])) {
EDIT:
if (isset($_POST['name'])) {
try {
$DBH = new PDO($dsn, $user, $pass, $opt);
$STH = $DBH->prepare("INSERT INTO zemljiste (naziv) VALUES (:name)");
$STH->bindParam(':name', $_POST['name']);
$STH->execute();
$datas['msg']= "success" ;
} catch (PDOException $e) {
echo $e->getMessage();
}
$DBH = null;
echo json_encode($datas);
}
and your script:
<script>
var nova_parcela = 'Nova parcela';
$("#dodaj").click(function() {
$.ajax({
url: "insert.php",
type: "POST",
async: true,
data: { name:nova_parcela}, //your form data to post goes here as a json object
dataType: "json",
success: function(data) {
if (data.msg == 'success'){
$('#output').html("<p>Data submitted successfully</p>"+nova_parcela);
drawVisualization();
}
else{
$('#output').html("<p>Popunite sva polja</p>");
}
}
});
});
</script>

Categories

Resources