Retrieve parts of jquery response to populate inputs and selects - javascript

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

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.

how can I use jquery variable in mysql query

At the moment, I am using a $_GET to query mysql and populate a select statement, which works fine. However, I now need to query db using jquery variable and am unable to find a way to use 'depts' instead of '$_GET['dept']'.
I have declared the var global, but realise that you cannot use var in query.
I would be grateful if someone could show me how to amend my code to achieve this. Thanks
php code to populate select
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("sample", $conn);
$result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}' and status = 1 ORDER BY custref ASC");
?>
<select name="boxdest[]" id="boxdest" size="7" multiple="multiple">
<?php
$i=0;
while($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
<?php
$i++;
}
?>
</select>
jQuery change event code
<script type="text/javascript">
var depts;
$('#dept').on('change', function() {
depts = $('#dept option:selected').html();
if (depts === 'Select a Department') {
$('#deptResult').html('<p>ERROR: You must Select a department to proceed<p/>').css({'color':'red'});
$( "#submit" ).prop( "disabled", true );
return;
}
$('#deptResult').html('<p>SUCCESS: You have selected the following dept: ' + depts + '</p>').css({'color':'black'});
});
</script>
Use jquery ajax() like:
$.ajax({
url : 'process.php',
method : 'get',
async : false,
data : {
variable : value,
// you can pass multiple variables like this and this is available in php like $_REQUEST['variable']
},
success : function(response){
// do what ever you want with the server resposne
}
});
process.php:
$variable = $_REQUEST['variable']; // you can use $variable in mysql query
Can you? Yes
You have to use AJAX. I can recommend crafting simple API for this task. Example using JSON:
api.php
<?php
function output($arr) {
echo json_encode($arr);
exit();
}
if (!isset($_GET['dept'])) {
output([
'success' => false,
"message" => "Department not defined"
]);
}
$mysqli = new mysqli("localhost", "root", "", "test");
if ($mysqli->connect_errno) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Connect failed: ". $mysqli->connect_error
]);
}
$result = $mysqli->query("SELECT DISTINCT(`department`) FROM `boxes`");
if (!$result) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Query failed"
]);
}
$departments = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$departments[] = $row['department'];
}
if (!in_array($_GET['dept'], $departments)) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Department not present in database"
]);
}
$result = $mysqli->query("SELECT `custref` FROM `boxes` WHERE `department`='". $_GET['dept'] ."' ORDER BY `custref` ASC");
if (!$result) {
output([
'success' => false,
'dept' => $_GET['dept'],
'message' => "Query failed"
]);
}
$custref = [];
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$custref[] = $row['custref'];
}
output([
'success' => true,
'dept' => $_GET['dept'],
'custref' => $custref
]);
$result->free();
$mysqli->close();
$(function () {
$('select[data-key][data-value]').each(function (i, element) {
var key = $(element).data("key");
var value = $(element).data("value");
var $originSelector = $('[name="'+ key +'"]');
/**
* Get options from element by name
*/
function getOptions () {
var request = {};
request[key] = $originSelector.val();
$.ajax({
url: "./api.php",
method: "GET",
dataType: "json",
data: request
}).done(function(data) {
setOptions(data);
});
}
/**
* Remove old options
*/
function clearOptions () {
$(element).find('option').remove();
}
/**
* Put new options in input
*/
function setOptions (data) {
if (data['success'] && data[value] !== undefined) {
clearOptions();
$.each(data[value], function (i, option) {
$(element).append('<option value="'+ option +'">'+ option +'</option>');
});
}
}
getOptions();
$originSelector.on("change", function () {
getOptions();
});
});
});
<select name="dept">
<option value="accounting">Accounting</option>
<option value="it">Information technology</option>
</select>
<select name="boxdest[]" id="boxdest" size="7" multiple="multiple" data-key="dept" data-value="custref"></select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Data Saving: Write to MySQL Database with Ajax and Json

I am total lost. What is wrong? I try to INSERT INTO mysql.
It add a row in MySQL , but it does not fill in data.
I am sitting since some days on it and dont understand it. I checked hundreds of web pages.
How can I send data to the PHP part? What is wrong in this code?
...
Here is the full code:
Javascript:
function jsRecordInsertWrite()
{
var jsObject = {
"ID": document.form_articles.ID.value,
"Item": document.form_articles.Item.value,
"ItemNo": document.form_articles.ItemNo.value,
"Material": document.form_articles.Material.value,
"Age": document.form_articles.Age.value,
"ItemSize": document.form_articles.ItemSize.value,
"Price": document.form_articles.Price.value,
"Info": document.form_articles.Info.value,
"InfoRed": document.form_articles.InfoRed.value,
"ArrivalDate": document.form_articles.ArrivalDate.value,
"ArrivalDateShown": document.form_articles.ArrivalDateShown.value,
"MainPicLink": document.form_articles.MainPicLink.value,
"ItemCondition": document.form_articles.ItemCondition.value,
"ItemTimestamp": document.form_articles.ItemTimestamp.value,
"ItemCategory": document.form_articles.ItemCategory.value
};
// ... the AJAX request is successful
var updatePage = function (response) {
alert("insert record successful");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("insert record failed");
};
// Create an object to describe the AJAX request
$.ajax({
url : 'insertarticle.php',
dataType : 'json',
contentType: 'application/json; charset=UTF-8',
// This is the money shot
data : jsObject,
type : 'POST',
success: updatePage,
error: printError
});
}
insertarticle.php
<?php
$link = mysql_connect('localhost', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//read the json file contents
$ID = $_POST['ID'];
$Item = $_POST['Item'];
$ItemNo = $_POST['ItemNo'];
$Material = $_POST['Material'];
$Age = $_POST['Age'];
$ItemSize = $_POST['ItemSize'];
$Price = $_POST['Price'];
$Info = $_POST['Info'];
$InfoRed = $_POST['InfoRed'];
$ArrivalDate = $_POST['ArrivalDate'];
$ArrivalDateShown = $_POST['ArrivalDateShown'];
$MainPicLink = $_POST['MainPicLink'];
$ItemCondition = $_POST['ItemCondition'];
$ItemTimestamp = $_POST['timestamp'];
$ItemCategory = $_POST['ItemCategory'];
//insert into mysql table
$sql = "INSERT INTO articles(ID, Item, ItemNo, Material, Age, ItemSize,
Price, Info, InfoRed, ArrivalDate, ArrivalDateShown, MainPicLink,
ItemCondition, ItemTimestamp, ItemCategory)
VALUES(NULL,'$Item','$ItemNo','$Material','$Age',
'$ItemSize','$Price','$Info','$InfoRed','$ArrivalDate',
'$ArrivalDateShown','$MainPicLink','$ItemCondition',
'$ItemTimestamp','$ItemCategory')";
if(!mysql_query($sql))
{
die('Error : ' . mysql_error());
}
//database connection close
mysql_close($link);
//}
?>
//+++++++++++++++++++++++++++++++++++++++++++++++++
//The first NULL is for autoincrement ID,
//the other NULL is for automatic timestamp

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