Store value in DB with PHP - Ajax call from JavaScript - javascript

i want to store a value in a database with PHP. I call a PHP-function with AJAX.
I check on document.ready() if the website was called with a parameter called temperature:
$(document).ready(function(){
var data = 5; //gup('temperature', location.href);
if(data != undefined){
var sendData = 'func=storeValue&value=' + data + '&datetime=' + getDateTime();
$.ajax({
data: sendData,
type: "POST",
url: "FunctionManager.php",
success: function(data){
alert("Data Saved " + data);
},
error: function(xhr){
alert(xhr.responseText);
}
})
}
}
I use a the php file "FunctionManager" to call the according function which i determine with the passed parameters. So i pass dataand datetime. My FunctionManager looks like this:
<?php
include "$_SERVER[DOCUMENT_ROOT]/SQLCommunication.php";
header('Content-Type: application/json');
if(!isset($_GET['func']) && empty($_GET['func'])){
exit();
}
if($_POST['func'] === "readValue"){
echo readValue();
}elseif($_POST['func'] === "storeValue"){
echo storeValue($_POST["value"], $_POST["datetime"]);
}
?>
So as you can see i first check which function is called and then call the function itself with parameters. I know that this works because i have a new row in my database after calling the website with a parameter. But the fields datetime and value are always zero.
My storeValue- function is located in SQLCommunication.phpand looks like this:
function storeValue($val, $datetime){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
//$datetime = date_default_timezone_get();
//$datetime = '2016-01-04 00:18:00';
$sql = "INSERT INTO tempvalues (datetime, value) VALUES ('$datetime', '$val')";
$conn->query($sql);
$conn->close();
}
This is the function i use to read the temperature parameter:
function gup( name, url ) {
if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url ).toString();
return results == null ? null : results[1];
}
Do you have any ideas which mistake i made?
Thanks

The jquery code must be like this. If you look at your browser console, you may see some errors.
The jquery should be like this:
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
newdate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
$(document).ready(function(){
var storeValue = 'storeValue';
var data = gup('temperature', location.href);
if(data != undefined){
yourData = 'func='+storeValue+'&value='+data+'&newdate='+newdate;
$.ajax({
data: yourData,
type: "POST",
url: "FunctionManager.php,
success: function(data){
alert("Data Saved " + data);
},
error: function(xhr){
alert(xhr.responseText);
}
});
}
});
In Functionmanager.php
print_r($_POST);
include "$_SERVER[DOCUMENT_ROOT]/SQLCommunication.php";
header('Content-Type: application/json');
if(!isset($_POST['func']) || empty($_POST['func'])){
exit();
}else{
$func = isset($_POST['func'])? $_POST['func']: 'storeValue';
$val = isset($_POST['value'])? $_POST['value']:'';
$datetime = isset($_POST['newdate'])? $_POST['newdate']:'';
if($func == 'readValue'){
echo readValue();
}elseif($func == 'storeValue'){
echo storeValue($val, $datetime);
}
}
In your date field in your table, set datatype as datetime. Hope this may help.

Related

PHP not getting first post value

Experts, my php is not showing the first value of the input field but console.log showing correctly
console.log
PHP Output
function summary() {
$(document).ready(function (e) {
var date = $("#dddeliverydate").val();
var soid = $("#sssoid option:selected").val();
var form = $("#formsum").serialize();
console.log(form);
$.ajax({
url: "test.php",
method: "POST",
data: "&date=" + date + "&soid=" + soid + "&form=" + form,
success: function (data) {
var w = window.open("about:blank", "windowname");
w.document.write(data);
},
});
});
}
below is my PHP code
<?php
for ($count = 0; $count < count($_POST['invoiceno']); $count++) {
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO " . $invoiceno . " Amount " . $amount . '<br>';
}
?>
what I am doing wrong need your help thanks in advance
You can change the code as below
function summary() {
$(document).ready(function (e) {
var send_data= $("#formsum").serialize();
send_data += '&date='+$("#dddeliverydate").val();
send_data += '&soid ='+$("#sssoid option:selected").val();
$.ajax({
url: "test.php",
method: "POST",
data: send_data,
success: function (data) {
var w = window.open("about:blank", "windowname");
w.document.write(data);
},
});
});
}

Cannot retrieve data from PHP array, which is returned by a function() that uses JQuery Ajax

I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '',
arrayedUserData = getModalData(userId);
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.
function getModalData(passedUserId) {
var UserData;
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
UserData = data;
}
}
);
return UserData;
}
this is the "get_modal_data.php".
<?php
include "../includes/connect.php";
if (isset($_POST['passedUserId'])) {
$UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);
$getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
$uaRow = mysqli_fetch_assoc($getUserData);
$UserDataArr = array("UserId" => $uaRow['uaUserId'],
"EmailAddress" => $uaRow['uaEmailAddress'],
"FirstName" => $uaRow['uaFirstName'],
"LastName" => $uaRow['uaLastName'],
"BirthDate" => $uaRow['uaBirthDate'],
"Address" => $uaRow['uaAddress'],
"Gender" => $uaRow['uaGender'],
"ContactNumber" => $uaRow['uaContactNumber'],
"BloodTypeId" => $uaRow['uaBloodTypeId'],
"AccountStatus" => $uaRow['uaAccountStatus'],
);
echo json_encode($UserDataArr);
exit();
}
?>
this error appears on the console:
Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66
this is the line 66 of get_user_accounts.js, which is present on the "click listener".
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
but, I am confused because the php array appears on the browser's Network Response:
Successful Connection{"UserId":"1","EmailAddress":"paulanselmendoza#gmail.com","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}
Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.
I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.
include "../includes/connect.php";
It can be something like:
$conn = mysqli_connect() or die("Error");
echo "Successful Connection";
Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:
using callbacks
function getModalData(passedUserId,callback) {
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
callback(data);
}
}
);
}
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '';
getModalData(userId, function (arrayedUserData) {
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
});

get value in php from js function

I am confused that how to get data from js to php variable.In JS function, I am getting data frequently on event.The problem is I want to get data in php frequently because it is real time data.payload contains the data whenever the data comes.So I have to get value of payload continuously.
<html>
<head>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="mqttws31.js" type="text/javascript"></script>
<script>
function myFunction(p1, p2) {
return p1 * p2;
};
var mqtt,payload;
var value = 10;
var reconnectTimeout = 2000;
function MQTTconnect() {
if (typeof path == "undefined") {
path = '/mqtt';
}
mqtt = new Paho.MQTT.Client(
'broker',
1883,
"/mqtt",
"a:" + "abcdef" + ":" + Date.now()
);
var options = {
timeout: 3,
useSSL: false,
cleanSession: true,
onSuccess: onConnect,
onFailure: function (message) {
$('#status').val("Connection failed: " + message.errorMessage + "Retrying");
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
options.userName = 'user';
options.password = 'password';
mqtt.connect(options);
}
function onConnect() {
document.writeln("connected");
// Connection succeeded; subscribe to our topic
mqtt.subscribe('iot-2/type/+/id/+/evt/evt1/fmt', {qos: 0});
//$('#topic').val('iot-2/type/" + "+" + "/id/" + "+" + "/evt/evt1/fmt');
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
//$('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");
};
function onMessageArrived(message) {
var topic = message.destinationName;
payload = message.payloadString;
//document.writeln(payload);
//document.write("\n");
//$('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
};
</script>
</head>
<body>
<?php
$db = '<script type="text/javascript">document.write(MQTTconnect());</script>';
$db1 = '<script type="text/javascript">document.write(payload);</script>';
echo $db;
echo $db1;
?>
</body>
</html>
You can do something like
echo '<script type="text/javascript">'
, 'document.write(MQTTconnect());'
, '</script>'
;
the applicable way to get data in php frequently is to assign js data for an php element when it change .
for example , when js function executed you can write
$("Element").val(output)// from js function
, $("element").html(output) or
by document.getElementById(element) etc...`
So , any change will change the value of php element accordingly

ajax post to php not actually writing to the mysql table

$(document).ready(function() {
$('#save').click(function() {
var rows = [];
for (i = 1 ; i < document.getElementById("schedule").rows.length ; i++) {
var name;
var tuesday;
var wednesday;
var thursday;
var friday;
var saturday;
var sunday;
name = document.getElementById("schedule").rows[i].cells[0].firstChild.value;
tuesday = document.getElementById("schedule").rows[i].cells[1].firstChild.value;
wednesday = document.getElementById("schedule").rows[i].cells[2].firstChild.value;
thursday = document.getElementById("schedule").rows[i].cells[3].firstChild.value;
friday = document.getElementById("schedule").rows[i].cells[4].firstChild.value;
saturday = document.getElementById("schedule").rows[i].cells[5].firstChild.value;
sunday = document.getElementById("schedule").rows[i].cells[6].firstChild.value;
monday = document.getElementById("schedule").rows[i].cells[7].firstChild.value;
rows[i-1] = "name=" + name + "&tuesday=" + tuesday + "&wednesday=" + wednesday + "&thursday=" + thursday + "&friday=" + friday + "&saturday=" + saturday + "&sunday=" + sunday + "&monday=" + monday;
}
for (i = 0 ; i < rows.length ; i++) {
$.ajax({
type: "POST",
url: "save-schedule.php",
data: rows[i],
success: function () {
alert("POST successful");
}
});
}
});
});
The javascript array is working correctly and showing the correct format and the ajax success function is executing. It shows the alert "POST Successful" but then after checking the mysql table it is empty.
<?php
$servername = "localhost";
$username = "";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$conn->select_db("little_caesar");
$name=$_POST["name"];
$tuesday=$_POST["tuesday"];
$wednesday=$_POST["wednesday"];
$thursday=$_POST["thursday"];
$friday=$_POST["friday"];
$saturday=$_POST["saturday"];
$sunday=$_POST["sunday"];
$monday=$_POST["monday"];
$conn->query("INSERT INTO schedule (name,tuesday,wednesday,thursday,friday,saturday,sunday,monday) VALUES('$name','$tuesday','$wednesday','$thursday','$friday','$saturday','$sunday','$monday')");
$conn->close();
?>
this is the save-schedule.php any help would be great! Thanks in advance!
Remove '&' symbol from ajax data change instead of , symbol like
rows[i-1] = "{name=" + name + ",tuesday=" + tuesday + ",wednesday=" + wednesday + ",thursday=" + thursday + ",friday=" + friday + ",saturday=" + saturday + ",sunday=" + sunday + ",monday=" + monday+"}";
Probably error from your MySQL username. Look your PHP code:
$username = "";
Are you sure your username is blank, because MySQL default username is 'root'.

populated jquery objects show as undefined when passed

In the following script, although the two weather objects are both populated with data in the ajax calls, the updateWeather call shows them both as undefined prior to that line executing. I moved the variable declarations so they would be global but they still both show undefined prior to the updateWeather call. What am I missing? Can I not set up a variable in the ajax success function and then pass it later?
Note: If you want to test this use a different url as this one won't work for you with out my credentials
function getWeatherForecastStationCode() {
var d = new Date();
var parts = d.toString().split(" ");
var dDate = parts[1] + " " + parts[2] + ", " + parts[3];
var ampm;
if (parts[4].split(":")[0] <= 12) {
ampm = "AM";
} else {
ampm = "PM";
}
var dtime = parts[4].split(":")[0] + ":" + parts[4].split(":")[1];
var datetime = dDate + " " + dtime + ampm;
alert(datetime);
var weatherStation = "KPBI"; // get from GetWeatherService.svc
var forecastFields = "&fields=periods.maxTempF%2cperiods.minTempF%2cperiods.vaildTime%2cperiods.weather%2cperiods.icon";
var currentFields = "&fields=ob.tempC%2cob.tempF%2cob.icon%2cplace.name%2cplace.state";
var forecastUrlWeatherStation = 'http://api.aerisapi.com/forecasts/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + forecastFields;
var currentUrlWeatherStation = 'http://api.aerisapi.com/observations/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + currentFields;
$.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
forecastedWeather = {
weather: json.response[0].periods[0].weather,
maxTemp: json.response[0].periods[0].maxTempF,
minTemp: json.response[0].periods[0].minTempF,
weatherIcon: json.response[0].periods[0].icon,
obsTime: datetime
};
}
else {
alert('An error occurred: ' + json.error.description);
}
}
});
var location;
$.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
var place = json.response.place.name.split(" ");
if (place.length === 1) {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length);
} else {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length) + " " + place[1].charAt(0).toUpperCase() + place[1].substr(1, place[1].length) + ", " + json.response.place.state.toUpperCase();
}
currentWeather = {
location: location,
currentTemp: json.response.ob.tempF
};
} else {
alert('An error occurred: ' + json.error.description);
}
}
});
updateWeather(forecastedWeather,currentWeather);
}
The problem is that AJAX is Asynchronous (Thats the "A" in "AJAX"), so the call to updateWeather is executing before a response is received from your 2 ajax calls.
The way to do this then, is to wait for all ajax calls to complete before calling updateWeather.
Something like the following (untested):
$.when(getForecast(),getCurrent()).done(function(f,c){
updateWeather(forecastedWeather,currentWeather)
});
function getForecast(){
return $.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json"
....
});
};
function getCurrent(){
return $.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json"
....
});
};

Categories