I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.
Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?
Not very sure with AJAX and all so Thanks for helping!
This is for the "Save" button.
<input type="button" onClick="save();" value="Save">
This is the insert query whereby it will be inserted in database.
<?php
include("dbFunctions.php");
$idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);
while ($row = sqlsrv_fetch_array($idResult)) {
$fcID = $row['id'];
$question = $row['question'];
$surveyTitle = $_SESSION['surveyTitle'];
$input = $row['input'];
if (isset($_POST['qns' . $fcID])) {
$answer = implode(",", $_POST['qns' . $fcID]);
$newAns = str_replace($singleQuote,$changeQuote,$answer);
} else {
$newAns = '';
}
if (isset($_POST['others'.$fcID])) {
$others = $_POST['others' . $fcID];
$newOthers = str_replace($singleQuote,$changeQuote,$others);
}else {
$newOthers = 'N.A.';
}
$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo);
if ($input != 'Normal text line, no input required*') {
$query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";
$status = sqlsrv_query($newconn, $query);
} }
if ($status === false) {
die(print_r(sqlsrv_errors(), true));
}
sqlsrv_close($conn);
You can use jquery $.ajax() to send data from client side to PHP. (eg)
$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});
Then in PHP page, use $_POST[] to capture data and insert it into database.
$id = $_POST['id'];
$name = $_POST['name'];
Make sure you escape the values and make it safe for sql insert.
Related
I'm trying to edit a post using this snippiet of from my query.php page:
echo '<button type="submit" onclick="openModal(this)" id="btn-edit"
name="edit" value='.$postID.'></button>';
function openModal(id)
{
var editpost = id.value;
$.ajax({
url:"query.php",
method:"POST",
data:{ editpost : editpost },
success:function(data)
{ //
},
error: function () {//
}
});
$('#edit').modal('show');
}
The function to get the data from the post selected is on the same php page. This is the code:
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$_SESSION['editpostdesc'] = $row['PostDesc'];
$_SESSION['editpostfile'] = $row['PostFile'];
$_SESSION['editpostid'] = $row['PostId'];
}
}
}
}
But the modal is on the other page (main page). I want to get the data of the post and display it on the modal, so I tried using $_SESSION. Yes, I got the data and was able to display it on the modal, but the problem is when I try to edit another post, the first value assigned to the session cannot be replaced. Is there is any other way that I can pass the values without using session? I'm really running out of ideas, I'm just starting my first web project.
if you get multiple row means this methods will worked...
if(isset($_POST['editpost']))
{
session_start();
$editpostid = $_POST['editpost'];
if($editpostid != "")
{
$sql = "SELECT * FROM post WHERE PostId = '" . $editpostid . "'";
}
if($sql != "")
{
$qry = mysqli_query($connection, $sql);
if (mysqli_num_rows($qry) > 0)
{
foreach($qry as $row)
{
$res[] = array(
'editpostdesc' => $row['PostDesc'],
'editpostfile' => $row['PostFile'],
'editpostid' => $row['PostId']
);
}
}
}
}
I am trying to create a website where users login with their google login (https://developers.google.com/identity/sign-in/web/sign-in). The site has multiple pages and gets data for the user from a mysql database. I would like to store the users' data (name, email) in a php session to have ready for the php when accessing the database. The login function works, but I can't figure out how to get the data to php, with it currently all in javascript.
There wasn't a conventional way to do this, but I was able to get the information from the google auth token
function get_var($var_index) {
$id = $_POST["id"];
$id_token = file("https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" . $id);
$var = str_replace("\"", "", $id_token[$var_index]);
$var = str_replace(",", "", $var);
$var = substr($var, strpos($var, ":") + 2 );
return $var;
}
$name = get_var(12);
$email = get_var(5);
$img_url = get_var(13);
$exp = get_var(8);
$iss = get_var(9);
if ($_SERVER['REQUEST_TIME'] < $exp) {
session_start();
$_SESSION["name"] = $name;
//$_SESSION["imageurl"] = $img_url;
$_SESSION["email"] = $email;
$_SESSION["exp"] = $exp; // when to auto logout
header("LOCATION: page.php");
exit();
} else{
header("LOCATION: loginpage.html");
}
You can use ajax for this. It's a very efficient way. just make sure you have jquery uncmopressed or minified (not slim) in you page and you're good to go.
This my javascript code in my page where the button is:-
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
$.ajax({
type: "POST",
url: "googlesignin.php?action=google",
data: "gmail=" + profile.getEmail() + "&name=" + profile.getName(),
success: function(result) {
if (result == 1) {
alert("Hello, " + profile.getName());
$("#googlesignin").hide();
} else {
alert("failed to login");
}
}
})
}
So now the new file called googlesignin.php from where you will execute the insert query to the mysql database
if ($_GET['action'] == "google") {
$email = $_POST['gmail'];
$name = $_POST['name'];
$query = "SELECT * FROM google WHERE email='".$email."' AND name='".$name."'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) > 0) {
echo 1;
} else {
$query = "INSERT INTO google (email, name) VALUES ('".$email."', '".$name."')";
$result = mysqli_query($link, $query);
echo 1;
}
}
so now we have stored our post variables as php variables and we can use them easily to execute our insert query. but we need to check whether the email has first registered or not.
I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.
I have the following query:
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
This will return a number for any new mailbox messages, I have found an ajax code for checking if there is a change.
Code:
var previousValue = null;
function checkForChange() {
$.ajax({
url: '',
...
success: function(data) {
if (data != previousValue) { // Something have changed!
//Call function to update div
previousValue = data;
}
}
});
}
setInterval("checkForChange();", 1000);
But I really need to figure out how to update the query without refreshing the entire page? I figured maybe something with ajax can help but I am totally new to ajax and I don't have an no idea where to start.
Update: ok so I wrote a php script for the queries but not sure how to get ajax script to use my "emails" var.
here is the script.
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die();
}
include("..\internals\config.php");
$host = DB_HOST;
$user = DB_USER;
$password = DB_PASS;
$dbname = DB_NAME;
$prefix = DB_TBL_PREFIX;
$cxn = mysql_pconnect ($host, $user, $password);
mysql_select_db($dbname, $cxn);
function get_user_id()
{
$userid = NULL;
if (!empty($_COOKIE['PHPSESSID']))
{
$result = $cxn->execute("
SELECT profile_id
FROM " . TABLE_PREFIX . "profile_online
WHERE hash = '" . $cxn->escape_string($_COOKIE['PHPSESSID']) . "'
");
if ($row = $cxn->fetch_array($result))
{
$userid = $row[0];
}
}
return $userid;
}
$profile_id = get_user_id();
public static function newMessages( $profile_id )
{
if (!isset($profile_id) || !is_numeric($profile_id))
return false;
if ( isset(self::$newMessageCountCache[$profile_id]) )
{
return self::$newMessageCountCache[$profile_id];
}
// check config for filter condition
$filter_cond = SK_Config::section('mailbox')->section('spam_filter')->mailbox_message_filter ? " AND `m`.`status`='a'" : '';
$query = "SELECT COUNT(DISTINCT `c`.`conversation_id`)
FROM `".TBL_MAILBOX_CONVERSATION."` AS `c`
LEFT JOIN `".TBL_MAILBOX_MESSAGE."` AS `m` ON (`c`.`conversation_id` = `m`.`conversation_id`)
WHERE (`initiator_id`=$profile_id OR `interlocutor_id`=$profile_id)
AND (`bm_deleted` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_deleted` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
AND (`bm_read` IN(0,".self::INTERLOCUTOR_FLAG.") AND `initiator_id`=$profile_id OR `bm_read` IN(0,".self::INITIATOR_FLAG.") AND `interlocutor_id`=$profile_id)
$filter_cond AND `m`.`recipient_id`=$profile_id
";
self::$newMessageCountCache[$profile_id] = SK_MySQL::query($query)->fetch_cell();
return self::$newMessageCountCache[$profile_id];
}
mysql_close($cxn);
$emails = newMessages();
?>
Ajax is correct - with Ajax you can send a request to the webserver which will execute your query and receive a request.
Its like visiting a page with the browser except that it happens in the background and not reloading the browsertab/page.
Lets say this is your file query.php and you can access it via my-domain.tld/query.php
query.php:
//First make this file only executeable for AJAX-Requests but no regular visit via browser:
if($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
die(); //User tried to enter query.php with a browser or similar...
}
//call function where query is stored or put your query here and save result
//Its important to echo what you want to be returned in the ajax-request.
echo self::$newMessageCountCache[$profile_id];
die(); //Best is die after last echo to make sure there are no extra outputs!
Now in your template or atleast where your HTML code is:
function checkForChange() {
$.ajax({
url: 'my-domain.tld/query.php', //See, here is the URL to your file on server
data: {}, //You need this only if you want to mpass any variables to your script. On PHP Server-side this data are available via $_POST array!
success: function(data) { //data contains all echo'ed content from query.php
$(".mailbox_messages").html(data); //The best is make your container to be updated to a class or ID to access. Its content can be overridden with .html() function. Simply echo all contents in query.php that you want to be displayed in your element and override the content with .html(data);
}
});
}
Now you just need to call checkForChange() when something special happens like a button click for example:
<input type="button" id="refresh-mailbox" value="Refresh my Mailbox" />
<script type="text/javascript">
$("#refresh-mailbox").on("click", function() {
checkForChange(); //Execute your function on button click and done!
});
</script>
I hope this helps. :)
I have this form:
<form method = \"get\" action = \"\" onsubmit = \"return addBeer('$user','$id','$name','$abv','$ibu','$icon','$style','$brewery','$breweryID','$icon')\" >
<p> <input type = \"submit\" value = \"Go Fishing\" /> </p>
</form>
which calls this JavaScript function:
function addBeer(user,id,bname,abv,ibu,icon,bstyle,brewery,breweryID,icon)
{
//get elements
alert('userID' + user);
alert('beerid'+id);
alert('beername'+bname);
alert('style'+bstyle);
alert('brewery'+brewery);
alert('abv'+abv);
alert('ibu'+ibu);
alert('brewery id'+ breweryID);
alert('icon'+icon);
//run ajax
var ajaxSettings2 =
{
type: "POST",
url: "addBeer.php",
data: "uID="+user+"&bID="+id+"&bName="+bname+"&bStyle="+bstyle+"&bBrewery="+brewery+"&abv="+abv+"&ibu="+ibu+"&breweryID="+breweryID,
success: function()
{
$('#sbutton').remove();
alert('Load was performed.');
},
error: function(xhr, status, error) { alert("error: " + error); } };
$.ajax(ajaxSettings2);
}
All the alerts work so I know for a fact that the information is getting passed fom the form to the function, but it fails on the ajax call to addBeer.php because it runs the error function and pop up the error alert. Unfortunetley nothing is reported in the pop up.
This is the addBeer.php file that is called to add to the database:
<?php
require_once('myConnectDB.inc.php');
require_once('page.inc.php');
session_start();
//add beer to database code
$userID = $_POST['uID'];
$beerName = $_POST['bName'];
$beerID = $_POST['bid'];
$brewery = $_POST['bBrewery'];
$style = $_POST['bStyle'];
$abv = $_POST['abv'];
$ibu = $_POST['ibu'];
$breweryID = $_POST['breweryID'];
//$icon = $_POST['icon'];
//get brewery icon
$uri3 = "http://api.brewerydb.com/v2/brewery/$breweryID?key=myKey&format=json";
$response3 = file_get_contents($uri3);
//parse xml
$myBrew = json_decode($response3);
$iconBrew = $myBrew->data->images->medium;
//add above data to database
$db = new myConnectDB();
$beerName = $db->real_escape_string($beerName);
$beerID = $db->real_escape_string($beerID);
$brewery = $db->real_escape_string($brewery);
$style = $db->real_escape_string($style);
$userID = $db->real_escape_string($userID);
$abv = $db->real_escape_string($abv);
$ibu = $db->real_escape_string($ibu);
$breweryID = $db->real_escape_string($breweryID);
$icon = $db->real_escape_string($icon);
$query3 = "INSERT INTO tableName (userID,beerID,beerName,beerStyle,beerBrewery,abv,ibu,breweryID,icon, brewIcon) VALUES ($userID, '$beerID', '$beerName', '$style' , '$brewery', '$abv','$ibu','$breweryID', '$icon', '$iconBrew')";
$db->query($query3);
?>
I took out my api key and table name for security.
I have checked the network tab in chrome under inspect element and when I click on addBeer.php call and look under headers it shows in form data that the information is being passed.
Update:
I am escaping my quotes because its being printed from php
After lots and lots of frustration, I figured out my problem. The information I was sending, I was querying from another database and all that info was not always complete.
If I clicked submit and it and one of the variables in the function call was an empty string it did not like it.
You have your method as GET in the form but POST in your Ajax.