Reload an html page without refreshing/redirecting it [duplicate] - javascript

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 4 years ago.
I would like to try to find a way to reload my HTML page without making it refresh. For example, I want through a PHP file to reload my 1st page to a second page. Here is my try, but it shows me this message -->
Parse error: syntax error, unexpected '<' in C:\wamp64\www\PHP\pesto.php on line 26
Here is my php file:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];
//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
$result[]=$row['site_id'];
}
if ($res){
if($result[0] <20){
<script>
$.get("updated-content.html", function(data, status){ $("body").html(data); }).fail(function(e) { alert( "error" +JSON.stringify(e)); })
</script>
});
}
}
// while($row = mysqli_fetch_array($res)){
// array_push($result, array($row[0]));}
// echo json_encode(array($result));
// Close connection
mysqli_close($link);
?>
I don't want to use PHP redirection. I want to make that happen with the usage of jquery. Is it possible?

The error unexpected syntax clearly explains what the problem is... it does not expect that to be there!
Common fix : Check your semicolon and brackets.
It is obious you MUST use a " or '.
if ($res){
if($result[0] <20){
echo '<script>
$.get("updated-content.html", function(data, status){ $("body").html(data); }).fail(function(e) { alert( "error" +JSON.stringify(e)); })
</script>';
}
}
Also you should be using prepared statements as your code above is vulnerable to SQL injection. You can learn more by Googling "SQL Injection" and "Prepared Statements PHP".
You can also use PHP to include or require files based on conditions...
Such as :
<?php
if ($res){
if($result[0] <20){
include 'updated-content.html';
}else{
include 'file.html';
}
}
?>

Related

Accessing Through PHP a Posted Javascript Variable

I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.

AJAX function for retrieving postgres data not working

I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}

Trying to change from alert to popup window [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I'm trying to switch the "success/fail" notifications to my webpage. I've been successful doing this in several parts of my test website, but I'm running into a bit of a problem on my login page. My original way of doing this used an alert popup, which works okay, but doesn't provide the style I'm looking for. I decided to use the template that has been working for me in other parts of the website, but the login is unique since it's here where I establish my session for a user.
Here is my original login code which works as intended but uses a generic alert window...
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
}
}
mysqli_close($link);
?>
Here is the code I'm trying to get to work but comes up with
Parse error: syntax error, unexpected end of file on line 38.... which is my ?> to close out the php.
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
}
mysqli_close($link);
?>
I'm pretty sure this has to do with the quotes but I've tried several different combinations and I still get the error.
The window.open code works great on my other pages if I can keep all the if, else statements within the javascript. In these pages I just use the PHP tags to grab the parameters outside the javascript where needed.
However when I attempt to do with this with the $_Session, it doesn't work.
If this is a quotes problem, I'd appreciate it if someone could point me in the right direction. If this is related to the session, I could use some help formatting the javascript so I call the ?_Session properly.
There are so many quote issues with your code, try to put script separately or use heredoc, nowdoc.
PHP can read multiple lines with heredoc/nowdoc.
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Use delimiters and indentation correctly and you can put actual JS code in between.
Example as per your use case.
echo <<<SCRIPT
<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor="#EFEFEF"/>');
no.document.write('</br>');
no.document.write('<p style="text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px">Your credentials could not be verified</p></br>');
no.document.write('<div style="text-align:center"><button style="width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica" value="Close" onclick="window.close()"">OK</button></div>');
window.location.href = '../default.html';
</script>
SCRIPT;
Remember you can not use same kind of quote in between without escaping properly but you can also double between single and vice-versa.
I think your problem is using ' inside another '
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>...
You need to escape this char like this:
no.document.write('<p style=\'text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px\'>...

Php, js redirecting after successful registering, It inserts the user but won't redirect

<?php
$con = mysqli_connect("localhost", "root", "", "" ) or die("Neuspjelo spajanje");
function InsertUser(){ global $con;
if(isset($_POST['sign_up'])){
$name = mysqli_real_escape_string($con, $_POST['u_name']);
$pass = mysqli_real_escape_string($con,$_POST['u_pass']);
$email = mysqli_real_escape_string($con,$_POST['u_email']);
$country = mysqli_real_escape_string($con,$_POST['u_country']);
$gender = mysqli_real_escape_string($con,$_POST['u_gender']);
$b_day = mysqli_real_escape_string($con,$_POST['u_birthday']);
$date = date("m-d-Y");
$status = "unverified";
$posts = "No";
$get_email = "select * from users where user_email='$email'";
$run_email = mysqli_query($con, $get_email);
$check = mysqli_num_rows($run_email);
$insert = "insert into users (user_name, user_pass, user_email, user_country, user_gender, user_b_day,
user_image, register_date, last_login, status, posts) values
('$name','$pass', '$email', '$country', '$gender', '$b_day', 'default.jpg',
'$date', '$date', '$status', '$posts')";
$run_insert = mysqli_query($con, $insert);
$result = mysql_query($insert);
if($result){
echo "<script>alert ('You're successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}
}
}
?>
You can't echo javascript and run it in a page that's already loaded. This would need to be the result of an ajax call on the client side with your redirects occuring from your ajax callbacks.
If you're ok with ditching the alert, you can just issue a redirect from php:
header('Location: home.php');
To do it ajaxy:
$.ajax({
type: "GET",
url: "your_insert_user.php"
}).success(function(xhr) {
alert ("You're successfully registered!");
window.open('home.php', '_self');
}).fail(function (jqXHR, status, errorThrown) {
//something else here
});
But, why would you want to issue an ajax call just to redirect?
Additionally, you need to issue the appropriate responses from your insert script:
if ($result) { echo ""; } //issues a "200 OK"
else { header("HTTP/1.1 422 Unprocessable Entity"); } //fires the failure callback in ajax
I would pass a conditional GET or POST paramater to home.php with some value flag and display your message there.
Based on what you post above, you are dealing with two separate issues here.
You say "it inserts" so I'm assuming that means that the mysql query to insert the new row into your database completes successfully. Then you send some HTML code, containing a (somewhat mangled) Javascript snippet, to the browser, which is supposed to issue a redirect request to the client's web browser, which doesn't have the desired result, seeing as you write that it "won't redirect".
Keep in mind that redirection is performed by the browser, is dependent on the browser's capabilities and/or settings, and requires proper javascript in the first place.
How do properly request a redirect from the browser has been discussed before on SO.
First of all,remove this line $result = mysql_query($insert); then modify your code and add this, hope it will work:
$run_insert = mysqli_query($con, $insert);
if($run_insert){
echo "<script>alert ('You\'re successfully registered!')</script>";
echo "<script>window.open('home.php', '_self')</script>";
}

Search to MySQL table using jQuery, Ajax and PHP not working [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to create a search engine for a MySQL table with jQuery, Ajax and PHP. I have a database on my external server in order to get data from. Here is a pic of the MySQL database table.
I have these two scripts for the search engine:
index.html
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<input id="searchdb"/>
<div id="resultdb"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#searchdb').change(function() {
$.ajax({
type: 'GET',
url: 'getdb.php',
data: 'ip=' + $('#searchdb').val(),
success: function(msg) {
$('#resultdb').html(msg);
}
});
});
});
</script>
</body>
</html>
getdb.php
<?php
if ($_GET['insert']) :
$insert = preg_replace('#[^0-9]#', '', $_GET['insert']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM test WHERE id='.$insert.'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc()
echo $row["name"];
}
endif;
?>
What I want is to type the id, hit enter and get back the name or "0 results". There seems to be something wrong with the code I wrote. Could you please help me? Thanks in advance.
The period characters in your SQL text string are being interpreted as literal dot characters, not PHP concatenation.
e.g.
$sql = "SELECT id, name FROM test WHERE id='.$insert.'";
echo "SQL=" . $sql;
should return:
SQL=SELECT id, name FROM test WHERE id='.123.'
That would be easy enough to fix. But why include the value as part of the SQL text in the first place.
Using prepared statements and bind placeholders is really not that hard.
Use a static string as a SQL statement, use a question mark as a bind place holder, and call the mysqli_stmt_bind_param function. And check the prepare and execute calls for errors. (Those return FALSE if an error occurs.) And the call to num_rows isn't necessary. Just do a fetch. If it returns a row, you've got a row. If it returns FALSE, there wasn't a row to return.
Something like this:
$sql = "SELECT id, name FROM test WHERE id = ? ";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i",$insert);
if ($stmt->execute()) {
if ($row = $stmt->fetch_assoc()) {
echo $row['name'];
} else {
echo "0 results";
}
} else {
// handle error
die $conn->error;
}
} else {
// handle error
die $conn->error;
}
You could handle the error conditions differently, depending on your requirements.

Categories

Resources