Send GET in Ajax call and PHP script - php

I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?

If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType

Related

PHP variable to JS variable using AJAX

I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: $mapCode,
used: $used,
active: $active,
},
dataType: "text",
});
}
</script>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
?>
I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working
If the file extension is .php and not .js then this should work
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: "<?php echo $mapCode; ?>",
used: "<?php echo $used; ?>",
active: "<?php echo $active; ?>",
},
dataType: "text",
});
}
</script>
If you have .js file then declare javascript variable before including your js in .php file
<script>
var mapCode = "<?php echo $mapCode; ?>";
var used = "<?php echo $used; ?>";
var active = "<?php echo $active; ?>";
</script>
then in .js file you will get easily
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: mapCode,
used: used,
active: active,
},
dataType: "text",
});
}
</script>
You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag
My current project is actually dealing with lots of ajax calls,
here is the simplified version of what I use to communicate with server:
// php
// needed functions
function JSONE(array $array)
{
$json_str = json_encode( $array, JSON_NUMERIC_CHECK );
if (json_last_error() == JSON_ERROR_NONE)
{
return $json_str;
}
throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
header('Content-Type: application/json');
print JSONE($array);
exit();
}
// pack all data
$json_output = array(
'mapCode' => $mapCode,
'used' => $used,
'active' => $active
);
// output/exit
output_array_as_json( $json_output );
// javascript
function _fetch()
{
return $.ajax({
url: 'getMapCode.php', // url copied from yours
type: 'POST',
dataType: 'json',
success: function(data, textStatus, req){
console.log('server respond:', data);
window.mydata = data;
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}
window.mydata = null;
_fetch();
I have not tested this, but let me know I'll fix it for you.
How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
// Outputing results:
echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>
Then in ajax, use success for listening return message after ajax finished:
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
/** Your data to send to server **/
},
dataType: "text",
success: function(data) { /** Here is data returned by php echo **/
var temp = $.parseJSON(data);
mapCode = temp['mapCode'];
used = temp['used'];
active = temp['active'];
}
});
}
</script>

Call PHP function with JavaScript Ajax to get database values

i try to call a php function with Ajax. This is my JavaScript code in my html file:
<script type="text/javascript">
function ajax(){
$.ajax({
type:"POST",
url: "SQLCommunication.php",
dataType: "JSON",
success : function(json){
json = jQuery.parseJSON(json);
alert(json.value);
}
}
)
}
$("#btn_refresh").click(function(){
ajax();
});
</script>
I don't know if i have to specify which PHP function i actually want to call? I also don't know how i do that.
My PHP function:
header('Content-Type: application/json');
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
if(is_ajax()){
return json_encode($arr);
} else {
return $arr;
}
}
$conn->close();
}
So the problem is now, that nothing happens if i press the button.
I'll rewrite to my style
jQuery
<script type="text/javascript">
$("#btn_refresh").click(function(){
$.ajax({
type:"POST",
url: "SQLCommunication.php",
dataType: "JSON",
success : function(data){
console.log(data);
if(data.status === "success"){
alert("success");
}else{
alert("error");
}
}
error : function(XHR, status){
alert("fatal error");
}
})
});
</script>
PHP
header('Content-Type: application/json');
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
$arr["status"] = "success";
}else{
$arr["status"] = "error";
}
return json_encode($arr);
$conn->close();
}
echo readValue();
Untested
Updated
functions.php
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
$arr["status"] = "success";
}else{
$arr["status"] = "error";
}
return json_encode($arr);
$conn->close();
}
function writeValue(){
...
}
SQLCommunication.php
header('Content-Type: application/json');
if(!isset($_GET['func']) && empty($_GET['func'])){
//make the file inaccessible without $_GET
$arr['status'] = "error";
echo json_encode($arr);
exit();
)
if($_GET['func'] === "readvalue"){
echo readValue();
}elseif($_GET['func'] === "writevalue"){
echo writeValue();
}elseif($_GET['func'] === "whatever"){
//whatever...
}
....
jQuery
$("#btn_refresh").click(function(){
$.ajax({
type:"POST",
url: "SQLCommunication.php?func=readvalue", //SQLCommunication.php?func=writevalue
dataType: "JSON",
success : function(data){
console.log(data);
if(data.status === "success"){
alert("success");
}else{
alert("error");
}
}
error : function(XHR, status){
alert("fatal error");
}
})
});
If you want to see the result in your ajax response, you have to use echo(), or any other printing method in your controller instead of return

Variable is empty

I am trying to show data from the database in my textbox. But when I start the script I am getting no results. I tested the script in different ways and i figured out that the variable: $product1 is empty. Does anybody know how I can fix this?
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
}
?>
Change
var selectedItem = jQuery('.product1 option:selected').val();
To
var selectedItem = jQuery('#product1 option:selected').val();
You are selecting a class with name product1, but you set only an ID with this name. Id's are specified with # and classes with .
Update on your script, because you used getPrice(this.value);
<script>
function getPrice(selectedItem) {
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
TIP:
Did you know that you can use jQuery.ajax and jQuery('selector') also like this: $.ajax and $('selector') :-)
You have not a form tag in your HTML. The default form Method is GET.
In Your get.php you try to get a POST Variable with filter_input
The function filter_input returns null if the Variable is not set.
Two possible solutions:
1. Add a form to your html with method="post"
2. Change your php code to search for a GET variable

jQuery keyup function stops working when trying to insert into a database

This is a weird problem and I'm not sure how to approach it.
At the moment I'm trying to have the user enter an ingredient - a list of ingredients appears as you type with buttons next to them to add them which should insert them into SQL database.
The list population ceases to function when I uncomment
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
In the .click function of the add button.
Which is strange because it's like the .keyup function just stops working.
<html>
<head>
<title>Cocktails</title>
<script src="http://assets.absolutdrinks.com/api/addb-0.5.2.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="ingredientinput" id="ingredientinput"><br>
</form>
<div id="ingredientlist">
</div>
<script>
$(document).ready(function(){
//ajax call to query cokctail DB
//handleData is callback function that handles result
function get_ingredients(query,handleData){
var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var rooturl = "http://addb.absolutdrinks.com/";
$.ajax({
type: "GET",
url: rooturl + "/quickSearch/ingredients/" + query + "/",
dataType: 'jsonp',
data: {apiKey:apikey},
success: function(data) {
handleData(data);
},
error: function(){
//error
}
});
}
//when text is entered - quicksearch the database
$("#ingredientinput").keyup(function(){
query = $(this).val(); //value of textbox
divlist = ""; //list of ingredients
objectlist = {};
if (query.length > 0){
//set loading image on keypress
$("#ingredientlist").html("<img src='images/spinner.gif' alt='loading' height='24' width='24'>");
//pass query to ajax call and handle result
get_ingredients(query,function(data){
console.log(data);
//build list of ingredients
$.each(data["result"], function(key, value){
divlist += "<div id='" + value["id"] + "'>" + value["name"] + "<button class='addbutton' type='button' id = '"+value["id"]+"'>+</button></div>";
objectlist[value["id"]] = value;
//clicking button dumps object to file?
});
$("#ingredientlist").html(divlist); //populate div ingredientlist with results
divlist = ""; //clear html builder
});
console.log("input query:" + query);
}
else{
$("#ingredientlist").html(""); //if no input clear list
}
});
$("#ingredientlist").on('click','button.addbutton',function(){
$("#ingredientlist").on('click','button.addbutton',function(){
current = objectlist[this.id];
sqlquery = current["description"] + "," + current["id"] + "," + current["isAlcoholid"] + "," + current["isBaseSpirit"] + "," + current["isCarbonated"] + "," + current["isJuice"] + "," + current["languageBranch"] + "," + current["name"] + "," + current["type"];
console.log(sqlquery);
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES ('test','test','test','test','test','test','test','test','test',)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
});
});
});
</script>
</body>
</html>
You can't just embed a save query from within javascript like you are doing. This is a server side function that needs to happen, and return a result (Almost like you're doing with your get_ingredients function.)
My suggestion, is create a save_ingredients function that works through ajax to pass the information (In this case, the ingredient to save) to the server.
in saveingredients.php:
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = new mysqli($servername, $username, $password, $dbname);
$description = filter_input(INPUT_GET, 'description', $_GET['description'], FILTER_SANITIZE_SPECIAL_CHARS);
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$isAlcoholic = filter_input(INPUT_GET, 'isAlcoholic', FILTER_VALIDATE_BOOLEAN);
$isBaseSpirit = filter_input(INPUT_GET, 'isBaseSpirit', FILTER_VALIDATE_BOOLEAN);
$isCarbonated = filter_input(INPUT_GET, 'isCarbonated', FILTER_VALIDATE_BOOLEAN);
$isJuice = filter_input(INPUT_GET, 'isJuice', FILTER_VALIDATE_BOOLEAN);
$languageBranch = filter_input(INPUT_GET, 'languageBranch', FILTER_SANITIZE_SPECIAL_CHARS);
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$type = filter_input(INPUT_GET, 'type', FILTER_SANITIZE_SPECIAL_CHARS);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ( $stmt = $conn->prepare($sql) )
{
$stmt->bind_param('sdsssssss', $description, $id, $isAlcoholic, $isBaseSpirit, $isJuice, $languageBranch, $name, $type);
if ($stmt->execute($sql) === TRUE) {
echo json_encode('error' => false);
} else {
echo json_encode('error' => 'MySQL Error: ' . $conn->error);
}
}
$conn->close($conn);
?>
A sample AJAX function:
function saveingredients(current) {
$.ajax({
url: 'saveingredients.php',
data: {
description: current["description"],
id: current["id"],
isAlcoholid: current["isAlcoholid"],
isBaseSpirit: current["isBaseSpirit"],
isCarbonated: current["isCarbonated"],
isJuice: current["isJuice"],
languageBranch: current["languageBranch"],
name: current["name"],
type: current["type"]
},
success: function(res) {
if ( res.error )
{
console.log(res.error);
}
else
{
//Do something here because it inserted correctly.
}
},
failure: function(err) {
console.log(err);
}
});
}

Comparing $.ajax result

I would just like to know how to go about comparing the resulting echo from a $.ajax call in JavaScript. I attempted this and even though I get 1, it doesn't actually compare the results correctly.
jQuery:
$.ajax({
type: "POST",
url: "login.php",
data: user,
dataType: 'html',
success: function(result)
{
alert(result);
if(result == '1')
{
alert("logged in :D");
//document.location.replace('home.php');
}
else
{
alert("not logged in :<");
}
},
failure: function()
{
alert('An Error has occured, please try again.');
}
});
PHP:
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "";
$con = mysql_connect($host, $user, $passw);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$json = $_REQUEST['json'];
$json = stripslashes($json);
$jsonobj = json_decode($json);
$password = $jsonobj->password;
$email = $jsonobj->email;
mysql_select_db("tinyspace", $con);
$result = mysql_query("SELECT 1 FROM users WHERE email = '"
. $email . "' AND password = '" . $password . "'");
while($info = mysql_fetch_array( $result ))
{
if($info[0] == 1)
{
echo '1';
}
}
?>
There's probably a space or line break after the '1' that is echoed. Check if there's no space before the opening <?php tag and remove the closing ?> tag (you're allowed to do that, and it will prevent accidental whitespace being outputted.
You should be able to check by changing the javascript to:
alert('X' + result + 'X');
You'll see soon enough if there's any whitespace around result.
try to send json response
php:
echo json_encode(array(
'status' => 'ok',
));
js:
dataType : "json",
success : function(response) {
if (response.status == "ok") {
alert('success');
} else {
alert('error');
}
}

Categories