Add value to database with ajax and php - javascript

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>

Related

Why do I keep getting NULL returned?

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.

AJAX returns error with empty responseText

I'm trying to get some data trough AJAX but am getting an error with an empty responseText.
My code is as follows:
JS:
function getFounder(id) {
var founder = "";
$.ajax({
url: '/data/founder_info.php',
data: {founder: id},
dataType: 'json',
async: false,
type: 'post',
success: function(json) {
//founder = json.username;
console.log(json);
},
error: function(ts) {
console.log("Error: " + ts.responseText);
}
});
return founder;
}
PHP:
<?php
require_once '../core/init.php';
if($_POST['founder']) {
$u = new User();
$user_info = $u->find(escape($_POST['founder']));
$user_info = $u->data();
echo json_encode($user_info);
exit();
}
I cannot find the issue as to why it is throwing the error.
I fixed it using a method to convert everything to UTF-8.
function utf8ize($d) {
if (is_array($d))
foreach ($d as $k => $v)
$d[$k] = utf8ize($v);
else if(is_object($d))
foreach ($d as $k => $v)
$d->$k = utf8ize($v);
else
return utf8_encode($d);
return $d;
}
This was posted as an answer to this question
My problem is now solved!

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

How to return success in a ajax call

I have an ajax call to delete a page from my database, but I'm not quite sure how to return success and use it:
My ajax call looks like this:
$('.delete_button').click(function() {
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
succes:function() {
alert('something');
if (s.Err == false) {
window.location.reload(true);
}
}, error:function(e){
}
});
});
And in my delete_page.php I have this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
$delete_page = DB::getInstance()->delete('pages', array('id', '=', $page_id));
if ($delete_page) {
$output['Err'] = false;
} else {
$output['Err'] = true;
}
return json_encode($output);
It does delete the page, but it doesn't run the if statement and it is not alerting anything. How do I fix this?
Dont use return, actually output the data, with the correct header:
//return json_encode($output);
header('Content-Type: application/json');
echo json_encode($output);
In your PHP script, you need to output the data instead of returning it:
header('Content-Type: application/json');
echo json_encode($output);
Then in your javascript file you need to retrieve the data:
success: function (data) { // It's success not succes, and you need the parameter
alert('something');
if (data.Err == false) {
window.location.reload(true);
}
}
If that's the entire delete_page.php, it needs to echo the output, not just return it.
Here's a slightly more elegant way of handling this.
Update your delete_page.php script like this:
<?php
require 'core/init.php';
$id = $_POST['page_id'];
$page_id = $id[0];
// Init
$output = array(
'IsDeleted' = false,
'LastError' = ''
);
// Delete
try {
$output['IsDeleted'] = DB::getInstance()
->delete('pages', array('id', '=', $page_id));
}
catch (Exception $ex) {
$output['LastError'] = $ex->getMessage();
}
// Finished
echo json_encode($output);
?>
Then update your ajax code like this:
$.ajax({
url: 'delete_page.php',
dataType: 'json',
async: false,
type: 'post',
data: {
page_id: id
},
dataType: 'json',
succes: function(result) {
if (result.IsDeleted) {
window.location.reload(true);
} else {
alert('Failed to delete. Last error: ' + result.LastError)
}
},
error:function(e) {
}
});

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources