I don't know what I'm missing. I'm trying to load data from database into the navbar. Navbar should have different links for administrators, signed users and other users. Since I didn't make page for sign in and sign up yet, I assumed that the code from page showMenu.php called with AJAX will take last function loaded from functions.php which is a query for not signed in users. But instead of getting data back from the database to write with JS, the code fall into error property of AJAX call and in addition to that displays server error 500 for showMenu.php page. I checked all the paths for both main.js and php pages and names of tables and columns in database and everything is correct. And just for the record, connection.php includes fetch mode, so columns of tables can be accessed with ->. What do I'm missing.
js code
getViaAjax("showMenu",showMenu);
function getViaAjax(fileName, specificFunction) {
$.ajax({
url: "models/" + fileName + ".php",
method: "get",
dataType: "json",
success: function(jsonData){
specificFunction(jsonData);
},
error: function(xhr){
console.error(xhr);
}
});
}
function showMenu(menuJsonData){
let writingMenu = "";
menuJsonData.forEach(partOfMenu=>{
writingMenu+=`<li id="${partOfMenu.id}" class="nav-item">
<a class="nav-link" href="${partOfMenu.href}">${partOfMenu.label}</a>
</li>`;
});
document.getElementById("menu").innerHTML=writingMenu;
}
showMenu.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
include "../config/connection.php";
include "functions.php";
try{
if(isset($_SESSION['user'])){
$user = $_SESSION['user'];
if($user->roleId==1){
$jsonMenu = showMenuForAdmin();
}
else {
$jsonMenu = showMenuForSignedInUser();
}
}
else{
$jsonMenu = showMenuForNonSignedInUser();
}
echo json_encode($jsonMenu);
http_response_code(200);
}
catch(PDOException $exception){
http_response_code(500);
}
}
else{
http_response_code(404);
}
?>
function from functions.php I want to be triggered when user not registered or signed
function showMenuForNonSignedInUser(){
global $connection;
$query = "SELECT id, href, label WHERE id NOT LIKE 6;";
$data = $connection->query($query)->fetchAll();
return $data;
}
Related
I'm retrieving user information from the facebook API and sending it via AJAX to my php file to write into the mysql database.
The reason for this is so I can generate a random voucher code to give to them, which is also being written to the database.
I'm not at all experience in this and I'm just learning along the way.
my php file:
<?php
include_once 'db_connect.php';//$mysqli = new mysqli(HOST, USER, PASSWORD,
DATABASE);
include_once 'psl-config.php';//database login details
if(isset($_POST['name'],$_POST['email'],$_POST['id'])){
$name = $_POST['name'];
$email = $_POST['email'];
$uid = $_POST['id'];
$code = generateRandomString();
$prep_stmt="INSERT INTO memberinfo (name, email, id,code,dateadded) VALUES ('$name','$email','$uid','$code',now())";
$stmt = $mysqli->prepare($prep_stmt);
if($stmt) {
$stmt->execute();
$stmt->close();
}}
my javascript then runs this from the facebook button with the onlogin="checkLoginState();" function:
function checkLoginState() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
FB.api('/me', { locale: 'en_US', fields: 'name,email,id' },
function(response) {
$.ajax({
method: "POST",
url: "includes/process_fb_login.php",
data: response,
dataType: 'json',
cache: false,
success: function(data){
console.log(data);
}
});
});
}else{
alert("Failed to login");
}
});
}
At the moment nothing is being written into the database and I'm not even sure how to troubleshoot to see what's being executed along the way.
I had a couple of issues:
Firstly - My database id was type "Integer". Meaning the ID number I was getting from facebook was 15 characters long and the maximum value you can have is 2147483647(10 chars) (Signed) or 4294967295 (Unsigned). So I changed this to varchar.
Secondly - It seems that if(isset($_POST['name'],$_POST['email'],$_POST['id'])) was stuffing me up a bit, I couldn't get it to run past that line.
In the end this is the code that worked for me.
Not sure if it's the best way to do it but, hey, it works for me.
$email_exists="select email from memberinfo where email ='".$_POST['email']."'";
$exe = $mysqli->prepare($email_exists);
if($exe) {
$exe->execute();
$exe->store_result();
if ($exe->num_rows == 1) {
// A user with this email address already exists
$exe->close();
} else {
$prep_stmt = "INSERT INTO memberinfo (name, email,username,id,code,dateAdded)
VALUES ('".$_POST['name']."','".$_POST['email']."','".$_POST['email']."','".$_POST['id']."','$code',now())";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->execute();
$stmt->close();
}
}}
Trying to get together the sign up validation with PHP and Ajax. Not sure what is wrong but the submission does not happen. If I don't add the validation part everything looks fine and i am able to insert the data to mysql.
<script type="application/javascript">
$("#submit").submit(function (event) {
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signupregister.php",
type: "POST",
data: datatopost,
success: function (data) {
if (data) {
$("#signupmessage".html(data));
}
},
error: function () {
$("#signupmessage").html("<div class = 'alert alert-danger'></div>")
}
});
});
</script>
_
<?php
session_start();
include('mysqlconnection.php');
include('index.php');
function customError($errors, $errorslevel)
{
}
set_error_handler("customError", E_ALL);
if (isset($_POST['submit'])) {
if ($_POST($first_name) == "") {
$errors .= $first_nameError;
} else {
$first_name =
filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
}
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' .
$errors . '</div>';
echo $resultMessage;
exit;
}
$first_nameError = '<p>first name required</p>';
First up, in your validation PHP script, you won't need to include 'index.php'
Try redirecting the form to an empty page where you only include your validation data, while setting a session variable for the first error encountered.
At the end of your validation, if your error variable contains an error, you can redirect to the form and display your said error at a convenient location. Keep in mind you will have to save form data in session variables if you want to preserve all user input (thus removing the hassle of refilling the form over and over again).
If it doesn't, you can proceed to insert the data in your db then redirect to your desired landing page.
Here's a sample code based on your input:
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//so on for your other variables
if($_SESSION['fname'] == ""){
$_SESSION['err'] = "First Name Required";
}
if(//insert your format validation for first name){
$_SESSION['err'] = "First Name Invalid";}
}
//end of validation
if isset($_SESSION['err']){
header('Location: myform.php');
}
else{
//save all your variables into normal ones, i.e $fname-$_POST['fname'];
//insert into database;
//check correct insertion;
//redirect to landing page;
}
}
?>
My Ajax successfully update some information in database and as a result he should update one element, which shows this information. But it doesn't. However, after refreshing page, which cause reconnecting to db, information updating. Here is the function:
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function () {
var k = document.getElementById("balanceNumber");
k.innerHTML ="Your balance: "+ <?php echo $userRow['userBalance']; ?>;
}
}
);
}
and the handler.php
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
$res=mysqli_query($link, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
//$link = mysqli_connect("localhost","username","password", "users");
$bal = $userRow['userBalance']+$_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ? WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
<?php ob_end_flush(); ?>
Can anyone suggest me how to update this information without refreshing the page?
The issue is that you are trying to run php in the client side when you wrote k.innerHTML="string"+php code
You should instead produce an output in the php file you request to and retrieve that output and put it in here.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
The link explains how to send data to server through POST and get data from server through GET.
there is no detail information to help you but the first thing i noticed is your AJAX call, to get data you need to call it through GET type:
$.ajax({
'url': 'getdata.php',
'type': 'GET',
'dataType': 'json',
'data': {'topUpBalance':d},
'success': function(data) {
// if the request calls properly
},
'error': function(data) {
// if the request fails.
}
});
The main thing is you should throw output from php side but you have not sent output and You should use isset($_POST['topUpBalance']) and then go to other process for example :-
if(isset($_POST['topUpBalance'])){
$res=mysqli_query($link, "SELECT * FROM users WHERE
userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
$bal = $userRow['userBalance'] + $_POST['topUpBalance'];
if($stmt = mysqli_prepare($link, "UPDATE users SET userBalance = ?
WHERE userId = ?")){
mysqli_stmt_bind_param($stmt, "di", $bal, $userRow['userId']);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $result);
//Send output echo ...... ;
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
In jquery side :-
receive data using parameter
function topUpTheBalance(){
var d = document.getElementById("numberForm").value;
$.ajax({
type: 'POST',
url: 'handler.php',
data: {
'topUpBalance':d,
},
success: function (data) {
// use sent data or unsent data for processing
}
}
);
}
I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.
I have used the following guide to ifugre out how to send emails with file uploading without refreshing the page: http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/ and it works fine, except that I'd like to be able to take a message from the php I use to upload the file and send the email, so that I can display that message to the user, on the page where they submitted the form from.
I have this code currently in my contact.php page:
if (!$sentMail) {
header('HTTP/1.1 500 Couldnot send mail! Sorry..');
exit();
} else {
echo '<h3>Hi ' . $postName . ', Thank you for your email</h3>
<p>Your email has already arrived in our Inbox, all We need to do is Check it.
<br />Good day.</p>';
}
The only problem is getting that message that I've echoed to show up where I'd like it to go. Any help would be greatly appreciated.
The PHP in the iFrame should post unique sessionID in the database with result.
In the meanwhile you can do an Ajax call to check the database if the mail is sent.
So we got 3 files
Your form (like index.html)
Your Mailer in iframe (like sendMail.php)
Your status checker (like getStatus.php)
Here we go..
Your IFRAME Mailer:
<?php
session_start();
$_SESSION['mailsender'] = mt_rand();
// this is ur iframe mailer
// here your mail send stuff .....
// if mail is sent
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'successfull')");
// if mail fails
mysql_query("INSERT INTO mailsender (mailid, result) VALUES ('".$_SESSION['mailsender']."', 'failed')");
?>
getStatus.PHP :
<?php
session_start();
// check status and give JSON back
// getStatus.php - we be called from front-end
$query = mysql_query("SELECT * FROM mailsender WHERE mailid = '".$_SESSION['mailsender']."'");
$result = "Pending";
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_array($query)) {
$result = $rij['result'];
}
}
echo json_encode(array("result"=>$result));
?>
Your Front-end like Index.html:
<!DOCTYPE html>
<html>
<!-- include jQuery -->
<script>
$(document).ready(function(){
checkMailStatus = function() {
$.ajax({
url: 'getStatus.php',
dataType: 'JSON',
success: function(data) {
if (data['result'] == "successfull") {
// do successfull stuff here
// also clear the interval
}
if (data['result'] == "failed") {
// do failed stuff here
}
if (data['result'] == "pending") {
// still trying to send
// do stuff here while sending (like loading.gif)
}
}
})
}
$(".sendmailbutton").click(function(){
setInterval(function(){
checkMailStatus();
}, 800)
})
})
</script>
</html>