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

<?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>";
}

Related

Why successful ping $link returns nothing on query (ajax)

I'm trying to implement a "like" button with ajax so I don't have to reload the page to update the database, but no query done through ajax works.
I have it stripped down to just checking if the user already liked this project or not and I still don't manage to make it work.
I have validated:
-The $link is good (through mysqli_ping())
-The query itself is good (through phpMyAdmin)
-The ajax seems good too (replacing echo $val to echo 1 or echo memberId alert the good value).
code.js:
$("#likebtn").click(function(){
//check if already liked
$.ajax({
type:"POST",
url:"extra/projectpagefunctions.php",
data: {func: 'existsLinkProject', Table: 'projectLikes'},
success : function(result){
alert(result);
},
error : function(error){
console.log(error);
}
});
});
projectpagefunctions.php:
<?php
session_start();
$TestLink = mysqli_connect('localhost', '*******', '******', '******');
function existsLinkProject($Table){
$query = "SELECT * FROM `".$Table."` WHERE `memberId` = ".$_SESSION["account"]["memberId"]." AND `idProject` = ".$_SESSION["project"]["idProject"];
$result = mysqli_query($TestLink, $query);
$val=0;
if(mysqli_num_rows($result)>0){
$val=1;
}
echo $val;
}
if(isset($_POST["func"]) && mysqli_ping($TestLink)){
if($_POST["func"] == "existsLinkProject"){
existsLinkProject($_POST["Table"]);
}
}
else{
echo "error";
}
?>
I would expect the function to return 1 if already liked, and 0 if not.
But I only get 0 no matter what is in the database.
(on loading of the page I check it and set the color of the button accordingly and this already works)

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;
}

How to check successful data Submit using MySQL in a PHP file

I'm submitting a form using MySQL command inside a PHP file. I'm able to insert the data without any problem.
However, I also, at the same time, want to display the user a "Thank you message" on the same page so that he/she knows that the data has been successfully registered. On the other hand I could also display a sorry message in case of any error.
Therein lies my problem. I've written some lines in Javascript to display the message in the same page. However, I'm stuck on what (and how) should I check for success and failure.
I'm attaching my code below.
Can you please help me on this with your ideas?
Thanks
AB
HTML Form tag:
<form id="info-form" method="POST" action="form-submit.php">
form-submit.php:
<?php
require("database-connect.php");
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
return false;
}
echo "Entered data successfully\n";
mysql_close($conn);
?>
submit-logic.js:
$(function ()
{
$('form').submit(function (e)
{
e.preventDefault();
if(e.target === document.getElementById("info-form"))
{
$.ajax(
{
type:this.method,
url:this.action,
data: $('#info-form').serialize(),
dataType: 'json',
success: function(response)
{
console.log(response);
if(response.result == 'true')
{
document.getElementById("thankyou_info").style.display = "inline";
$('#please_wait_info').hide();
document.getElementById("info-form").reset();
}
else
{
document.getElementById("thankyou_info").style.display = "none";
document.getElementById("sorry_info").style.display = "inline";
$('#please_wait_info').hide();
}
}
}
)};
});
}
Per documentation: http://api.jquery.com/jquery.ajax/
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
You are explicitly setting this to json but then returning a string. You should be returning json like you are telling the ajax script to expect.
<?php
require("database-connect.php");
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$mobile = mysql_real_escape_string($_POST['mobile']);
$sql = "INSERT INTO tbl_details ".
"(name,email_id,mobile_number) ".
"VALUES ".
"('$name','$email','$mobile')";
mysql_select_db('db_info');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die(json_encode(array('result' => false, 'message' => 'Could not enter data: ' . mysql_error()));
}
echo json_encode(array('result' => true, 'message' => 'Entered data successfully'));
mysql_close($conn);
?>
I also added code to sanitize your strings, although mysql_* is deprecated and it would be better to upgrade to mysqli or PDO. Without sanitization, users can hack your database..
Nevertheless, returning json properly will ensure that your response in success: function(response) is an object, and response.result will be returned as expected, and you can use response.message to display the message where you want.

jquery getJSON request with params

This is my js script :
$.getJSON(riceviPaginaPrincipale, {tipo: "Principale"}).done(function(data) {
$("#contenitorePaginePrincipali").empty();
$.each(data.risultato, function(){
$("#contenitorePaginePrincipali").append('<button class="btnMenu">'+this['Nome']+'</button>');
});
$("#contenitorePaginePrincipali").append('<button class="btnMenu" onclick="creaPagina()"> Crea nuova pagina </button>');
});
and this is my php script :
<?php
//It includes session script php and global variables
include('../../sessione.php');
$tipo = $_POST['tipo'];
if(!$conn){
mysqli_close($conn);
$_SESSION['error'] = "Connessione al database pagine fallita.";
}
else{
$comando = "select * from Pagine where Tipo='$tipo'";
$result = mysqli_query($conn, $comando);
$res = array();
while($row = mysqli_fetch_array($result)) {
array_push($res, array('Nome' => $row[2]));
}
$_SESSION['error'] = "Connessione al DataBase pagine riuscita, pagine recuperate.";
}
echo json_encode(array("risultato" => $res));
?>
but it doesn't work. I'm not receiving anything.
You are currently sending the server a GET request. Id imagine that this is then causing some error due to the lack of validation on the $tipo = $_POST['tipo'] line.
You should look into using the POST from jquery http://api.jquery.com/jquery.post/ and also ensure you validate your code
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// post handling
}
Is a basic starting point.
You should also be checking your query you are sending to MySQL its open to SQL Injection. Look into using http://php.net/manual/en/book.pdo.php

Categories

Resources