Getting values from php to ajax request with Javascript - javascript

Greetings to everyone,
I'm a beginner in javaScript and I am kinda new to ajax... I am trying to get a return value from php like error message or success message and pass it to the user. Any kind of suggestion is welcome
PS: Everything was working when I have not started using ajax
$('button[post-request]').click(function() {
// event.preventDefault();
var request, address, form, response;
address = $('form').attr('action');
response = document.getElementById("return");
$('input').prop('disabled', true);
request = new XMLHttpRequest();
request.open('POST', address, true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
response.innerHTML = this.responseText;
console.log(request.responseText);
}
else{
console.log(request.statusText);
}
}
request.send();
});
Here is my php code
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller
{
public $data, $uid;
public function __construct()
{
parent::__construct();
// loading models
$this->load->model(['logic/auth_action'=>'auth','validations/auth_validation'=>'verify']);
// store ecncrypted user uid in a session
$this->uid = $this->session->userdata('uid');
$this->data['user'] = $this->usr->fetch_all_information($this->uid);
}
public function login()
{
$this->func->is_logged_in(true, 'dashboard');
$this->data['title'] = "Sign in";
if(!empty($_POST) && $this->input->is_ajax_request()):
// validating users inputs coming from the form
$user_inputs = $this->verify->authenticate_userInputs('login');
// checking if no error isset && carry on with the next step
if(!isset($user_inputs['error_msgs'])):
// performing neccessary action after validating
$return = $this->auth->login($user_inputs);
else:
// store error for $return variable if there is any && pass it on
$return = $this->func->return_validation_error($user_inputs);
endif;
// retrieve the error stored and display it to user
print $this->func->fetch_message('error',$return);
endif;
// this display login page
$this->load->view('auth/login', $this->data);
}
}

Related

Unable to make php $_REQUEST from XMLHttpRequest data

I am trying to make XMLHttpRequest from my html frontend to the php microservice backend, sending data from the input to be manipulated, and displayed on html output
The function I am trying to execute is triggered by 'onlick'
Frontend
function markRequired()
{
input_text = document.getElementById('input-text').value
input_text2 = document.getElementById('input-text2').value
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var j = JSON.parse(this.response);
mark_required = j.answer;
displayMark();
}
};
xhttp.open("GET",markURL+"?input_text="+input_text+"?input_text2="+input_text2);
xhttp.send();
return;
}
}
Backend
<?php
header("Access-Control-Allow-Origin: *");
header("Content-type: application/json");
require('functions.inc.php');
//main array
$inputtext = $_REQUEST['input_text'];
$furthertext = $_REQUEST['input_text2'];
$totalsofar = getTotal($inputtext, $furthertext) // In php unittest the function works, so i know it's not the problem
$output['string']=$inputtext."=".$answer;
$output['answer']=$totalsofar;
echo json_encode($output);
exit();
Whenever I run my html front end and call the function, markRequired() I am not getting any response. Status code is 200 and I can see the sent data in the request URL.
When I try to return the input string, I am getting a null response.
I can't use cURL for this particular project otherwise I would have.
Any help would be much appreciated!!

PHP AJAX redirect after register

I have a registration form. The PHP is checking for errors such as short password
AJAX gives an alert with the echo error from PHP.
With PHP, after an if else statement,
the user will be registered and redirected successfully to index.php (good)
header('Location:home.php');
exit;
The problem is, if there is any error, the user will be redirected to handler.php and the echo alert shows there (on white page)
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
if (xhr.status >= 200 && xhr.status <= 299) {
var response = JSON.parse(xhr.responseText);
if (response.location) {
window.location.href = response.location;
} else {
xhr.send(form_data);
}
}
Example 2: the alerts will display properly at <div class="msg"></div> position
(But will also throw the index.php on registration form, where the alerts go)
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
xhr.send(form_data);
};
So, i want the user to be redirected to index.php & also the alerts to be handled by AJAX
Regarding responding to AJAX requests with redirects, please see What is the difference between post api call and form submission with post method?. Does a better job explaining than I could.
The basic idea is that when called asynchronously, your PHP should do what it needs to do and respond with either a 200 (success) or an error status like 400 (bad request) + error details.
// make sure nothing is echo'd or otherwise sent to the
// output buffer at this stage
$errors = []; // collect errors in here
// do whatever you need to do with the $_POST / $_FILES data...
// capturing errors example...
if ($_POST['cpassword'] != $_POST['password']) {
$errors[] = "Passwords do not match!";
}
// use content negotiation to determine response type
if ($_SERVER['HTTP_ACCEPT'] === "application/json") {
if (count($errors)) {
header("Content-type: application/problem+json");
http_response_code(400);
exit(json_encode([
"message" => "Invalid form data or something",
"errors" => $errors
]));
}
header("Content-type: application/json");
exit(json_encode(["location" => "home.php"]));
}
// just a normal request, respond with redirects or HTML
// ...
foreach ($errors as $error) : ?>
<div class="error"><?= $error ?></div>
<?php endforeach;
The client can navigate to home on success or display error information otherwise
document.querySelector(".register form").addEventListener("submit", async (e) => {
e.preventDefault()
const form = e.target
const body = new FormData(form)
// fetch is much easier to use than XHR
const res = await fetch(form.action, {
method: "POST",
headers: {
accept: "application/json", // let PHP know what type of response we want
},
body
})
const data = await res.json()
if (res.ok) {
location.href = data.location
} else if (res.status === 400) {
document.querySelector('.msg').textContent = data.message
// also do something with data.errors maybe
}
})

Using Ajax to run a php script to change a session variable for a Login System

I am creating a website with a login system for a university assignment. the method to do this i have created is have a a php page (the main page) have a section on the top that checks for a session variable for the user:
<?php
// open the session
session_start();
header('Access-Control-Allow-Origin: *');
// check for existing user
if(isset($_SESSION['User'])){
$isUser = true;
$userName = $_SESSION['userName'];
}else{
$isUser = false;
}
?}
There is more to this but the rest is just functions that use the session to add appropriate fields (login section/logged in confirmation) this works fine.
In order to change the session variable a login confirmation function is used (very long script to check against database, also works perfectly) and at the end of the login check if correct changes the session variable like so:
//Start the session
session_start();
$arrUser = $result[0];
$_SESSION['User'] = $arrUser[0];
$_SESSION['userName'] = $arrUser[1];
return true;
this works, if loaded in a separate page (changes the session variable and adjusts adjusts the page to confirm session has changed, only if url in manually opened with variables). however by attempting to run the php using ajax:
function Login(){
var Username = document.getElementById("Username");
var Password = document.getElementById("Password");
if(Username.value != "" && Password.value != ""){
URL = "https://localhost/CAB230/Login.php?username=" + Username.value +
"&password=" + Password.value;
httpGetAsync(URL, function(response){
if(response){
location.reload();
} else {
document.getElementById("Username").style.background = "red";
document.getElementById("Password").style.background = "red";
}
});
} else {
window.alert("Username and Password fields must both be filled out");
}
}
function httpGetAsync(theUrl, callback){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
results in true being return and the page being reloaded, but the session variable don't change as the login section loads instead of the logged in confirmation section.
This is very confusing because running this ajax on my laptop changes the session variable, however on my PC this doesn't work.

javascript ajax login form handling

Im working on an ajax form to show errors without reloading the page. So if everything is good, the user we be redirected to home.php. At the moment the user will also be redirected when there is an error.
This is my code so far:
index.php:
<script>
function myFunction()
{
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
window.location.replace("/index.php");
}
}
xmlHttp.open("post", "login.php");
xmlHttp.send(formData);
}
</script>
login.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
echo 'not ok';
}
}
?>
Remove loop from the code and pass elements in FormData() because passing element will take all the fields inside the form
var elements = document.getElementsByClassName("formVal");
var formData = new FormData(elements);
Throw a 401 error if it fails login, this will stop the redirect.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if (!$user->logUser($$_POST['username'], $_POST['password'])) {
echo 'ok';
} else {
header("HTTP/1.1 401 Unauthorized");
exit;
}
}
?>
do you know jquery ?
jquery w3 school search on google
avaible
$('#data-div-id').load('www.sdasd .php ? or whatevver');
function tmp_func_sil_ok(e){
$.ajax({type:"GET",url:"go.php",data:{'snf_sil':e},success: function(e){msg_("<h3>Başarılı</h3>");}});
}

Undefined $_POST after xmlhttp request

My code makes an xmlhttp request to a php file, sending an ID so that a record can be identified and deleted from the database. However, when performing the delete query, I'm get an error saying 'comicID' is undefined (the variable using the ID value sent by POST). I'm not sure how to make sure it is defined correctly. Currently, the error I'm getting back from error handling is: "No comic supplied." and the error I get when removing the ISSET section of code is: "Error. Pages in comic not deleted." As it stands, the delete query doesn't work.
Javascript:
function delComic()
{
var radioButtons = $("#listID input:radio[name='comicList']");
var radioID = radioButtons.index(radioButtons.filter(':checked'));
console.log(radioID);
if (radioID < 0)
{
window.alert("You must select a comic before deleting.");
}
else
{
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php?comicID="+radioID;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
}
PHP:
<?php
if (isset($_POST["comicID"]))
{
$comic = $_POST["comicID"];
$dir = 'comics/'.$comic.'/';
if (!file_exists($dir))
{
mkdir($dir, 0777, true);
}
include_once('includes/conn.inc.php');
mysqli_query($conn, "DELETE FROM serieslink WHERE comicID = '$comic'");
$query = ("DELETE FROM page WHERE comicID = '$comic'");
if (!$result = mysqli_query($conn, $query))
{
echo ("Query1 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
$dirHandle = opendir($dir);
while($file = readdir($dirHandle))
{
if(!is_dir($file))
{
unlink("$dir"."$file");
}
}
closedir($dirHandle);
rmdir($dir);
$query2 = ("DELETE FROM comic WHERE comicID = '$comic'");
if (!mysqli_query($conn, $query2))
{
echo ("Query2 error: " . mysqli_error($conn));
exit;
}
else
{
if (mysqli_affected_rows($conn) > 0)
{
echo ("The selected comic was successfully deleted.");
}
else
{
echo ("Error. Comic not deleted.");
}
}
}
else
{
echo "Error. Pages in comic not deleted.";
}
}
$conn->close();
}
else
{
$comic = null;
echo "No comic supplied";
}
?>
With POST you do your Ajax request different that with GET. The query string is an argument to the send() function rather than part of the url, and you leave off the ?:
var xmlhttp = new XMLHttpRequest();
var url = "delCom.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var message = xmlhttp.responseText;
loadComic();
window.alert(message);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send("comicID="+radioID);
Edit:
You also really should urlencode the parameter values, if they can contain spaces, etc. And to circumvent possible browser caching you can add a parameter with the time:
var d = new Date();
xmlhttp.send("comicID="+encodeURIComponent(radioID)+"&ts="+d.getTime());
There's no need to read that timestamp param on the server-side; its only to trick the browser.
Change the three first lines to, and everything should work fine.
if (isset($_GET["comicID"]))
{
$comic = $_GET["comicID"];
I actually solved it myself by accident. It turns out the error is that the program is halting at the point that it tries to delete all pages associated with a comic. When it is presented with an already empty comic, it tries to delete nonexistent records. Manually adding a page to the comic and THEN trying to delete the comic outright worked perfectly.
So basically, I just need error handling for empty comics.
Thanks for the pointers regarding POST, however.

Categories

Resources