How to open link after the webpage receive POST call in PHP? - php

I have an application to POST data to my webpage. My webpage should use POSTed data to generate a link with parameters and open it.
My webpage has these PHP codes
if(isset($_POST['name']) && isset($_POST['surname']))
{
$name = $_POST['name'];
$surname = $_POST['surname'];
header('Location: http://localhost/smcreader/tktest.php?name=' . $name . '&surname=' . $surname);
}
My problem is it won't open generated URL. I replace header with echo and add MessageBox.Show(response_stuff) to my app to show response message. It response normally, STATUS is OK, and the response message is a generated link.

I think that it isn't the right approach for redirect a page dynamically builded. Have you tried an AJAX function?
index.php
<html>
<head>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function(){
var name = $("#name").val();
var surname = $("#surname").val();
$.ajax({
type: "POST",
url: "GenUrl.php",
data: "name=" + name + "&surname=" + surname,
dataType: "text",
success: function(url)
{
if (url != "KO") {
window.location = url
}
else
{
$("#result").html("Check Values");
}
},
error: function()
{
alert("Error......");
}
});
});
});
</script>
<body>
<form name="modulo">
<p>Name</p>
<p><input type="text" name="name" id="name"></p>
<p>Surname</p>
<p><input type="text" name="surname" id="surname"></p>
<input type="button" id="send" value="GO">
</form>
<div id="result"></div>
</body>
</html>
GenUrl.php
<?php
if(!empty($_POST['name']) && !empty($_POST['surname']))
{
$name = $_POST['name'];
$surname = $_POST['surname'];
echo "http://localhost/smcreader/tktest.php?name=" . $name . "&surname=" . $surname;
}
else
{
echo "KO";
}
?>

Related

How to make auto_search using ajax jquery, php and mysql

I have created auto suggest using Javascript AJAX now I want to create auto suggest using Jquery AJAX here is the code I have written using jquery AJAX
This is my indexa.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#search_input").keyup(function(){
var txt = $("#search_input").val();
$.get("search.inc.php?search_username="+document.search_form.txt, {suggest: txt}, function(result){
$("searchResults").html(result);
});
});
});
</script>
</head>
<body>
<form id="search" name="search_form" action="<?php $_SERVER['PHP_SELF']; ?> " method="post">
Search For Names : <input type="text" id="search_input" name="search_text"><br/><br/>
<!-- <input type="submit" > -->
</form>
<div id="searchResults"></div>
</body>
</html>
and this is my search.inc.php
<?php
if (isset($_GET['searched_username'])) {
$username = $_GET['searched_username'];
}
if (!empty($username)) {
if (#$db_connect=mysqli_connect('localhost', 'root', '')) {
if (#mysqli_select_db($db_connect,'my_databse')) {
$query_like = "SELECT `user_name` FROM `members_data` WHERE `user_name` LIKE '%". mysqli_real_escape_string($db_connect,$username)."%'";
$query_like_run = mysqli_query($db_connect,$query_like);
$query_num_rows = mysqli_num_rows($query_like_run);
if ($query_num_rows == NULL) {
echo 'No Result Found';
} else {
if ($query_num_rows == 1) {
echo $query_num_rows ." Result found<br/><br/>";
} else {
echo $query_num_rows ." Results found<br/><br/>";
}
foreach ($query_like_run as $searched_members) {
$searched_results = ''.$searched_members['user_name']."<br/>";
echo $searched_results;
}
}
}
}
}
?>
what I am doing worng . Please Help me
Remove the values from the url and change the key to search_username
Do the following:
<script type="text/javascript">
$(document).ready(function(){
$("#search_input").keyup(function(){
var txt = $(this).val();
$.get("search.inc.php", {searched_username: txt}, function(result){
$("#searchResults").html(result);//don't forget the # for the id
});
});
});
</script>
The param name is different between your indexa.php and search.inc.php files.
You should use
if (isset($_GET['search_username'])) { $username = $_GET['search_username']; }
or
if (isset($_GET['suggest'])) { $username = $_GET['suggest']; }
To get the value your wanted in search.inc.php file
or change search.inc.php?search_username="+document.search_form.txt
to
search.inc.php?searched_username="+document.search_form.txt

How to check if jquery ajax send POST request or not?

I have created a simple Login Register program using PHP.
Now I am trying to validate if username already exists or not using jquery ajax. The jquery code runs but keeps on showing 'Checking Availability'.
Here is the code I have used. Please ignore the vulnerability and other errors in my PHP code ( which may not affect jquery ajax process ) as I am new to this. I'm working for improving those things.
Register.php
<?php
include('config.php');
if(isset($login_session))
{
header("Location: login.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$name = mysqli_real_escape_string($obj->conn,$_POST['name']);
$email = mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = md5($password);
$sql ="SELECT uid from users WHERE username = '$username' or email = '$email'";
$register_user = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$no_rows = mysqli_num_rows($register_user);
if($no_rows == 0)
{
$sql2 = "INSERT INTO users(username, password, name, email) values ('$username', '$password', '$name', '$email')";
$result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
echo "Registration Successfull!";
}
else{
echo "Registration Failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/username.js"></script>
</head>
<body>
<form action="register.php" method="post">
<label>UserName:</label>
<input type="text" id="username" name="username" required/>
<span id="status"></span><br />
<label>Password :</label>
<input type="password" name="password" required/><br/>
<label>Full Name :</label>
<input type="text" name="name" required/><br/>
<label>Email :</label>
<input type="email" name="email" required/><br/>
<input type="submit" value=" Submit "/><br />
</form>
</body>
</html>
username.js
$(document).ready(function()
{
$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");
if(username.length > 3)
{
$("#status").html('<img src="img/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "php/username-check.php",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK')
{
msgbox.html('<img src="img/yes.png" align="absmiddle"> <font color="Green"> Available </font> ');
}
else
{
$("#username").removeClass("green");
$("#username").addClass("red");
msgbox.html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
username-check.php
<?php
include("config.php");
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$username = mysqli_real_escape_string($obj->conn,$username);
$sql = "SELECT username FROM users WHERE username='$username'";
$sql_check = mysqli_query($obj->conn,$sql);
if (!$sql_check)))
{
echo 'could not complete query: ' . mysqli_error($obj->conn,$sql_check);
}else{
echo 'query successful!';
}
if(mysqli_num_rows($obj->conn,$sql_check))
{
echo '<font color="#cc0000"><b>'.$username.'</b> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
and I want to know if there is a way to check if jQuery Ajax sent the POST request to that file or not?
You are confusing ajax functions...Syntax will be like this
$.ajax({
url: url,
data: data,
type: "POST",
beforeSend: function () {
},
success: function (returnData) {
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function () {
}
});
Examine the request using a browser utility
- Launch the chrome browser
- Right click and select inspect element menu
- click on Network tab
- Load your URL
- Perform the Ajax request
- You can see the request here (new request will be last in the list).
- Click on it
- Right side window shows you request and response data
You did correct.Easy way to check them is use firebug tool on your browser...I recommend firefox with firebug.install it first and then open it before you post your form.then goto console log and send your form...Check it out,best software.

Ajax Post with PHP and MySQL

Im trying to post data to mysql by using PHP and Ajax, the only thing problem that data does not enter into database it so the problem seems in the javascript which i think ajax please help me.
Please there some one can fix it if there any error on code?
FORM:
<form id="contactForm" action="ajax.php" method="post">
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" name="submit" id="submit" />
<span id="error" class="warning">Message</span></p>
</form>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
JS:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
// on submit...
$("#contactForm #submit").click(function() {
$("#error").hide();
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email;
$.ajax({
type:"POST",
data: dataString,
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
return false;
});
AJAX.php
$con=mysqli_connect("localhost","admin","admin","test");
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO test (name, email) VALUES ('$name', '$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Thank you in Advance.
You must include the URL you want to POST to in the AJAX call.
$.ajax({
url: "ajax.php",
type:"POST",
data: dataString,
success: success()
});
Here is what I suggest doing:
HTML:
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" onclick="validate();" id="submit" />
<span id="error" class="warning">Message</span></p>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
Javascript:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
}
// on submit...
function validate()
{
$("#error").hide();
var name = $("#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
}
var email = $("#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
// var dataString = 'name=' + name + '&email=' + email;
$.ajax({
url: "phpScript.php"
type:"POST",
data: {name:name, email:email},
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
}
PHP:
$con = mysqli_connect("localhost","admin","admin","test");
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO test (name, email) VALUES ('$name', '$email')";
//I like to do it like this:
$result = mysql_query($query, $connect);
/*if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}*/
echo "1 record added";
mysqli_close($con);
I give credit also to the other answer by mattmemo. The thing he corrected was definitely a mistake. I think there may have been other mistakes in MARGELANI's script so I chose to post my answer as well. If this script doesn't work let my know and I will recode it. Good luck! :D

AJAX > PHP Log in not working

I'm trying to create a log in form using html > ajax > php, the problem is the php is not working, I don't know where is the problem, I think the ajax cannot execute my php file. I need help. Thanks in advance.
Here is my HTML code: my form and inputs are below
<form id="loginForm">
<input type="text" data-clear-btn="true" name="username" id="username" value="" placeholder="Username / ID No.">
<input type="password" data-clear-btn="true" name="password" id="password" value="" placeholder="Password">
<input type="checkbox" name="rem_user" id="rem_user" data-mini="true">
<label for="rem_user">Remember me</label>
<input type="submit" name="login" id="login" value="Log in" class="ui-btn" />
</form>
<div class="err" id="add_err"></div>
AJAX script that sends request on my php file
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is in database.
var dataString = 'username=' + username + '&password=' + password;
if (username == '' || password == ''){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: dataString,
success: function(result){
window.location="#report_page";
}
});
}
return false;
});
});
</script>
PHP File
<?php
require "includes/connection.php";
include "includes/function.php";
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = sanitize($username);
$password = sanitize($password);
$pass2 = md5($password);
$salt = "sometext";
$validateHash = $salt.$pass2;
$pass = hash("sha512", $validateHash);
$sql = "SELECT * FROM user_login WHERE username='".$username."' and password='".$password."'";
$result = mysqli_query($con,$sql) or die("Error: ". mysqli_error($con));
$count=mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
$id = $row['user_id'];
$username = $row['username'];
$name = "".$row['firstname']." ".$row['lastname']."";
$acc_type = $row['Acc_Type'];
}
if($count==1){
if($acc_type == 'user') {
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
echo 'true';
}
else {
echo 'false';
}
}
}
?>
as Cattla mentioned in comments.
Your PHP is looking for $_POST['login'], and your $.ajax call didn't pass that in.
so here is the answer
var dataString = 'login=login&username=' + username + '&password=' + password;
Debug tips
Did ajax send all required inputs to PHP (you can inspect this from browser developer tool)
Did php receive all required inputs (you could var_dump($_POST)
Did php connect to mysql successfully
Did ajax receive data from PHP (use alert or console.log)
try this, and if you get error state what it is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
if (username == ' ' || password == ' '){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: $(this).serialize(),
success: function(result){
alert('sucess'); //window.location="#report_page";
}
});
}
return false;
});
});
</script>

ajax doesn't load my php file in the background

I'm having a problem with my ajax call. I'm submitting some info via php to mySQL, the submission part works perfectly, it's adding the data to the database, but the ajax function isn't loading that php in the background, it's loading it in the window and showing the php file results.
Here's the HTML code.
<form action="upload.php" class="addItem" method="post">
Firstname:<br><input type="text" class="firstname" name="firstname" /><br>
Lastname:<br><input type="text" class="lastname" name="lastname" /><br>
Age:<br><input type="text" class="age" name="age" /><br>
Photo:<br><input type="file" name="image" accept="image/jpeg" /><br><br>
<input type="submit" class="submitItem" value="Add Row" />
</form>
Logout
</div>
<script>
$(document).ready(function(){
$(".submitItem").click(function(){
// Start AJAX send
jQuery.ajax({
// Enter below the full path to your "send" php file
url: "upload.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
// If form submission is successful
if ( html == 1 ) {
$('.successMessage').show(200);
$('.successMessage').delay(2000).hide();
}
// Double check if maths question is correct
else {
$('.errorMessage').show(200);
$('.errorMessage').delay(2000).hide();
}
}
});
});
});
</script>
Here's the PHP code
<?php
$name = $_POST['firstname'];
$surname = $_POST['lastname'];
$age = $_POST['age'];
if(($name === "") || ($surname === "") || ($age === "")){
echo "please fill in all fields";
} else {
$con = mysql_connect("localhost","user","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
if ($sql) { echo "1"; }
else{echo "error";}
}
mysql_close($con);
?>
Your handler needs to return false; to instruct the browser not to do its regular submission action.
(Also, you should really consider using the submit event of the form, rather than the click event of the button.)
<script type="text/javascript">
$(function(){
$("form.addItem").submit(function(){
// Start AJAX send
jQuery.ajax({
// ... your parameters ...
});
return false;
});
});
</script>

Categories