$(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'.
Related
So I am trying to display the information that I have retrieved from a database and I'm using Javascript to pass these info to their corresponding tags using the IDs. I have no problem with outputting the text, but I am having a hard time to output the images in the database which is a MediumBLOB.
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var buffer = new Buffer(userid.images);
var bufferBase64 = buffer.toString('base64');
$('#img').attr("src", "data:image/jpeg;base64," + bufferBase)
});
$('#viewModal').modal("show");
}
As for the update.php, here is the condition that receives the Post method.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'phpfinals');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ".$conn->connect_error);
}
//Sending details to be viewed
if(isset($_POST['sendview']))
{
$user_id = $_POST['sendview'];
$stmnt = mysqli_query($conn,"SELECT `username`, `password`, `firstname`, `middlename`, `lastname` , `gender`, `yearlevel`, `position`, `accesslevel`, `images` FROM phpfinals.records WHERE `username` = $user_id");
$result=array();
while($row = mysqli_fetch_assoc($stmnt))
{
$result = $row;
}
echo json_encode($result);
}
else
{
$response['status'] = 200;
$response['message'] = "Invalid or data not found";
}
?>
try creating an URL object
function ShowDetails(viewid)
{
$('#view').val(viewid)
$.post("update.php",{sendview:viewid},function(data,
status){
var userid = JSON.parse(data);
$('#uname').text("Username: " + userid.username)
$('#pass').text("Password: " + userid.password)
$('#fname').text("First Name: " + userid.firstname)
$('#mname').text("Middle Name: " + userid.middlename)
$('#lname').text("Last Name: " + userid.lastname)
$('#gen').text("Gender: " + userid.gender)
$('#yearlevel').text("Year Level: " + userid.yearlevel)
$('#pos').text("Position: " + userid.position)
$('#accesslevel').text("Access Level: " + userid.accesslevel)
var objectURL = URL.createObjectURL(userid.images);
$('#img').attr("src", objectURL)
});
$('#viewModal').modal("show");
}
and as a suggestion not related to your question instead of echo should be better use return for send the result
return json_encode($result);
I am trying to populate a HTML table using JQUERY, AJAX and PHP code. When I run my code, my table is displayed but it is filled with 'undefined'.
I have three pieces of code. Here is my HTML and jQuery:
var integer = $("#transfers_in").attr("name");
alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {
dataType: 'json',
myData: integer
}, // data to submit
success: function(response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var name = response[i].name;
var amount = response[i].amount;
var tr_str = "<tr>" +
"<td align='center'>" + (i + 1) + "</td>" +
"<td align='center'>" + name + "</td>" +
"<td align='center'>" + amount + "</td>" +
"</tr>";
$("#money_in").append(tr_str);
}
}
});
<table id="money_in">
<tr>
<th>Name</th>
<th>Amount(Million £)</th>
</tr>
</table>
and here is my PHP Code:
<?php
if (isset($_POST['myData'])) {
$integer = $_POST['myData'];
if ($integer === "1"){
include 'db_connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$return_arr = array();
$query = "SELECT * FROM `money_in_19_20`";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result)){
$name = $row['Name'];
$amount = $row['Amount'];
$return_arr[] = array("Name" => $name,
"Amount" => $Amount);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
}
The Json data is being received in the format of
{"Name":"Hazard","Amount":"103000000"}
You are returning object as Name,Amount and checking as name,amount
var name = response[i].name;
var amount = response[i].amount;
it should be
var name = response[i].Name;
var amount = response[i].Amount;
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.
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
function retrieveHasilRawatJalan(row, kd_klp) {
var hasil_rawat_jalan2 = <?php echo
Modules::run("lab/get_row_content_from_lab_code","HL-024") ?>;
}
how to replace "HL-024" with variable kd_klp?
i get an error if i use it this way
function retrieveHasilRawatJalan(row, kd_klp) {
var hasil_rawat_jalan2 = <?php echo
Modules::run("lab/get_row_content_from_lab_code",?>kd_klp<?php) ?>;
}
the error say Parse error: syntax error, unexpected '?>'
if my question isnt clear, please ask Thanks^^
UPDATE
Before add AJAX
/**
*
* #param {type} id
* #returns {undefined}
*/
function retrieveHasilRawatJalan(row) {
var hasil_rawat_jalan2 = <? php echo Modules::run("lab/get_row_content_from_lab_code", "HL-003") ?> ;
//var hasil_rawat_jalan2 = <?php //echo Modules::run("lab/get_row_content_from_lab_code", row) ?>;
var number_of_row = parseInt(Object.size(hasil_rawat_jalan2));
var row_start = parseInt(row);
addNewRow(number_of_row);
var row_end = (number_of_row + row_start);
j = 1;
for (i = row_start; i <= row_end; i++) {
document.getElementById('SUBKLP[' + i + ']').value = hasil_rawat_jalan2[j]['sub_klp'];
document.getElementById('NAMA[' + i + ']').value = hasil_rawat_jalan2[j]['name_of_inspection'];
document.getElementById('KODE[' + i + ']').value = hasil_rawat_jalan2[j]['inspection_id'];
document.getElementById('HASIL[' + i + ']').value = hasil_rawat_jalan2[j]['result'];
//document.getElementById('NILAI_NORMAL[' + i + ']').value = hasil_rawat_jalan2[j]['normal_result'];
document.getElementById('NILAI_NORMAL[' + i + ']').value = 'null';
document.getElementById('SATUAN[' + i + ']').value = hasil_rawat_jalan2[j]['measure_unit'];
document.getElementById('KDKLP[' + i + ']').value = hasil_rawat_jalan2[j]['klp_id'];
j++;
}
console.log("row start: " + row_start + ", row end:" + row_end + ", column length: " + number_of_row);
}
After Add AJAX
/**
* test ajax
* #param {type} row
* #returns {undefined}
*/
function retrieveHasilRawatJalan2() {
var row = "HL-003";
var hasil_rawat_jalan2;
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//document.getElementById("demo").innerHTML = xhttp.responseText; //to print on <p id="demo"></p>
hasil_rawat_jalan2 = xhttp.responseText;
}
}
//this isnt work
xhttp.open("POST", "<?php echo site_url("
lab / get_row_content_from_lab_code / ") ?>" + row, true);
//this work
xhttp.open("POST", "<?php echo site_url("
lab / get_row_content_from_lab_code /HL-003") ?>", true);
xhttp.send();
var number_of_row = parseInt(Object.size(JSON.parse(hasil_rawat_jalan2))); //try to change hasil_rawat_jalan2 to json but fail.
var row_start = parseInt(row);
addNewRow(number_of_row);
var row_end = (number_of_row + row_start);
j = 1;
for (i = row_start; i <= row_end; i++) {
document.getElementById('SUBKLP[' + i + ']').value = hasil_rawat_jalan2[j]['sub_klp'];
document.getElementById('NAMA[' + i + ']').value = hasil_rawat_jalan2[j]['name_of_inspection'];
document.getElementById('KODE[' + i + ']').value = hasil_rawat_jalan2[j]['inspection_id'];
document.getElementById('HASIL[' + i + ']').value = hasil_rawat_jalan2[j]['result'];
//document.getElementById('NILAI_NORMAL[' + i + ']').value = hasil_rawat_jalan2[j]['normal_result'];
document.getElementById('NILAI_NORMAL[' + i + ']').value = 'null';
document.getElementById('SATUAN[' + i + ']').value = hasil_rawat_jalan2[j]['measure_unit'];
document.getElementById('KDKLP[' + i + ']').value = hasil_rawat_jalan2[j]['klp_id'];
j++;
}
console.log("row start: " + row_start + ", row end:" + row_end + ", column length: " + number_of_row);
}
problems after update ajax,
I assign var row = "HL-003"; but i wasnt able to assign variable row to xhttp.open("POST", "<?php echo site_url("
lab / get_row_content_from_lab_code / ") ?>" + row, true); unless i write it directly like this xhttp.open("POST", "<?php echo site_url("
lab / get_row_content_from_lab_code /HL-003") ?>", true);
I get result from xhttp.open("POST", "<?php echo
site_url("
lab / get_row_content_from_lab_code /HL-003") ?>", true); but it return string not object eventhough format of the string is the same. so i change hasil_rawat_jalan2 = xhttp.responseText; and add JSON.parse(hasil_rawat_jalan2); //try to change hasil_rawat_jalan2 to object but fail.
Its impossible to place a javascript value (clientside) in PHP (serverside).
Unless you use AJAX to get the page and send the variable along as a POST/GET value.
javascript values get stored in your browser after the page has been loaded. And PHP executes before the page is sent to the browser. Therefor this is impossible in the way you want it in your question. (For as far as i understand the question :p)
Example for ajax request
I have a dilema. I've created this order request page for a website I'm building, and here's how it works:
You check/uncheck core items, and based on it's state (active or unactive), it'll apply a true/false value to a boolean in the coresponding order.js. Likewise, it'll take desired unit count for other items, and your information, and apply them to variables.
It groups those variables into arrays and, right now, console.log() them.
Here's where the trouble comes...this is a snippet of the order.js file.
function compileInfo() {
console.log("compileInfo active");
var name = "Name: " + $("#name").val() + "\n";
var email = "Email: " + $("#email").val() + "\n";
var phone = "Phone: " + $("#phone").val() + "\n";
var weddingDate = "Wedding Date: " + $("#date").val() + "\n";
var comments = "Comments: " + $("#comments").val() + "\n";
var base = "Base Experience: " + $("#base").hasClass("active") + "\n";
var special = "Special Edition: " + $("#special").hasClass("active") + "\n";
var teaser = "Teaser Trailer: " + $("#teaser").hasClass("active") + "\n";
var raw = "Raw Footage: " + $("#raw").hasClass("active") + "\n";
var standard = "Standard Shipping: " + $("#standard").hasClass("active") + "\n";
var expedited = "Expedited Shipping: " + $("#expedited").hasClass("active") + "\n";
var dvd = "Standard DVD: " + a + "\n";
var br = "Standard Blu-Ray: " + b + "\n";
var dvdSe = "Special DVD: " + x + "\n";
var brSe = "Special Blu-Ray: " + y + "\n";
var info = new Array();
info[0] = name;
info[1] = email;
info[2] = phone;
info[3] = weddingDate;
info[4] = comments;
var services = new Array();
services[0] = base;
services[1] = special;
services[2] = teaser;
services[3] = raw;
var delivery = new Array();
delivery[0] = standard;
delivery[1] = expedited;
var extras = new Array();
extras[0] = dvd;
extras[1] = br;
extras[2] = dvdSe;
extras[3] = brSe;
var dataVar = info + "\n" + services + "\n" + delivery + "\n" + extras;
var dataVarJSON = JSON.stringify(dataVar);
console.log(dataVar);
$.ajax({
type: "POST",
url: "order.php",
data: {data : dataVarJSON},
success: function() {
console.log("SUCCESS");
}
});
}
function validate() {
var name = $("#name").val();
var email = $("#email").val();
var weddingDate = $("#date").val();
if (name === "" || email == "" || weddingDate == "") {
alert("You must complete all required fields to send this request.");
} else {
console.log("working");
compileInfo();
return true;
}
}
Here's my recieving PHP:
<?php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
$body = json_decode(stripslashes($_POST['data']));
$to = "thekevinhaube#gmail.com";
$subject = "Order Request";
function sendInfo() {
mail($to, $subject, $body);
}
?>
Now, I'm far from a PHP expert. This is my first encounter with it, in fact. How can I get it to send. It seems to POST just fine, but isn't sending to the email adress listed. Any and all help is appreciated! Again, this is my first time with PHP, so...
You need to give sendInfo some parameters:
function sendInfo($to, $subject, $body) {
...
}
And don't try mail() on your localhost, try it - if possible - online.