Here's my JavaScript code to post to my API:
var pageRequest = new XMLHttpRequest();
pageRequest.open("POST", "/api.php", true);
pageRequest.onreadystatechange = function() {
if (pageRequest.readyState === 4 && pageRequest.status === 200) {
console.log(pageRequest.responseText);
}
}
pageRequest.send("firstname=John&lastname=Doe");
And here is my PHP backend code:
<?php
if (isset($_POST["firstname"]) && isset($_POST["lastname"])) {
$first_name = $_POST["firstname"];
$last_name = $_POST["lastname"];
echo "Hello, " . htmlspecialchars($first_name) . " " . htmlspecialchars($last_name);
} else {
echo "Please include all fields.";
}
?>
However, my PHP code just echos "Please include all fields.", and when I try doing
var_dump($_POST);
It returns an empty array. Am I doing something wrong here?
Thanks.
You are likely missing setup of request header:
var pageRequest = new XMLHttpRequest();
pageRequest.open("POST", "/api.php", true);
pageRequest.onreadystatechange = function() {
if (pageRequest.readyState === 4 && pageRequest.status === 200) {
console.log(pageRequest.responseText);
}
}
*** pageRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
pageRequest.send("firstname=John&lastname=Doe");
Related
I am studying a code and need help to learn further.
The JS code below is from a Q/A html form that sends data to server.
It crosschecks answer and on server and scores the user.
I need help writing a PHP code that receives the inputs using GET method and echo "ok" back to the html.
JS:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
if(this.responseText == "ok") {
document.getElementById("messagefont").innerHTML = checkans;
document.getElementById("answer").value = "";
document.getElementById('submit-btn').value = continuebutton;
checkans.focus();
PHP:
<?php
header('Content-Type: application/json');
$errors = array ();
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' );
if (isset ($_GET['answer'])) {
$answer = $_GET["answer"];
}
else {
array_push ($errors, no);
}
$response = "";
if (sizeof ($errors) > 0) {
$response = implode (",", $errors);
}
else {
$response = ok;
}
echo json_encode($response);
?>
I seem not to be getting something right with the PHP, please i need assistance/guide to fix the PHP code rightly.
I am sending echoing some data to be received in Javascript however when i debug it, it seems that a new line has been added.
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
require './connection.php';
$obj = json_decode($_POST["x"], false);
$usernamequery = "SELECT * FROM User WHERE username='$obj->newUser'";
$result = mysqli_query($db, $usernamequery);
$row = mysqli_fetch_assoc($result);
if($row["Username"] == null){
$updatequery = "UPDATE User SET User='$obj->newUser' WHERE username ='$obj->username'";
$result = mysqli_query($db, $updatequery);
echo "valid";
} else{
echo "invalid";
}
?>
JS
///// USERNAME
$(document).ready(function () {
$("#userSubmitForm").on("click", function(e) {
$username = document.getElementById("user").value;
$newUser = document.getElementById("newUser").value;
user = $newUser;
obj = { "username":$username, "newUser":$newUser};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "valid"){
$('#usernameModal .modal-header .modal-title').html("Result");
$('#usernameModal .modal-body').html("Your Username Has Been Changed to '$newUser'");
$("#passSubmitForm").remove();
$("#userCloseForm").remove();
window.setTimeout(redirect,3000);
} else{
$('#error').html("This Username Already Exists"); ;
}
}
};
What is happening is responseText will be receive "valid"/"Invalid" as "valid[newline]"/"invalid[newline]"
As stated at http://php.net/manual/en/function.echo.php that can't be a "problem" of the echo. There must be some newline-character after your -tags
A simple solution would be to just trim your response text like this: var validity = this.responseText.trim(); in order to strip it from unwanted space/tab/newline characters.
$adm=$_POST["admno"];
$phn=$_POST["phn1"];
include("model.php");
$db = new database;
$r=$db->register($adm,$schoolcode);
while($row=mysql_fetch_array($r))
{
if($row["phn_no1"]==$phn || $row["phn_no2"]==$phn || $row["phn_no3"]==$phn)
{
$formatted = "".substr($phn,6,10)." ";
$password = $formatted + $adm;
echo $password;
$db->setpassword($adm,$password,$schoolcode);
$pre = 'Dear%20Parents,Your%20Password%20is%20';
$suf = '%20ThankYou.CV';
$sms = $pre.$password.$suf;
session_start();
?>
<script>
window.onload = function(){
{
$("#active"+id).css({"color":"red"});
var http = new XMLHttpRequest();
var url = "http://www.perfectbulksms.in/Sendsmsapi.aspx?USERID=UID&PASSWORD=UPASS$&SENDERID=SID&TO=<?php echo $phn; ?>&MESSAGE=<?php echo $sms;?>";
var adm = "<?php echo $admno; ?>";
var params = "Id="+ id +"&adm="+adm;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(params);
window.location.href="#";
}
};
</script>
<?php
header("Location:password.php?msg=new");
this code is not working .. well it is change my password according to code but not sending the sms .. i m not using curl command because it works fine on localhost but on server it is not working..
This is not the right approach, if CURL is not available on your server then install it and then use CURL.
CURL installation process is defined here:
Help Doc
Help Doc
Still havent solved this. Can someone help me with my new, updated code. The new code is at the bottom of this post.
Im learning PHP and right now Im trying to learn to pass data from JS to PHP using AJAX.
This is my form:
<form id="login">
<label><b>Username</b></label>
<input type="text" name="username" id="username"
required>
<label><b>Password</b></label>
<input type="password" name="password" id="password"
required>
<button type="button" id="submitLogin">Login</button>
</form>
First I have a function, something like this:
try {
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}else{
Do stuff }
}
catch(error){ alert('"XMLHttpRequest failed!' + error.message); }
After this, Im trying to send my form data to a php-file, using new FormData(), but Im not really sure how to do this. Right now I have a code like this:
if (getElementById('username').value != "" & getElementById('password').value != "") {
request.addEventListener('readystatechange', Login, false);
request.open('GET', 'login.php', true);
request.send(new FormData(getElementById('login')));
}
The login-function is a function to test
if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
In my PHP-file I have a function looking like this right now:
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_GET['login'])) {
$Username = isset($_GET['username']) ? $_GET['username'] : '';
$Password = isset($_GET['password']) ? $_GET['password'] : '';
if (isset($logins[$Username]) && $logins[$Username] == $Password){
do stuff
}
What more do I need to pass my form data from the js-file to the php-file, so I can check if the input data is the same as the data I have in the array?
-----------------------------------------------------------------------
New code:
function LoginToSite() {
if (getElementById('username').value != "" && getElementById('password').value != "") {
request.addEventListener('readystatechange', Login, false);
var username = encodeURIComponent(document.getElementById("username").value);
var password = encodeURIComponent(document.getElementById("password").value);
request.open('GET', 'login.php?username='+username+"&password="+password, true);
request.send(null);
}
}
function Login() {
if (request.readyState === 4 && request.status === 200) {
alert("READY");
var myResponse = JSON.parse(this.responseText);
getElementById("count").innerHTML = myResponse;
getElementById('login').style.display = "none";
if(request.responseText == 1){
alert("Login is successfull");
}
else if(request.responseText == 0){
alert("Invalid Username or Password");
}
}
else{
alert("Error :Something went wrong");
}
request.send();
}
session_start();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if($username != '' and $password != ''){
foreach($user_array as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}
}else{
echo "0";
}
When im trying to login, the site first alert that something went wrong, then the same thing happens again and after that, it alerts "ready". What do I have to change to get this right?
Try running the following code.
HTML :
<form id="login">
<label><b>Username</b></label>
<input type="text" name="username" id="username"
required>
<label><b>Password</b></label>
<input type="password" name="password" id="password"
required>
<button type="button" id="submitLogin">Login</button>
</form>
JavaScript:
function submitLogin{
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var http = new XMLHttpRequest();
var url = "login.php";
var params = "username="+username+"&password="+password;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
if(http.responseText == 1){
alert("Login is successfull");
}
else{
alert("Invalid Username or Password");
}
}
else{
alert("Error :Something went wrong");
}
}
http.send(params);
}
PHP:
<?php
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_POST['username']) && isset($_POST['password'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
foreach($logins as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}
}else{
echo "0";
}
?>
I hope this helps you.
Basically you need something like this (JS side)
// create and open XMLHttpRequest
var xhr = new XMLHttpRequest;
xhr.open ('POST', 'login.php'); // don't use GET
// 'onload' event to handle response
xhr.addEventListener ('load', function () {
if (this.responseText == 'success')
alert ('successfully logged in.');
else
alert ('failed to log in.');
}, false);
// prepare and send FormData
var fd = new FormData;
fd.append ('username', document.getElementById("username").value);
fd.append ('password', document.getElementById("password").value);
xhr.send (fd);
PHP code (login.php) may look like this.
# users array
$logins = array ( 'username1' => 'pwd1', 'username2' => 'pwd2' );
# validate inputs
$u = isset ($_POST['username']) ? $_POST['username'] : false;
$p = isset ($_POST['password']) ? $_POST['password'] : false;
# check login
if ($u !== false && $p !== false && isset ($logins[$u]) && $logins[$u] == $p)
echo "success";
else
echo "error";
Course, it's recommended to check do functions XMLHttpRequest and FormData exist first.
if (window['XMLHttpRequest'] && window['FormData']) {
/* place your Ajax code here */
}
<?php
require_once './db_connect.php';
$db = new DB_Connect();
$db->connect();
$data = json_decode($_POST['myData']);
$array=json_decode($_REQUEST['question']);
if(isset($_POST['myData'])){
$obj = json_decode($_POST['myData']);
//some php operation
$q = "insert into questions(question)
values ('". $obj."')";
$result = mysql_query($q) or die(mysql_error());
}
?>
I want to retrieve the JSON data that is being sent from another php page to this page , but I just can't ,,why is that ?
here's the other page
function validateForm()
{
var q = document.forms["form1"]["question"].value;
var T = document.forms["form1"]["title"].value;
if (T == null || T == "")
{
alert("please type you form title first");
return false;
}
if (q == null || q == "")
{
document.getElementById("question").style.color="black";
alert("please enter your question");
return false;
}
question.push(q);
//alert(JSON.stringify(question));
var xhr = new XMLHttpRequest();
xhr.open('post', 'create_form.php',true);
// Track the state changes of the request
xhr.onreadystatechange = function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
alert(xhr.responseText); // 'This is the returned text.'
}else{
alert('Error: '+xhr.status); // An error occurred during the request
}
}
}
// Send the request to send-ajax-data.php
xhr.send({myData:JSON.stringify(question)}); //+encodeURI(JSON.stringify(question))
// addField();
return true;
}
can someone please help me ??
I'm tried to solve this using jquery ajax , it's just the same ,, that's why i tried to use only javascript to solve this
try this
$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE);
instead of this
$data = json_decode($_POST['myData']);
$array=json_decode($_REQUEST['question']);
if(isset($_POST['myData'])){
$obj = json_decode($_POST['myData']);