passing login data from ajax to php script - javascript

Here is my script in the html page:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid=$('#loginid').val();
var password=$('#password').val();
alert("loginid="+loginid);
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid:loginid,password:password},
success: function(html) {
//alert(html);
$('#status').html(html);
}
});
});
});
</script>
I am trying to get the values from the html input boxes and then passing those values to the ajax code which passes it to the php script, which then validates the login id and password and echoes a message
The php script:
<?php
require_once('dbconfig.php');
//if (isset($_POST['signin'])) {
$loginid = $_POST['loginid'];
$password = $_POST['password'];
if ($operations->login($loginid, $password)) {
header("Location:../view/admin_home.php");
} else {
echo "wrong details";
}
//}
$conn = null;
?>
html div where message should be printed:
<div id="status"></div>
When I run the code in the browser no errors are shown, but the code does not work and neither the message is displayed nor is the validation done.

My contribution:
In ajax requests I suggest you to end the php script, you can use a simple die(); for this. After this, you must to print the response, you can use numeric or string pattern to expose this like: 'success' or 'fail', also: 1 or 0.
Here is the same example with a new solution:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid = $('#loginid').val();
var password = $('#password').val();
e.preventDefault(); //for avoiding conflict with default form function
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid: loginid, password: password},
success: function(response) {
if (response == 'success') {
// if a successful response, redirect your client
window.location.href = '../view/admin_home.php';
} else {
// if login fails, put a message on screen
$('#status').html('Wrong credentials, try again.');
}
}
});
});
});
</script>
Don't forget to filter data in php, never trust in your user!
require_once('dbconfig.php');
// pre setting a response status as fail, this avoid you to use an
// else statement
$result = 'fail';
if (isset($_POST['signin'])) {
// Apply filter and sanitize data, if the loginid is an e-mail
// use the FILTER_SANITIZE_EMAIL else a simple string filter is ok.
$loginid = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
if($operations->login($loginid,$password)){
// If everything is ok, you just override the response message
$result = 'success';
}
}
// Ath the end you simply close the connection, print the response and
// stops the PHP script
$conn = null;
print(result);
die();

i solved it by preventing it from performing the default function
i used e.preventDefault() it worked but i have a new problem now
the page to which the php script tries to redirect appears on the same login page how should i solve this now??
here is a screen shot of the same

Give this a try:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: "../controller/login_check.php",
data: form.serialize()
}).done(function (html) {
$('#status').html(html);
});
});
});
</script>

You must redirect with javascript, you are not actually going to the php page, you are just retrieving whatever is printed.
window.open(page,'_self')
rather than
header(...)

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

Delete post using $.ajax

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID
<button type="button" onclick="submitdata();">Delete</button>
When click this button then following $.ajax process running.
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:datastring,
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
And delete.php is
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_GET['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
This code not working post not deleted. Please how do I do?
You likely want to not only match the "GET" you use in your PHP but also add the ID to the button
<button class="del" type="button"
data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>
using $.get which matches your PHP OR use $.ajax({ "type":"DELETE"
$(function() {
$(".del").on("click", function() {
$.get("delete.php",{"post_id":$(this).data("id")},
function(html) {
alert(html);
}
);
});
});
NOTE: Please clean the var
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Using ajax DELETE with error handling
$(function() {
$(".del").on("click", function() {
$.ajax({
url: "delete.php",
method: "DELETE", // use "GET" if server does not handle DELETE
data: { "post_id": $(this).data("id") },
dataType: "html"
}).done(function( msg ) {
$( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
In the PHP you can do
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_REQUEST["post_id"] ....
}
since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET
here is how it sould be
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_POST['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
for the JS code
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:{"post_id":post_id},
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
here i've supposed thqt the give you the real id post you're looking for !!
The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request
Change:
type:"POST",
url:"delete.php",
data:datastring,
to
type:"DELETE",
url:"delete.php?" + datastring,
in PHP
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
$id = $_REQUEST["post_id"];
// perform delete
}
DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.
Follow #roberts advise and also:
You should have a way to handle errors eg.
to your ajax code add this:
error:function(e){
alert(e.statusText)// if you like alerts
console.log(e.statusText)// If you like console
}
You should also check your error logs. Assuming you use apache2 and linux
execute this in terminal:
tail -f /var/log/apache2/error.log
This gives you a very elaborate way to code. You also eliminate the problem of trial and error.

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Header wont redirect when passedthrough ajax

Not sure if this is possible but I have a page that submits a form with AJAX and if it meets certain conditions it should automatically take the user to another page. NOTHING is outputted before the header tag its just a bunch of conditions.
Problem: Header redirect not working...
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
header("Location: http://localhost/manage/card.php?id=$id");
Headers can only be modified before any body is sent to the browser (hence the names header/body). Since you have AJAX sent to the browser, you can't modify the headers any more. However, you can have the add.php script called via AJAX return the $id parameter. Then that parameter can be used in JavaScript to redirect the page: window.location = 'http://localhost/manage/card.php?id=' + id.
More info on PHP header(): http://www.php.net/manual/en/function.header.php
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
window.location = 'http://localhost/manage/card.php?id=' + data;
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
echo $id;
exit;
You indicate in the question that under certain conditions, you want a redirect.
To do that, you would want to alter your javascript to contain an if condition, and to watch for certain responses.
I would recommend modifying your responses to be json, so that you can pass back different information (such as a success status, as well as a redirect url, or other information you might want).
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
var response = $.parseJSON(data);
if (response.redirect) {
window.location = response.redirect_url;
} else {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
}
});
});
As for your add.php file, you'll want to change this to be something more like so:
$json = array(
'redirect' => 0,
'url' => '',
}
if (...condition for redirect...) {
$row = mysqli_fetch_array($result);
$id = $row['id'];
$json['redirect'] = 1;
$json['redirect_url'] = "Location: http://localhost/manage/card.php?id=$id";
}
echo json_encode($json);
die();
You seem to have a miss understanding of how AJAX works. Introduction to Ajax.
The reason why your redirect appears not to working is because an Ajax call doesn't directly affect your browser. It's a behind the scenes call.
To get the data out from the AJAX call you need to do something with the returned data.
success: function (data) {
$("input").val('Company Name');
$("form").hide();
//You need to do something with data here.
$("#myDiv").html(data); //This would update a div with the id myDiv with the response from the ajax call.
getInfo();
}

jquery ajax json doesnt return true

i have large form in my website and using serialize() to process the form.
my problem is:
the result always return false after the form has been completed! i checked using firebug. if false, the result being shown. it was actually data.ok == true had been called, but it didnt show the message in the page? and it didnt redirect the page to the destination address?
jquery ajax:
$("#details").live("submit", function(e){
var form = $(this).serialize();
var data_string = form;
$.ajax({
type: "post",
url: "../_include/ajax.php?details",
cache: false,
data: data_string,
dataType: "json",
success: function(data) {
if(data.ok) {
("#pop").html(data.message).addClass("oke").fadeIn("slow");
setInterval(function() {
location.href = data.redirect
},2000)
} else {
$("#pop").html(data.message).addClass("warning").fadeIn("slow");
}
}
});
e.preventDefault();
})
in PHP:
if (isset($_GET['details'])) {
if (empty($name)) {
$data['ok'] = false;
$data['message'] = 'Please enter name!';
} ................ {
.............
} else {
$db->query("UPDATE query....");
$data['ok'] = true;
$data['message'] = 'Your details has been submitted!';
$data['redirect'] = 'index.php?p=details';
}
echo json_encode($data);
}
You appear to have a syntax error in your success function (if that's not a copy/paste error):
("#pop").html(data.message).addClass("oke").fadeIn("slow");
should be:
$("#pop").html(data.message).addClass("oke").fadeIn("slow");
you check for GET in your PHP (if (isset($_GET['details']))), but send POST (by specifying the type as post) in your AJAX.
Either check the $_POST array instead of the $_GET, or change the type to get.

Categories

Resources