Uncaught SyntaxError: - php

The code should make a pop up window, asking for confirmation "press ok to confirm the action for user" but it doesn't. i'm all out of ideas.
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
if(conf != true){
return false;
}
$(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "php_parsers/friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
$(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
$(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
$(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&user="+user);
}
</script>
PHP code:
<?php
$friend_button = '<button disabled>Request As Friend</button>';
$block_button = '<button disabled>Block User</button>';
// LOGIC FOR FRIEND BUTTON
if($isFriend == true){
$friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>';
}
else if($user_ok == true && $u != $log_username &&
$ownerBlockViewer == false){
$friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>';
}
// LOGIC FOR BLOCK BUTTON
if($viewerBlockOwner == true){
$block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>';
} else if($user_ok == true && $u != $log_username){
$block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>';
}
?>
Opening up the console i see "Uncaught SyntaxError: Invalid or unexpected token"

The console issue is with lines 2 & 3 of your JavaScript code;
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
You have a multi-line String which the console is not interpreting as one String value. In order to resolve, ECMAScript 6 (ES6) introduced template literals which can be utilized like below to handle multi-line Strings;
var conf = confirm(`Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.`);
(i.e. use back-ticks rather than double quotes to start & end the multi-line String)
Or, if ES6 isn't supported you can use good old String concatenation like below;
var conf = confirm("Press OK to confirm the '"+type+"' action for user" +
"<?php echo $u; ?>.");

Related

How do I code this the smart way, Ajax/PHP

I've got myself a little script that checks the validity of a link supplied by the user, making it safe to store in the database (safer at least) and to confirm it's a link to facebook.
Now I want to roll this code out for another links, changing parameters as and when needed so that links to people user profile on these sites work, bit I dont want to copy and paste the code another 5 times and then try and adapt the Ajax to work with it, if theres a better way to approach this.
This is my code, it can been seen working at www.vwrx_project.co.uk/test.php. It hopefully only accepts facebook.com/(something here) .
link_checker.php
<?php
function check_url($dirty_url) {
//remove anything before facebook.com using strstr()
//clean url leaving alphanumerics : / . only - required to remove facebook link format with /#!/
$clean_url = strstr(preg_replace('#[^a-z0-9:/.?=]#i', '', $dirty_url), 'facebook.com');
$parsed_url = parse_url("http://www.".$clean_url); //parse url to get brakedown of components
$safe_host = $parsed_url['host']; // safe host direct from parse_url
// str_replace to switch any // to a / inside the returned path - required due to preg_replace process above
$safe_path = str_replace("//", "/", ($parsed_url['path']));
if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] != '' && $parsed_url['path'] != '/') {
echo "Facebook";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '') {
echo "missing_profile1";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '/') {
echo "missing_profile2";
} else {
echo "invalid_url";
}
}
?>
Test.php
<?php
include_once ("includes/check_login_status.php");
include_once ("includes/link_checker.php");
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["L"])){
$dirty_url = $_POST["L"]; //user supplied link
//$dirty_url = "http://www.facebook.com/profile.php?id=4";
// if $dirty_url is blank
if($dirty_url == ""){
echo "no link supplied";
exit();
} else {
check_url($dirty_url);
}
exit();
}
?>
<html>
<head>
<title>testing</title>
<script type="text/javascript" src="js/main.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function cleanURL(){
var user_url = _("user_link").value;
var func = _("hidden").value;
if(user_url == ""){
_("status").innerHTML = "Please provide a link before clicking submit";
} else {
_("submitbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "test.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no link supplied"){
_("status").innerHTML = "Submitted blank form data.";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "invalid_url"){
_("status").innerHTML = "The url supplied is invalid";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile1"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile2"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else{
_("status").innerHTML = ajax.responseText;
}
}
}
ajax.send("L="+user_url);
}
}
</script>
</head>
<body>
<p id="status"></p>
<form id="linkform" onSubmit="return false;">
<input type="text" id="user_link">
<input type="hidden" id="hidden" value="Facebook">
<button id="submitbtn" onClick="cleanURL()">Submit</button>
</form>
Why dont you add an additional parameter which is the website you want to allow?
function check_url($dirty_url, $websiteURL)
Then update your function to use the $websiteURL variable instead of the hardcoded 'facebook.com'
Then when you want to have several different urls you can do this
check_url($dirty_url, 'facebook.com');
or
check_url($dirty_url, 'twitter.com');
Or are you wanting to be able to check for multiple sites in the single function? such as facebook.com and twitter.com

jQuery AJAX method returns current page

First, let me say that I've looked through other similar questions on this site and the jQuery documentation. So far I haven't found something that fixes my issue.
I'm trying to setup a login form for logging in using an email address and password. I have a PHP-only solution that works just fine, but I'm trying to add AJAX functionality as well.
The code I'm using now returns the whole page that's making the AJAX call. Just for some extra info, I'm using jQuery 1.10.2 and PHP 5.4.12. This is also my first time setting up a site to use a PHP script for deciding what other scripts to use based on what data is sent to it, so please bear with me.
Here's my form:
<form id="employee_login" name="employee_login" action="portal.php" method="post">
<input type="text" name="email" placeholder="Email address">
<input type="password" name="password" placeholder="Password">
<button id="login" type="submit" name="submit">Submit</button>
</form>
<div id="error_box">
<?php if(isset($GLOBALS['loginError']) && $GLOBALS['loginError'] != '') { ?>
<p class="error"><?php echo $GLOBALS['loginError']; ?></p>
<?php } ?>
</div>
Here's my AJAX function:
function ajaxValidate(email, pass, error) {
if($(email).val() == '' || $(pass).val() == '') {
$(error).html('<p class="error">You must enter your email address and password!</p>');
}
else {
$.ajax({
type: 'POST',
url: '/php-modules/ajax_filter.php',
dataType: 'text',
data: { emailAddr: $(email).val(), password: $(pass).val()},
success: function(text, textStatus, jqXHR)
{
console.log(Date() + ': ' + text);
try{
if( IsType(text, 'json') ) {
var ajaxData = $.parseJSON(text);
if(ajaxData['error'] != null && ajaxData['error'] != 'undefined')
$(error).html('<p class="error">' + ajaxData['error'] + '</p>');
else if(ajaxData['is_email'] != 1)
$(error).html('<p class="error">You must enter a <strong>VALID</strong> email address.</p>');
else if(ajaxData['is_email'] == 1)
document.location = jqXHR.getResponseHeader('Location');
else
$(error).html('<p class="error">You must enter your email address and password!</p>');
}
else if( IsType(text, 'html') ) $(error).html( $.parseHTML(text) );
else if( IsType(text, 'xml') ) alert('Data is XML.');
}
catch(e) {
$(error).html('<p class="error">' + e.description + '</p>');
console.debug(e);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$(error).html('<p class="error">' + jqXHR.status + ' ' + errorThrown + ' ' + jqXHR.responseText + '</p>');
}
});
}
}
The script I'm sending the AJAX call to is only setup for 1 request so far. I intend to add more later. I'm not sure if I've setup too many checks either, but I wanted to be safe since I'm not very familiar with something like this. And the "unidentified error" thing I added just today was a replacement for a "return false" that I thought could've been causing the problem. Here's the code:
<?php
// a filter for all AJAX requests
// for email checking
if( isset($_POST['emailAddr']) ) {
require_once('login.php');
if(isset($GLOBALS['loginError']) && $GLOBALS['loginError'] != '') {
echo '{"error":"' . $GLOBALS['loginError'] . '"}';
} else echo '{"error":"Unidentified error"}';
}
// if $_POST isn't set, isn't an array, or has a length less than 1, return an error
else if(!isset($_POST) || !is_array($_POST) || count($_POST) < 1) {
echo '{"error":"No data sent"}';
}
// if the previous check fails, invalid or insuficient data was sent
else {
echo '{"error":"Could not process request"}';
}
?>
The last piece is my login checking script. I've omitted the actual query and table fields because those parts work fine when using my PHP-only solution.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
// halt execution if the login fields are empty
if((!isset($_POST['emailAddr']) || $_POST['emailAddr'] == "") && (!isset($_POST['password']) || $_POST['password'] == "")) {
$GLOBALS['loginError'] = 'You must enter your email and password!';
}
else {// check for valid email
require_once('is_email.php');
if( !is_email($_POST['emailAddr']) ) $GLOBALS['loginError'] = 'You must enter a valid email address!';
else if($_POST['emailAddr'] != "" && $_POST['password'] != "") {
try{
// PDO setup
include('pdo.php');
$con = createPDO();
// PDO statement preparation and execution
$query = $con->prepare("[query code];");
$email = $_POST['emailAddr'];
$password = $_POST['password'];
// returned PDO query data
if($query->execute( array($email) ) ) {
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
if(strtolower($email) == strtolower($row['email']) && $password == $row['password']) {
// set session data
$_SESSION['user_id'] = $row['[id field]'];
$_SESSION['name'] = ucfirst($row['[name field]']);
$_SESSION['email'] = $row['[email field]'];
session_regenerate_id();
header("location: /");
}
else $GLOBALS['loginError'] = 'ID or password incorrect!';
}
}
} catch(Exception $e) {
$GLOBALS['loginError'] = $e->getMessage();
}
}
else $GLOBALS['loginError'] = 'You must enter your email and password!';
}
}
?>
I've cut out an unnecessary function and return false; lines, added the console.log(); method, changed the email: value name in the ajax data: option to emailAddr: (in my PHP code too) in case of a name conflict between it and my email variable, and changed my code to parse for HTML in case of PHP generating HTML error messages. My parentheses, braces, and brackets seem to be matched ok (I checked using Sublime Text's parenthesis/brace/bracket highlighting to check), the form checking portion of the script works fine.
I'm honestly at a loss...
Also, thanks to everyone who reads through this long-winded post.
Question updates:
I just realized that parsing code in the try is working correctly. Since the $.parseJSON doesn't work, it's skipping down to the if statement for parsing HTML and that one is working.
Code changes:
I replaced some return statements with echo, per Morganster.
When you are going to return data across an ajax call, you must print your data.
For example,
$var['error']="Could not process request";
echo json_encode($var);
The problem is fixed. Someone named Scott Sawyer said header("Location: /") would cause the $.ajax() method to return the whole current page. The redirect seems to be working now. Thanks for the input everyone.

echo out php variable in jQuery

this is changepassword.php file
<?php
include 'core/init.php';
if (empty($_POST) === false) {
if (md5($_POST['current_password']) === $user_data['password']) {
} else {
$errors[] = 'Your current psasword is incorrect';
}
}
if (empty($_POST) === false && empty($errors) === true) {
change_password($session_user_id, $_POST['password']);
} else if (empty($errors) === false) {
$error = output_errors($errors);
this variable
}
?>
this is the jQuery file
$('#save_pass').click(function(){
var current_password = $('#current').val();
var password = $('#new').val();
var password_again = $('#confirm').val();
if ((password == password_again) && (password.length >= 8)) {
$.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });
$('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
} else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {
$('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);
} else {
$('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }
$('#current').val(null);
$('#new').val(null);
$('#confirm').val(null);
});
i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"
You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:
<script>
function something() {
alert('<?php echo $error; ?>');
}
</script>
In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post():
$.post('changepassword.php', {current_password: current_password ...})
.done(function (data) {
alert(data);
}
This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.

POST php headers failing

When I call a script from Javascript
var user = document.getElementById('username').value;
var pass = document.getElementById('password').value;
var conf = document.getElementById('confirm').value;
var code = document.getElementById('code').value;
if(code.length == 0 || pass.length == 0 || user.length == 0 || conf.length == 0) {
alert("Entries empty");
} else if(pass != conf) {
alert("Passwords don't match");
}
window.location = "scripts/changepassword.php?Username="+user+"&Password="+pass+"&Code="+code;
changepassword.php in my scripts folder has the following headings its refreshing the current page and not passing the parameters into the script. any ideas?
it gives me error2.
scripts/changepassword.php
if (isset($_GET['Username']) && isset($_GET['Password'])&& isset($_GET['Code'])) {
...
} else {
$response = array('result'=>"error2");
echo json_encode($response);
echo "hi";
}
the window.location changes the page location (url). If you want to execute the php script without refreshing the page, use AJAX

Ajax + PHP validation and call Javascript function inside PHP validation

Basically, I'm trying to call a Javascript function inside a PHP script when using Ajax.
JavaScript:
<script type="text/javascript">
function Validate() {
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function() {
if ( hr.readyState == 4 && hr.status == 200 ) {
document.getElementById('message').innerHTML = hr.responseText;
}
}
hr.send('name=' + name);
}
function disable() {
document.getElementById('message').innerHTML = '';
}
</script>
HTML:
<div id="message"></div>
Name: <input type="text" id="name /">
<input type="button" onclick="Validate();" value="Validate" />
PHP:
<?php
$name = $_POST['name'];
if ( !empty( $name ) ) {
if ( $name == 'Tom' ) {
echo "<script>alert('Hello Tom, Welcome Back')</script>";
} else {
echo 'You are not Tom';
}
} else {
echo 'Please enter a name.';
}
?>
Everything works fine except calling the Javascript function inside PHP echo <script>alert()</script>
What I think the problem here is because I declared hr.responseText, as a result, the javascript I want to show has returned into text. But what should I do to solve this problem?
Any help would be appreciated.
Try changing your echo from "<script>alert('Hello Tom, Welcome Back')</script>";
to just 'Hello Tom, Welcome Back';
Then in your javascript you can call alert(hr.responseText);
You will have to change your javascript to check for what is returned so you know to call either the alert or the
document.getElementById('message').innerHTML = hr.responseText;
EDIT: I will add all the changed code...
<?php
$name = $_POST['name'];
if(!empty($name)){
if($name == 'Tom'){
echo 'Hello Tom, Welcome Back';
}else{
echo 'You are not Tom';
}
}else{
echo 'Please enter a name.';
}
?>
Javascript
<script type="text/javascript">
function Validate(){
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
response = hr.responseText.replace(/^\s+|\s+$/g,''); //remove whitespace so you can compare
if (response == ("You are not Tom") || response == ("Please enter a name."))
{
document.getElementById('message').innerHTML = hr.responseText;
}
else {
alert(hr.responseText);
}
}
}
hr.send('name=' + name);
}
function disable(){
document.getElementById('message').innerHTML = '';
}
</script>
Try this:
function do_alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
if(!empty($name)){
if($name == 'Tom'){
do_alert("You are tom");
}else{
do_alert("You are not tom");
}
}else{
echo 'Please enter a name.';
}
You didn't tag jQuery, but if you are using it, $.getScript might be what you want.
Aside from that, it might be better to build the script into your original document, and then execute this or that function based on the response text.

Categories