I'm trying to send data to a php file to save in database, but I don't have any response. If a checkbox is check, the [obj][idCheckbox] = 1, else [obj][idCheckbox] = 0.
File that sends
var i=0;
var objetoTodasPermissoes = function(){};
var objTodasPermissoes = new objetoTodasPermissoes();
$.each($(".classePermissoes"), function(){
objTodasPermissoes[$(this)[0].id] = 0
i++;
});
$.each($(".classePermissoes:checked"), function(){
alert('ok');
objTodasPermissoes[$(this)[0].id] = 1;
});
console.log(objTodasPermissoes);
$.each($("#userList tr"),function(){
alert(this.id);
var iduser = this.id;
$.ajax({
url:'../json/usuarioperm/savePermissions.php',
data:({
idusuario:iduser,
objTodasPermissoes:objTodasPermissoes,
}),
success:function(a){
Alert("Saved!");
}
});
});
}
the savePermissions.php file.
$iduser = $_POST["iduser"];
$perm_usuarios = $_POST["objTodasPermissoes"]["perm_usuarios"];
$perm_importar = $_POST["objTodasPermissoes"]["perm_importar"];
$perm_log = $_POST["objTodasPermissoes"]["perm_log"];
$perm_proto = $_POST["objTodasPermissoes"]["perm_proto"];
$perm_limpeza = $_POST["objTodasPermissoes"]["perm_limpeza"];
$perm_lixeira = $_POST["objTodasPermissoes"]["perm_lixeira"];
$perm_relatusuarios = $_POST["objTodasPermissoes"]["perm_relatusuarios"];
$perm_deptos = $_POST["objTodasPermissoes"]["perm_deptos"];
$perm_deptospastas = $_POST["objTodasPermissoes"]["perm_deptospastas"];
$perm_empresas = $_POST["objTodasPermissoes"]["perm_empresas"];
mysql_query("UPDATE hospital.users set
perm_usuarios=".$perm_usuarios.",
perm_importar=".$perm_importar.",
perm_log=".$perm_log.",
perm_proto=".$perm_proto.",
perm_limpeza=".$perm_limpeza.",
perm_lixeira=".$perm_lixeira.",
perm_relatusuarios=".$perm_relatusuarios.",
perm_deptos=".$perm_deptos.",
perm_deptospastas=".$perm_deptospastas.",
perm_empresas=".$perm_empresas." where id=".$iduser) or die (mysql_error());
Thank you.
PHP is kind of interesting in that it doesn't pull from $_POST like other forms when Ajax is involved. You actually will need to read the input from php://input
Here is a tiny example
$data = file_get_contents("php://input");
$response = json_decode($data, true ); // True converts to array; blank converts to object
$emailAddr = $response["email"];
Hopefully you can apply that successfully.
Edit: You can add the filter_var command to strip bad characters and sanitize the input.
$emailAddr = filter_var($response["email"], FILTER_SANITIZE_EMAIL);
$firstName = filter_var($response["firstName"], FILTER_SANITIZE_STRING);
While debugging this I would highly recommend using Chrome's Developer mode with the 'network' tab. Find your ajax call near the bottom and you can view exact header info.
Related
I have a web app that is basically a huge form that will eventually be transformed into a pdf. When the form is submitted, all the input gets sent to a php file that stores them as variables to be added to the pdf. Some of the data I need on the pdf is calculated in JavaScript, so I am using ajax to send those calculated variables to the same php file that the form sends its data to. The ajax call is not sending the data to the php script. I tried to echo some of the variables, but nothing shows up. Here is my ajax call:
$.ajax({
url: 'FMpdf_values.php',
method: 'POST',
data: {elevChartImg : elevChartImg, azChartImg : azChartImg, power_rating : power_rating, antWeight : antWeight, antennaWithRadomeWeight : antWithRadomeWeight,
epa : epa, radome : radome, deicer : deicer, thetaCol : thetaCol, afAmpCol : afAmpCol, dbCol : dbCol, product : product, channelFM : channelFM,
antLongDescription : antLongDescription, antShortDescription : antShortDescription},
success:function(data){
console.log(data);
}
});
The PHP file is just setting the variables to $_POST['some_data'], then that file is included in the PHP file that creates the pdf. I am relatively new to both PHP and ajax, so I apologize if this is an easy fix. I am wondering if it is even possible to get values from the HTML form and ajax in the same file?
FMpdf_values.php:
<?php
//PHP file for getting the values needed for the PDF
//All html element variables are added here, while calculated values are passed through AJAX
header("Content-Type: application/json", true); //For accepting JSON data
//HTML Element Variables
$projectName = $_POST['projectTitle'];
$customer = $_POST['customer'];
$location = $_POST['location'];
$antModel = $_POST['tlantennaModel'];
$specCode = $_POST['specNumber'];
$createdBy = $_POST['completedBy'];
$notes = $_POST['notes'];
$date = date("F j, Y");
$revDate = $_POST['revisionDate'];
$freq = $_POST['channelNum'];
$wavelength = "11807.22891";
$gainVal = $_POST['tlhorPeakPower'];
$erpVal = $_POST['tlhorERP'];
$beamtilt = $_POST['beamTiltVal'];
$firstNull = $_POST['firstNull'];
$secondNull = $_POST['secondNull'];
$rfInput = $_POST['rfInputs'];
$antennaHeightFt = $_POST['antennaHeightFt'];
$antennaHeightMt = $_POST['antennaHeightMt'];
$CORHeightFt = $_POST['CORHeightFt'];
$CORHeightMt = $_POST['CORHeightMt'];
$ovrHeightFt = $_POST['overallHeightFt'];
$ovrHeightMt = $_POST['overallHeightMt'];
$vertLineType = $_POST['tlTypeVertSelect'];
$vertLineLengthFt = $_POST['tlvertft'];
$vertLineLengthMt = $_POST['vertLengthMeters'];
$vertAttenFt = $_POST['tlvertatten'];
$vertAttenMt = $_POST['tlVertAttenMt'];
$horLineType = $_POST['tlTypeHorSelect'];
$horLineLengthFt = $_POST['tlhorft'];
$horLineLengthMt = $_POST['horLengthMeters'];
$horAttenFt = $_POST['tlhoratten'];
$horAttenMt = $_POST['tlhorattenmt'];
$transLineLosskW = $_POST['tranlinelossKW'];
$transLineLossdB = $_POST['tranlinelossdb'];
$transLineEff = $_POST['tlefficiency'];
$antInputPowerkW = $_POST['antennaInputPowerkw'];
$antInputPowerdB = $_POST['antennaInputPowerdBk'];
$isoTranLosskW = $_POST['isoLosskw'];
$isoTranLossdB = $_POST['isoLossdB'];
$filterLosskW = $_POST['filterLosskw'];
$filterLossdB = $_POST['filterLossdB'];
$systemLosskW = $_POST['systemLosskw'];
$systemLossdB = $_POST['systemLossdB'];
$totalLosskW = $_POST['totallosskw'];
$totalLossdB = $_POST['totallossdB'];
$TPOkW = $_POST['poweroutputkw'];
$TPOdB = $_POST['poweroutputdB'];
$systemEff = $_POST['otherSystemEfficiency'];
//Variables from AJAX
$elevChartImg = $_POST['elevChartImg'];
$azChartImg = $_POST['azChartImg'];
$power_rating = $_POST['power_rating'];
$antWeight = $_POST['antWeight'];
$antWithRadomeWeight = $_POST['antWithRadomeWeight'];
$epa = $_POST['epa'];
$radome = $_POST['radome'];
$deicer = $_POST['deicer'];
$thetaCol = $_POST['thetaCol'];
$afAmpCol = $_POST['afAmpCol'];
$dbCol = $_POST['dbCol'];
$product = $_POST['product'];
$channelFM = $_POST['channelFM'];
$antLongDescription = $_POST['antLongDescription'];
$antShortDescription = $_POST['antShortDescription'];
//ThetaCol, afAmpCol, & dbCol are currently JSON encoded objects
$thetaCol = json_decode($thetaCol);
$afAmpCol = json_decode($afAmpCol);
$dbCol = json_decode($dbCol);
die(print_r($_POST));
You are basically calling your PHP script 2 times.
At the first time you are firing up an ajax call (Your php script executes at the server side and PDF generator code runs and generates invalid PDF, as you don't have the form data yet)
Second time the actual form is submitted, your PHP script executes again, this time you don't have the AJAX data, so again the target PDF will be invalid)
Instead of sending data in 2 parts (one part using form POST and another part using AJAX POST), have some hidden fields in your form, fire the javascript calculation function on click of your submit button, fill up the hidden fields and then submit the form. This way you get all the data at one go.
Let me know if that make sense and if you are able to proceed ahead or do you need some sort of code samples..
I have an HMTL form with 3 fields on it, Firstname, Lastname and image upload file. When submit is pressed it calls the following JS script.
//main function to be called on submit
function processData() {
var firstName = document.querySelector('#first-name'),
lastName = document.querySelector('#last-name'),
imageUser = document.querySelector('#image-user');
var formSubmitData = {
'firstName': firstName.value,
'lastName': lastName.value,
'imageUser': imageUser.value
};
var dataString = JSON.stringify(formSubmitData);
if (navigator.onLine) {
sendDataToServer(dataString);
} else {
saveDataLocally(dataString);
}
firstName.value = '';
lastName.value = '';
imageUser.value = '';
}
//called on submit if device is online from processData()
function sendDataToServer(dataString) {
var myRequest = new XMLHttpRequest();
//new code added so data is sent to server
//displays popup message - data sent to server
myRequest.onreadystatechange = function() {
if (myRequest.readyState == 4 && myRequest.status == 200) {
console.log('Sent to server: ' + dataString + '');
window.localStorage.removeItem(dataString);
} else if (myRequest.readyState == 4 && myRequest.status != 200) {
console.log('Server request could not be completed');
saveDataLocally(dataString);
}
}
myRequest.open("POST", "write_test.php", true);
//Send the proper header information along with the request
myRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myRequest.send(dataString);
alert('Sent: ' + dataString + ''); //remove this line as only for example
}
As you will see it sends a POST request to the php page. The "datastring" is encoded as JSON.
I use the following PHP code to send the data to the SQL server, but all it does is create a blank record with no data but it does create a new record.
<?php
//TRYING NEW CODE TO EXTRACT DATA FROM dataString
$json = json_decode(file_get_contents("php://input"), true);
$data = json_decode($json, true);
echo '<pre>' . print_r($data, true) . '</pre>';
// INSERT into your contact table.
$sql="INSERT INTO contacts (firstName, lastName)VALUES('$firstName','$lastName')";
How do I get it to create records in SQL with data that has been submitted from the form??
I have no final solution as I don't have the form code. Hope you are ready to learn.
I'm worried about user image - don't send any image for testing, but a string (like path) or nothing, please.
js - change for double quotes:
var formSubmitData = {
"firstName" : firstName.value,
"lastName" : lastName.value,
"imageUser" : imageUser.value
};
php - leave only this
<?php
$data = json_decode(file_get_contents("php://input")); // test only version
print_r($data); // test only version
/*
and close the rest as a comment - SQL is fine, don't worry
$data = json_decode(file_get_contents("php://input",true)); // final ver
echo print_r($data, true); // final ver
...
*/
If you receive the right output, delete the trial version and good luck.
If not - go back to var formSubmitData to the values on the right - they are so naked ... without any quotes
And of course, take care of security (injection) and order, set the required at the inputs - you don't need empty submits
I am beginner in web development so please understand me. I am trying to create a session using php file and call it in javascript using ajax request. but after I input the path of the index.html in address bar, it always shows the index. I want to know how can i possibly do this with javascript and php. restricting the all the pages of the site if there is no user active.
for example logic:
if (userhasValue == true) {
//redirect to index and can access the whole website
} else {
// redirect to login page
}
I have tried the code below but it still redirecting to index.html even if the data recieve in ajax request is empty.
<?php
include('config.php');
session_start();
$user_check = $_SESSION['login_user'];
$temparray = array();
$ses_sql = mysqli_query($db,"select user_id,username,fullname from user where username = '$user_check'");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
if ($row > 0 ){
array_push($temparray, $row); //save your data into array
echo json_encode($temparray);
} else {
echo 'Error';
}
?>
function getUser(){
var user ='';
var fullname ='';
var id ='';
var tempArray = '';
var name = '';
$.ajax({
type:'POST',
url:'../bench/php/session.php',
data:'',
success:function(msg){
alert(JSON.stringify(msg));
let tempArray = JSON.parse(msg)
user = JSON.stringify(tempArray[0]['username']);
fullname = JSON.stringify(tempArray[0]['fullname']);
id = JSON.stringify(tempArray[0]['id']);
document.getElementById('fullname').innerHTML = fullname;
if (msg == 'Error') {
window.location.href = "../pages-login.html";
}
}, error: function(e){
console.log(e);
}, complete: function(c){
console.log(c);
}
});
}
The code above does not restrict the accessibility of the index.html and other pages if the user is not logged in.
I want to restrict the index page and other pages if the user try to redirect to index page without logging in.
Please help me. Any help will much be appreciated! Thanks in advance
I want to transfer some coordinates to php (server-side) from javascript (client-side) via Ajax, and after processing (filter, etc) I want to retrieve the result to javascript, for use. The pass to php working, but I don't know how get and use the processed result from php. Any help is highly appreciated.
The php part script is:
$dbconn = pg_connect ("host=localhost port=5432 user=postgres password=xxxxxxx dbname=yyyyyyyy") or die('can not connect!'.pg_last_error());
//The nearest point of Start point
$ss='';
if (isset($_POST['kuldes_st'])){
$kuldes=$_POST['kuldes_st'];
$latk=$_POST['lat_st'];
$lngk=$_POST['lng_st'];
$query = "SELECT ST_X(the_geom), ST_Y(the_geom) FROM tbl_mypoints ORDER BY ST_Distance(the_geom, ST_GeomFromText('POINT($latk $lngk)', 4326)) LIMIT 1";
//$result = pg_query($query) or die('The query failed: ' . pg_last_error());
$result = pg_query($dbconn,$query);
if (!$result) {
die('The query failed: ' . pg_last_error());
}
else {
while ($line =pg_fetch_row($result))
{
$latitude=$line[0];
$longitude =$line[1];
$ss .= "L.latLng(".$latitude.", ".$longitude.")";
}
}
echo json_encode($ss);
}
Javascript code:
map.on('click', function(e) {
var container = L.DomUtil.create('div'),
startBtn = createButton('Start from this location', container),
destBtn = createButton('Go to this location', container);
nearestBtn = createButton('Find and go to nearest parking', container);
//Start
L.DomEvent.on(startBtn, 'click', function() {
control.spliceWaypoints(0, 1, e.latlng);
var lats=e.latlng.lat;
var lngs=e.latlng.lng;
$.ajax({
url : 'index.php',
type : 'POST',
async : true,
data : { 'kuldes_st':1,
'lat_st': lats,
'lng_st': lngs
},
success: function(data,response) {
if (response == 'success') {
alert("Post working fine");
alert(response);
console.log(data);
} else {
alert("Post don't working");
console.log(data);
}
}
});
map.closePopup();
});
I think the main problem is how to use return value.
in index.php file , you can return value without html tags. for example, if you wants to return array of number, just use code like this:
echo implode($array,",");
the data that return by ajax function is some things like this:
1,2,4,2
you can split this string to a javascript array with code like this:
var result = data.split(",");
after it, you can use the array result every where you want in jquery code.
My PHP is a bit rusty but I think the issue is that you are returning a string that is not JSON but trying to pack it up like JSON.
I think you want something more like
$ss = array();
while ($line =pg_fetch_row($result))
{
$latlng = array();
$latlng["lat"] = $line[0];
$latlng["lng"] = $line[1];
array_push($ss,$latlng);
}
echo json_encode($ss)
Forgive my PHP if it's wrong, but hopefullly from this you get the idea. At this point, the thing the server will return should look like real JSON like (
[
{"lat":46.5,"lng":24.5},
{"lat":46.5,"lng":24.5},
...
]
Then in the javascript, you can just deal with it like an array.
var latitudeOfTheFirstEntry = data[0].lat;
var longitudeOfTheSecondEntry = data[1].lng;
Do you know what L.latLng is supposed to be providing. This solution I've outlined is not using that and if that is needed, there maybe more work to figure out where that is supposed to happen.
Hope this helps
I am trying to modify a Cookie through an Ajax petition but it doesn't work. It modifies the Session but not the cookie. Here is my code:
HTML:
<li class="en_GB" id="1" onclick="changeLanguage('en_GB;1')"><span></span>ENGLISH</li>
Javascript:
function changeLanguage(lang){
$.ajax({
url: 'lib/loadLanguageList.php',
data: {lan: lang},
type: 'POST',
success: function(data){
location.reload();
}
});
}
PHP (loadLanguageList.php) / Action:
if(isset($_POST['lan']) && preg_match("/([a-z]+_[A-Z]+;[0-9]+)/", $_POST['lan'])){
setUserLanguage($_POST['lan']);
}
PHP (loadLanguageList.php) / function EDITED*:
(Following the suggestion of #MikeBrant, I've edited the function)
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
}
setcookie("locale","",time()-2592000);
setcookie("locale_id","",time()-2592000);
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
print_r($locale);
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
But the cookie is not being deleted and the print_r print $locale variable as it should be. I don't understand why the setcookie function didn't work.
First, let's rewrite your function to where it makes better logic sense in terms of the code path flow (i.e. we have simplified the conditionals).
function setUserLanguage($lan){
$locale['value'] = "";
$locale['id'] = "";
if(isset($lan)){
$lan = explode(";", $lan);
$locale['value'] = $lan[0];
$locale['id'] = $lan[1];
if(!isset($_COOKIE["locale"])){
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
} else {
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
}
} else if (!isset($_COOKIE["locale"])){
$lan = $this->getUserLanguage();
$locale['value'] = $lan[0]['value'];
$locale['id'] = $lan[0]['id'];
setcookie("locale",$locale['value'],time()+60*60*24*30);
setcookie("locale_id",$locale['id'],time()+60*60*24*30);
}
$_SESSION['locale'] = $locale['value'];
$_SESSION['locale_id'] = $locale['id'];
require_once(ROOT."/lib/utils/localization.php");
}
Now let's walk through the use cases here. Let's say the user already has a locale cookie set and they are trying to change it.
This user would pass this conditional:
if(isset($lan))
And should fail this conditional
if(!isset($_COOKIE["locale"]))
This means this code block would be executed:
$_COOKIE["locale"] = $locale['value'];
$_COOKIE["locale_id"] = $locale['id'];
This would change the cookie value for the duration of the script execution only, as nothing in the response to the browser would trigger a change in cookie value.
My guess is that you want to ALWAYS call setcookie().
Also I would think the whole (!isset($lan)) section of code could be removed in favor for throwing some kind of error, as having a "set" function without passing it a value doesn't seem to make much sense.