Uncaught SyntaxError: Unexpected end of input -- inside PHP with onclick - javascript

getReport.php
<?php
$data = $_POST;
//print_r($_POST);
if (isset($_POST['idws']))
{
$getListData = new getListData();
$List = $getListData->get($_POST['idws']);
print_r($List);
}
else{
exit;
}
class getListData {
public function get($idws){
include __DIR__ .'/../../../include/conn.php';
$q = "SELECT * from customers where idws= '$idws'
ORDER BY idws DESC";
$stmt = mysql_query($q);
$id = array();
$outp = '';
while($row = mysql_fetch_array($stmt)){
if ($outp != "") {$outp .= ",";}
$outp .= '{"item_d":"'.rawurlencode($row['item_desc']).'",';
$outp .= '"qty":"'. rawurlencode($row["qty"]). '"}';
}
$result = '{ "status":"ok", "message":"1", "records":['.$outp.']}';
return $result;
}
}
?>
I'm using a HTML tag inside PHP with onclick, and I am confused when I get the end of input error.
echo "<td><div style='cursor:pointer; color:#3386FF' data-toggle='modal' data-target='.detmatstat' onclick='getReport("."'".$data['id']."'".")'>$data[id]</div></td>";
I guess it is because the parentheses inside the getReport. So I tried to switch the quotation mark position, from this:
onclick='getReport("."'".$data['id']."'".")'
to this:
onclick='getReport(".'"'.$data['id'].'"'.")'
But I get this Error:
Uncaught ReferenceError: getReport is not defined
at HTMLDivElement.onclick
Honestly, I'm still confused how to read the correct tag with so many quotation mark. Please help me fix this.

You could do this :
<?php echo "<div style='cursor:pointer; color:#3386FF' data-toggle='modal' data-target='.detmatstat' onclick='getReport(".$data[id].")'>".$data[id]."</div>";
?>

Related

Alert() javascript function not working in php

I know this is frequently asked question however I have tried using :
script language='javascript'
placed header in else after alert
script type='text/javascript'
Still I don't get alert box, while else parts executes perfectly.
Here's my code:
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data=mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
}
else{
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
?>
What am I missing here.
Thanks
You have your js files mixed up.
Include jquery and then your script, inside separate tags:
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>';
echo '<script type="text/javascript">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
By the way, you do NOT need jquery for a simple alert, as it is plain javascript. Try to avoid including external library if not needed, you will end up with a bloated code.
And printing js with php it's a bit of a hack. Why not just print it into your html or js file?
Javascript inside a script tag that has an src attribute does not get executed, you have to create a second script tag after the jquery one.
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data = mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo '</script>';
echo "<script>alert('PF No. Does not exist. Please Contact Admin!!!');</script>";
} else {
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
}
?>

Fill a javascript array with php variable

I want to fill a javascript array with my php variable $jaar. But when I print it in the js file I don't get the right output.
php file
<?php
$jaar = "[";
$result = mysql_query("SELECT jaar FROM agenda");
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
$jaar .= "\"" . $row[0] . "\"";
$jaar .= ",";
}
$jaar{ strlen($jaar)-1 } = ']';
echo "<script type='text/javascript'>var db_jaar = '" . $jaar ."'</script>";
?>
<script src="js/calender.js"></script>
js file
//Get the variable from the php file
alert(db_jaar);
//printed: ["2018","2018"]
//When I make the variable local
var db_jaar = ["2018","2018"];
alert(db_jaar);
//printed: 2018,2018 <-- This is what I want
Some changes required:
while( $row=mysql_fetch_array($result, MYSQL_NUM) ) {
// create $jaar[]
$jaar[] = $row[0];
}
// echo using json_encode
?><script type='text/javascript'>var db_jaar = <?php echo json_encode($jaar); ?>;</script>";<?php
Read more:
json_encode()

PHP echo selected value from html dropdown list

In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().

Uncaught SyntaxError: Unexpected identifier (alert connected)

what is the error in this statement
<?php
session_start();
$host = "localhost";
$uname = "root";
$pass = "";
$database = "mcndb";
$cons = mysqli_connect($host, $uname, $pass, $database);
mysqli_select_db($cons, $database);
if (!$cons) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['username'])) {
date_default_timezone_set("Asia/Bangkok");
$today = date("Y/m/d h:i:s:A");
$username = mysqli_real_escape_string($cons, $_POST['username']);
$password = mysqli_real_escape_string($cons, $_POST['password']);
$firstname = mysqli_real_escape_string($cons, $_POST['firstname']);
$middlename = mysqli_real_escape_string($cons, $_POST['middlename']);
$lastname = mysqli_real_escape_string($cons, $_POST['lastname']);
// $age=mysqli_real_escape_string($cons,$_POST['age']);
$gender = mysqli_real_escape_string($cons, $_POST['gender']);
$email = mysqli_real_escape_string($cons, $_POST['usremail']);
$companyname = mysqli_real_escape_string($cons, $_POST['companyname']);
$position = mysqli_real_escape_string($cons, $_POST['position']);
$contactnumber = mysqli_real_escape_string($cons, $_POST['contactnumber']);
$addresss = mysqli_real_escape_string($cons, $_POST['address']);
$sql = "INSERT INTO tbltry (username,password,email,firstname,middlename,lastname,gender, company_name,position,contact_number,address_of_company,dateofregister)
VALUES ('$username', '$password', '$email','$firstname', '$middlename','$lastname','$gender', '$companyname','$position','$contactnumber','$addresss','$today')";
if ($cons->query($sql) == TRUE) {
echo '<script>';
echo 'alert("Successfully created an account")';
echo '</script>';
} else {
echo '<script>';
echo "Error: " . $sql . "<br>" . $cons->error;
echo 'alert("Account already exist")';
echo '</script>';
}
}
?>
enter image description here
the problem with this is that when ever i try registering a dulicate value to unique column in databse, the error message in the alert dont show up and it does not show any kind of error even in sql it just says Uncaught SyntaxError: Unexpected identifier so what is wrong with my code that the alert for error dont show?
so what is wrong with my code
This:
<script>
Error: some text<br>some more text
alert("Account already exist")
</script>
(And potentially other things, but this seems to be where the error you're currently seeing takes place.)
That first line of JavaScript code isn't actually JavaScript code. It's just text. So Error: (and everything after it) is an unexpected identifier as far as JavaScript is concerned.
I suspect you meant to put that text outside of the script block:
echo "Error: " . $sql . "<br>" . $cons->error;
echo '<script>';
echo 'alert("Account already exist")';
echo '</script>';

how to throw an exception from php to angular $http service

i am working on a blog in angularJS and i use php to generate a json with data from a database.
My angular 'get article' function looks like this
$scope.getDetail = function() {
$http.get('php/blogGetArticle.php?id=2').success(function(json) {
$scope.jsonDetail = json;
alert('ok');
}).error(function() {
alert('error');
});
};
and my php 'blogGetArticle.php' looks like this.
<?php
$id = $_GET['id'];
$dbhost = "localhost";
$dbport = "5432";
$dbname = "pd";
$dbuser = "postgres";
$dbpass = "123";
$connect = pg_connect("host=" . $dbhost . " port=" . $dbport . " dbname=" . $dbname . " user=" . $dbuser . " password=" . $dbpass);
if(!$connect)
die("error 0"); // connect error
$query = "SELECT * FROM blog WHERE id=" . $id;
$result = pg_query($connect, $query);
if(!$result)
die('error 1'); // query error
$row = pg_fetch_row($result);
$json = '{';
$json .= '"id":"' . addslashes($row[0]) . '",';
$json .= '"title":"' . addslashes($row[1]) . '",';
$json .= '"message":"' . addslashes($row[2]) . '",';
$json .= '"category":"' . addslashes($row[4]) . '"';
$json .= '}';
echo $json;
?>
Now what i try to do is i try to make the angular function take to the .error branch when i call something inside php .. i dont know how to explain well. Example when i have in php an id that is lower than 10, i want the angular function to throw an exception but i want to make it from php file to throw that exception to angular function.
Thank you, Daniel!
EDIT: so how do i throw a 4xx or 5xx error ?
PHP:
try {
} catch (Exception $e) {
header("HTTP/1.1 500 Internal Server Error");
echo '{"data": "Exception occurred: '.$e->getMessage().'"}';
}
AngularJS
, function(error) {
$log.error('Error message: '+error.data);
});
You can do like
if(!$connect)
// or may be code 500
header("HTTP/1.0 404 Not Found");
exit;
$query = "SELECT * FROM blog WHERE id=" . $id;
$result = pg_query($connect, $query);
if(!$result)
header("HTTP/1.0 404 Not Found");
exit;
I advice you to try http://us.php.net/manual/en/function.json-encode.php without any further ado :)
Bye
Couldn't you return json with a different format?
if(!$result){
$json = '{';
$json .= '"error":"failed loading data",';
$json .= '}';
}else{
$row = pg_fetch_row($result);
$json = '{';
$json .= '"id":"' . addslashes($row[0]) . '",';
$json .= '"title":"' . addslashes($row[1]) . '",';
$json .= '"message":"' . addslashes($row[2]) . '",';
$json .= '"category":"' . addslashes($row[4]) . '"';
$json .= '}';
}
echo $json;
Then in angular detect if error exists in json and then you can plan for multiple errors vs processes status result calls.
jsonObj.hasOwnProperty("error")

Categories

Resources