Can't get AJAX calls or session to function - javascript

I have an extremely similar service like the one in this thread:
Php: Form auto-fill using $_SESSION variables with multiple php files
I would have asked there but since I don't have 50 reputation, I'll have to ask a new question.
To understand Ajax better I wanted to re-create rkmax's files and see if they would work. So I saved them as 5 separate files.
The SESSION does not seem to store any posted information. Added a print_r($_SESSION); to keep track of what's currently in there. Furthermore the .blur event to retrieve account information via the phone number doesn't work either.
Been banging my head against the wall for days with this one. It won't work when working either hosted locally via Apache/XAMPP or on an actual web server. All 5 files are in the same folder and titled exactly the same as rkmax's file titles.
I understand the logic behind each of the functions and can't seem to find a problem anywhere. I'm pretty new to coding so it could easily be something obvious like file structure or my own computer's settings?
Read a bunch of other StackOverflow threads with similar problems, but none of them seemed whatsoever applicable.
Thanks for your time.
Here's everything copied from rkmax's code:
index.php
<?php
session_start();
if (!isset($_SESSION['customers'])) {
$_SESSION['customers'] = array(
'1234567' => '{"lname": "Berg", "mi": "M", "fname": "Thomas", "account": "1234"}',
'1122334' => '{"lname": "Jordan", "mi": "C", "fname": "Jacky", "account": "4321"}',
);
}
require __DIR__ . '/index_template.php';
index_template.php
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<script src="scripts.js"></script>
</head>
<body>
<div style="margin-left: 300px">
<form id="dataForm" method="post">
<fieldset>
<legend>User info</legend>
<label for="fname">First name</label>
<input id="fname" type="text" name="fname" placeholder="First name"/>
<label for="mi">Middle inicial</label>
<input id="mi" type="text" name="mi" placeholder="Middle Initial"/>
<label for="lname">Last name</label>
<input id="lname" type="text" name="lname" placeholder="Middle Initial"/>
<label for="phone">Phone number</label>
<input id="phone" type="text" name="phone" placeholder="000000"/>
</fieldset>
<fieldset>
<legend>Account info</legend>
<label for="account">Account</label>
<input id="account" type="text" name="account"/>
</fieldset>
<input type="submit" name="submit"/>
<input type="reset" name="clear"/>
</form>
</div>
</body>
</html>
postCustomerInformation.php
session_start();
// example: converts $_POST['phone'] into $post_phone if exists
extract($_POST, EXTR_PREFIX_ALL, 'post');
// Validates that all required information was sent
if (isset($post_lname) && isset($post_fname) && isset($post_phone) && isset($post_account)) {
$customer = array(
'fname' => $post_fname,
'lname' => $post_lname,
'account' => $post_account,
'mi' => isset($post_mi) ? $post_mi : '' // optional
);
$_SESSION['customers'][$post_phone] = json_encode($customer);
// returns a valid json format header
header('Content-Type: application/json');
header("HTTP/1.0 204 No Response");
} else {
// returns error
header('Content-Type: application/json');
header("HTTP/1.0 400 Bad Request");
}
getCustomerInformation.php
session_start();
// example: converts $_GET['phone'] into $get_phone if exists
extract($_GET, EXTR_PREFIX_ALL, 'get');
if (isset($get_phone) && isset($_SESSION['customers'][$get_phone])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$get_phone];
} else {
header('Content-Type: application/json');
echo '{}';
}
scripts.js
;(function () {
"use strict";
function getCustomerInformation() {
var phone = jQuery(this).val();
if (!phone) {
return;
}
jQuery.ajax({
type: 'get',
url: 'getCustomerInformation.php',
data: {
phone: phone
},
success: function getCustomerInformation_success(data) {
// for each returned value is assigned to the field
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
}
});
}
function postCustomerInformation(event) {
event.preventDefault();
var form = jQuery(this);
jQuery.ajax({
type: 'post',
url: 'postCustomerInformation.php',
data: form.serializeArray(),
success: function postCustomerInformation_success() {
alert("OK");
},
error: function postCustomerInformation_error() {
alert("Error");
}
})
}
// set behaviors when document is ready
jQuery(document).ready(function document_ready() {
jQuery('#phone').blur(getCustomerInformation);
jQuery('#dataForm').submit(postCustomerInformation);
});
})();

I would try and do something a bit scaled down, see if this is what you are trying to do. You only need 3 pages, the original form page, the php page, and the js file:
/ajax/dispatch.php
/*
** #param $phone [string] Gets key from session
*/
function getCustomerByPhone($phone)
{
if(!empty($_SESSION['customers'][$phone])) {
// I am decoding, but if you have the ability to set,
// create an array like below with success and data
$values = json_decode($_SESSION['customers'][$phone]);
die(json_encode(array("success"=>true,"data"=>$values)));
}
}
function makeError()
{
// Send back error
die(json_encode(array("success"=>false,"data"=>false)));
}
/*
** #param $array [string] This will be a query string generated from the
** jQuery serialize, so it's to be turned to array
*/
function updateSession($array)
{
// This should come back as a string, so you will need to parse it
$data = false;
parse_str(htmlspecialchars_decode($array),$data);
// Update the session
$_SESSION['customers'][$data['phone']] = json_encode($data);
die(json_encode(array("success"=>true,"data"=>$data)));
}
if(isset($_POST['phone'])) {
// If already exists, return to ajax the data
getCustomerByPhone($_POST['phone']);
}
elseif(isset($_POST['data'])) {
updateSession($_POST['data']);
}
// If not exists, return false
makeError();
/scripts.js
// I try not to duplicate things as much as possible
// so I would consider making an object to reuse
var AjaxEngine = function($)
{
this.ajax = function(url,data,func,method)
{
method = (typeof method === "undefined")? 'post' : 'get';
$.ajax({
url: url,
data: data,
type: method,
success: function(response) {
func(response);
}
});
};
};
$(document).ready(function(){
// Create instance
var Ajax = new AjaxEngine($);
var dispatcher = '/ajax/dispatch.php';
// On submit of form
$(this).on('submit','#dataForm',function(e) {
// Get the form
var thisForm = $(this);
// Stop form from firing
e.preventDefault();
// Run ajax to dispatch
Ajax.ajax(dispatcher,
// Serialize form
$('#dataForm').serialize(),
// Create an anonymous function to handle return
function(response) {
// Parse
var resp = JSON.parse(response);
// See if data exists
if(typeof resp.data === "undefined") {
console.log(resp.data);
return false;
}
// If there is a hit in session
else if(resp.success == true) {
// Loop through it and fill empty inputs in form
$.each(resp.data, function(k,v){
var input = $("input[name="+k+"]");
if(input.length > 0) {
if(input.val() == '') {
input.val(v);
}
}
});
}
// Run the session update
Ajax.ajax(dispatcher,
// This time send an action
// (just to differentiate from check function)
{
"action":"update",
"data":thisForm.serialize()
},
function(response) {
// Check your console.
console.log(response);
});
});
});
});

Started from scratch working on my answer pretty much nonstop, but gotta go to work soon, here's what I've got so far; I'm currently stuck on successfully sending the SESSION data back to the javascript and decoding it and displaying it successfully. Once I have that working I think sending those to the appropriate forms as well as the POST will be trivial. If anyone has any suggestions to speed me through this last part I would appreciate it.
Edit: Edited with the final solution.
index2.php
<?php
session_start();
if (!isset($_SESSION['customers'])) {
$_SESSION['customers'] = array(
'1111111' => '{"phone": "1111111", "fname": "Za", "lname": "Zo", "mi": "Z", "account": "1234"}',
'2222222' => '{"phone": "2222222", "fname": "La", "lname": "Li", "mi": "L", "account": "4321"}',
);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title> Assignment5 </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type = "text/javascript" src = "scripts.js"></script>
</head>
<body>
<form id="myform">
<input placeholder="Phone Number" name="phone" type="text" id="phone" maxlength="7" autofocus>
<input placeholder="First Name" name="fname" type="text" id="fname">
<input placeholder="Last Name" name="lname" type="text" id="lname">
<input placeholder="Middle Initial" name="mi" type="text" id="mi">
<input placeholder="Account Number" name="account" type="text" id="account" maxlength="4">
<input type="submit" value="Submit">
</form>
</body>
</html>
scripts.js
$(document).ready(function(){
$("#phone").blur(function(){
var session;
var currentPhone = $("#phone").val();
$.get("getPhone.php", {phone: currentPhone}, function(data) {
for (var i in data) {
if (data.hasOwnProperty(i)) {
$('#' + i).val(data[i]);
}
}
});
});
$("form").submit(function(){
var form = jQuery(this);
$.post("postPhone.php", form.serializeArray(), function(data) {
alert(data);
});
});
});
getPhone.php
<?php
session_start();
$nowPhone = $_GET["phone"];
if (array_key_exists($nowPhone, $_SESSION['customers'])) {
header('Content-Type: application/json');
echo $_SESSION['customers'][$nowPhone];
} else {
header('Content-Type: application/json');
echo '{}';
}
?>
postPhone.php
<?php
session_start();
if (isset($_POST["phone"]) && isset($_POST["fname"]) && isset($_POST["lname"]) && isset($_POST["mi"]) && isset($_POST["account"])) {
echo ("Submitted");
$customer = array(
'phone' => $_POST["phone"],
'fname' => $_POST["fname"],
'lname' => $_POST["lname"],
'mi' => $_POST["mi"],
'account' => $_POST["account"],
);
$_SESSION['customers'][$_POST["phone"]] = json_encode($customer);
}
else
echo ("All Information is Required");
?>

Related

Calling Javascript function defined in external file through PHP

I have a web page on which i have a simple login form consisting of username and password text fields.
I validate the login form using javascript external file and if javascript code returns true, login form is submitted otherwise an error message is displayed via javascript function named displayErrorBlock() that i wrote.
If the form is submitted then using PHP, i verify username and password. If username/password combination is incorrect or doesn't exists in database, i want to call the same javascript function (displayErrorBLock) from PHP code.
To do this, i echo this
else { // if username/password combination is incorrect
echo '<script>displayErrorBlock("Incorrect Username/Password")</script>';
}
but this gives me displayErrorBLock undefined error because javascript is loaded at the end of the body tag of my web page.
Question
How can i call javascript function (displayErrorBlock) that is defined in an external file ?
This is the displayErrorBlock function defined in an external js file
function displayErrorBlock(errorMsg) {
'use strict';
let errorBlock = document.querySelector('.error-msg-block');
errorBlock.style.display = 'block';
errorBlock.firstElementChild.textContent = errorMsg;
setTimeout(function () {
errorBlock.style.height = '48px';
}, 10);
}
Edit
Here my entire web page
<?php
require 'DbConnection.php';
// if login button is clicked
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
verifyLoginCredentials($username, $password);
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session and login
// admin to his account
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
//take current admin to admin dashboard
header('Location:admin dashboard.php');
}
else { // if username/password combination is incorrect
echo '<script>displayErrorBlock("Incorrect Username/Password")</script>';
}
} else { // if username doesn't exists in the database
echo '<script>displayErrorBlock("Entered Username isn\'t registered")</script>';
}
}
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="../Resources/Bootstrap v4.1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="../CSS/admin login.css"/>
<link rel="stylesheet" href="../CSS/common.css"/>
<title>Admin Login</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 navbar-container">
<nav class="top-navbar">
<img src="../Resources/images/logo.png" alt="logo"/>
<p>Admin Panel</p>
</nav><!--end of navbar-->
</div><!--end of first column-->
</div><!--end of first row-->
<div class="row">
<div class="col-sm-4 login-form-container">
<p class="error-msg-block">
<span></span>
</p>
<form class="login-form" method="post" action="admin login.php" onsubmit="return validateForm()">
<p>Welcome Back!</p>
<div class="form-group username-group">
<label for="username-field">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<img src="../Resources/images/envelope.png" alt="envelope image"/>
</div>
</div>
<input class="form-control" id="username-field" type="text" name="username-field" id="username-field" placeholder="Username"/>
</div>
</div><!--end of first form group-->
<div class="form-group password-group">
<label for="password-field">Password</label>
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<img src="../Resources/images/lock.png" alt="lock image"/>
</div>
</div>
<input class="form-control" id="password-field" type="password" name="password-field" id="password-field" placeholder="Password"/>
</div>
</div><!--end of second form-group-->
<input type="submit" class="btn" id="login-btn" name="login-btn" value="Login"/>
</form><!--end of login form-->
</div><!--end of first column-->
</div><!--end of second row-->
</div><!--end of container-->
<!--CDN versions of JQuery and Popper.js-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="../Resources/Bootstrap v4.1/js/bootstrap.min.js"></script>
<script src="../Javascript/admin login form validation.js"></script>
</body>
</html>
Updated Question
I am facing a couple of problems.
I am getting whole web page as a response when i try to log to log .responseText to console inside .onLoad method.
When form is submitted via ajax, main if statement in php file
if(isset($_POST['login-btn'])) {....}
never evaluates to true, hence php code isn't executing.
What am i doing wrong here?
Here's my php code
<?php
require 'DbConnection.php';
// if login button is clicked
if(isset($_POST['login-btn'])) {
$username = $_POST['username-field'];
$password = $_POST['password-field'];
echo '<script>alert(\'form submitted\')</script>'; <---- this alert is never invoked
verifyLoginCredentials($username, $password);
}
// verify admin login credentials
function verifyLoginCredentials($username, $password) {
global $dbConnect;
$query = 'SELECT full_name, username, password FROM admins WHERE username = ?';
$statement = $dbConnect->prepare($query);
if($statement) {
$statement->bind_param('s', $username);
$statement->execute();
$resultSet = $statement->get_result();
// since there will be only one row returned at max, no need of a loop
$row = $resultSet->fetch_assoc();
if($row != null) {
$adminFullName = $row['full_name'];
$adminUsername = $row['username'];
$adminPassword = $row['password'];
// if username/password is correct start session and store
// username, password, full name in the session
if($username === $adminUsername && password_verify($password, $adminPassword)) {
session_start();
$_SESSION['current_admin_fullname'] = $adminFullName;
$_SESSION['current_admin_username'] = $adminUsername;
$_SESSION['current_admin_password'] = $adminPassword;
}
else { // if username/password combination is incorrect
echo 'Incorrect Username/Password Combination';
}
} else { // if username doesn't exists in the database
echo 'Entered username isn\'t registered';
}
} else {
echo 'Error while preparing sql query';
}
}
?>
Here's my relevant javascript code
let loginForm = document.querySelector('.login-form');
let usernameField = document.getElementById('username-field');
let passwordField = document.getElementById('password-field');
// submit login form to server using ajax
function ajaxFormSubmit() {
'use strict';
let ajaxRequest = new XMLHttpRequest();
let url = 'admin login.php';
// login form submitted on server successfully
ajaxRequest.onload = function () {
if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'success');
}
};
// error while login form submission on server
ajaxRequest.onerror = function () {
if (ajaxRequest.status !== 200) {
console.log(ajaxRequest.responseText);
displayInfoMessage(ajaxRequest.responseText, 'error');
}
};
ajaxRequest.open('POST', url, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(new FormData(loginForm));
}
function validateForm(e) {
'use strict';
// prevent form submission
e.preventDefault();
if (anyEmptyField()) {
displayInfoMessage('Please fill all the empty fields', 'error');
highLightEmptyFields();
//return false;
return;
}
// check if username is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, usernameField.value))) {
displayInfoMessage('Username not valid', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if username is atleast 3 characters long
if (usernameField.value.length < 3) {
displayInfoMessage('Username should contain atleast 3 characters', 'error');
highLightTextField(usernameField);
//return false;
return;
}
// check if password is in right format
if (!(regexTester(/^[A-Za-z0-9_]+$/g, passwordField.value))) {
displayInfoMessage('Password not valid', 'error');
highLightTextField(passwordField);
//return false;
return;
}
// check if password is atleast 6 characters long
if (passwordField.value.length < 6) {
displayInfoMessage('Password should contain atleast 6 characters', 'error');
highLightTextField(passwordField);
//return false;
return;
}
//return true;
// submit form information to server via ajax
ajaxFormSubmit();
}
// add submit event listener on login form
loginForm.addEventListener('submit', validateForm);
Inside the <head></head> elements of your HTML structure, add the following code:
<script type="text/javascript">
// Wait for the document to load
document.addEventListener("DOMContentLoaded", function(event) {
// Add event listener to form submit
document.querySelector(".login-form").addEventListener("submit", function(e) {
// Prevent the form from being submitted
e.preventDefault();
// Perform displayErrorBlock() function
validateForm();
// Create native XMLHttpRequest object
var xhr = new XMLHttpRequest();
// Set POST request header leaving second parameter empty because PHP
// code is in the same file.
xhr.open('POST', '');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
// Everything was ok, handle response
if (xhr.readyState === 4 && xhr.status === 200) {
// Succesful login. Redirect user
if(xhr.responseText === 'succes'){
window.location.replace("https://your_website.com/admin dashboard.php");
}
// Wrong username / password
else if(xhr.responseText === 'errorUserPass'){
displayErrorBlock("Incorrect Username/Password");
}
// User doesn't exist
else if(xhr.responseText === 'errorNotRegistered'){
displayErrorBlock("Entered Username isn't registered");
}
// Something else was returned by PHP
else {
displayErrorBlock("Unknown error: "+ xhr.responseText);
}
}
// Request failed, alert error
else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(new FormData(document.querySelector(".login-form")));
});
});
</script>
I've commented on most lines to explain what they do. Next you'll have to change your form to:
<form class="login-form" method="post" action="">
As we've created a custom event handler on the form, everything is controlled from there. So it's no longer needed to do this in your HTML structure.
Lastly you'll need to change your PHP code in such a way that it returns the correct responses:
Replace: header('Location:admin dashboard.php'); with echo 'succes';
Replace: echo '<script>displayErrorBlock("Incorrect Username/Password")</script>'; with echo 'errorUserPass';
Replace: echo '<script>displayErrorBlock("Entered Username isn\'t registered")</script>'; with echo 'errorNotRegistered';
As I said in the comments, it's been a while since I did this in native JS. I was unable to actually test this code, so let me know if something is wrong. Or at least it should help you into the right direction.

ajax request function does not work when its called

<script type="text/javascript"src="prototype.js"></script>
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
function sendRequest() {
var oform = document.forms[0];
var sBody = getRequestBody(oform);
var oOptions = {
method: "post",
parameters: sBody,
onSuccess: function (oXHR, oJson) {
saveResult(oXHR.responseText);
},
onFailure: function (oXHR, oJson) {
saveResult("An error occurred: " + oXHR.statusText);
}
};
var oRequest = new Ajax.Request("edit_status.php", oOptions);
}
function saveResult(sMessage) {
var divStatus = document.getElementById("divStatus");
divStatus.innerHTML = "Request completed: " + sMessage;
}
});
//]]>
</script>
I am new to ajax. i have a project at hand that really need a lot of ajax functionality. I am following this above code from a book i bought. when i copy this code on my local server, the ajax.request function is not working when i click the submit button. It takes me straight to the php page. Please can someone help me look at this?
**
<form method="post" action="SaveCustomer.php"
onsubmit="sendRequest(); return false">
<p>Enter customer information to be saved:</p>
<p>Customer Name: <input type="text" name="txtName" value="" /><br />
Address: <input type="text" name="txtAddress" value="" /><br />
City: <input type="text" name="txtCity" value="" /><br />
State: <input type="text" name="txtState" value="" /><br />
Zip Code: <input type="text" name="txtZipCode" value="" /><br />
Phone: <input type="text" name="txtPhone" value="" /><br />
E-mail: <input type="text" name="txtEmail" value="" /></p>
</form>
<div id="divStatus"></div>
**
**
header("Content-Type: text/plain");
//get information
$sName = $_POST["txtName"];
$sAddress = $_POST["txtAddress"];
$sCity = $_POST["txtCity"];
$sState = $_POST["txtState"];
$sZipCode = $_POST["txtZipCode"];
$sPhone = $_POST["txtPhone"];
$sEmail = $_POST["txtEmail"];
//status message
$sStatus = "";
//database information
$sDBServer = "localhost";
$sDBName = "ajax";
$sDBUsername = "root";
$sDBPassword = "";
//create the SQL query string
$sSQL = "Insert into Customers(Name,Address,City,State,Zip,Phone,`Email`) ".
" values ('$sName','$sAddress','$sCity','$sState', '$sZipCode'".
", '$sPhone', '$sEmail')";
$oLink = mysql_connect($sDBServer,$sDBUsername,$sDBPassword);
#mysql_select_db($sDBName) or $sStatus = "Unable to open database";
if ($sStatus == "") {
if(mysql_query($sSQL)) {
$sStatus = "Added customer; customer ID is ".mysql_insert_id();
} else {
$sStatus = "An error occurred while inserting; customer not saved.";
}
}
mysql_close($oLink);
echo $sStatus;
?>
**
you arent firing the ajax i see you define the options but thats it try
using jquery u can wait for form submission
$('your form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'your url',
type:'post',
data:'your data',
success:function(data, jxhr){
//your success function
},
error:function(){}
});
});
the e.preventDefault() prevents the synchronous submission from firing default methods
looking at your code the sendRequest() can be changed to sendRequest(event) then add the event.preventDefault. I always have issues with return false

Why is my newsletter form not working on Amazon CloudFront?

I am using HTML and using amazon EC2 (Linux free tier). I would like to use CloudFront, but my newsletter won't work. I am not an AWS expert, and I don't have a clue as to why it won't work on CloudFront.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName" name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail" name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</span>
</div>
</form>
and my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
The form works when I access it without using CloudFront, but I am worried of the server bandwidth that's why I want to use CloudFront. What happens is that when you click the submit button, the "adding email address" message will just appear for 1 second, and the email address entered is ignored.
Please make sure your CloudFront distribution is actually configured to handle POST/PUT requests. Take a look here for details: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesAllowedHTTPMethods

post data to PHP page in external server and load content from JavaScript in local computer

I want to post data to a PHP file in a server (www.domaine.com) using a JavaScript located in computer / mobile app
example : test.php
<?php
$x = $_POST['count'];
for ($i = 0; $i < $x; $x++)
echo $x;
?>
data to be post using JavaScript and PSOT method to test.php
example
input
test.php / post data : count=5
output
01234
I want JavaScript to get me the output (01234) after posting (count=5) to (test.php) located in external server (www.domaine.com)
I basically develop in C# but as I'm obliged to do a cross-platform mobile app I switched to JavaScript (won't use Xamarin) for C# I was able to do everything using WebBrowser but not anymore in JavaScript, isn't there any object equivalent to WebBrowser in .NET ?
I need it for a mobile app that will load data from GPS Tracking website, API returns data in both XML and JSON
note : I don't have access to the external server
Here I'll give you a pretty good example of how these things are usually managed.
Still, it's up to you and your programming experience to grasp the meaning of it.
html and js example:
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
}
$("#submit").click(function(){
$("#formId").submit();
});
$(document).ready(function () {
$("#formId").bind("submit", function (event)
{
$.ajax({
async: true,
data: $("#formId").serialize(),
success: function(data, textStatus) {
getPhpResponse( data )
},
type:"POST",
url:"name/and/location/of/php/file.php"
});
return false;
});
});
</script>
file.php example:
<?php
$x = $_POST['count'];
echo '{"response":"';
for ($i = 0; $i < $x; $i++)
{
echo $i;
}
echo '"}';
Poxriptum:
There should be further input validation, one can't trust the type="number" just yet.
That the submit button is a span instead of an input is a personal choice that makes difference just for styling purposes.
You should read up on AJAX and JSON.
Consider using a PHP framework, such as CakePHP; it may serve you well.
This answer assumes you have access to the server. If you don't, then you should be reading the API documentation instead of asking questions on SO without even detailing which API you are talking about.
Edit:
Here is the $less version.
<form action="" id="formId" method="post" accept-charset="utf-8">
<label for="inputNumber">Input something: </label>
<input type="number" id="inputNumber" name="count"></input>
</form>
<span id="submit">Submit</span>
<script>
document.getElementById("submit").onclick = function () {
var url = 'name/and/location/of/php/file.php';
var userInput = encodeURIComponent(document.getElementById("inputNumber").value);
var data = "count=" + userInput;
makeRequest( data, url );
};
var getPhpResponse = function( data ) {
console.log("manage php response HERE");
console.log(data);
parsed = JSON.parse(data);
console.log(parsed);
}
var xhr = new XMLHttpRequest();
var makeRequest = function( data, url ) {
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send(data);
};
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if ( xhr.readyState == 4 )
{
if ( xhr.status == 200 || window.location.href.indexOf("http") == -1 )
{
getPhpResponse(xhr.responseText);
}
else
{
console.log("Manage error here");
}
}
}
</script>

How to ajax POST to php

I can't seem to figure out how to use ajax to post. I made a silly form to try it out and even after having cut it all the way down to just two values, still can't get anything to work. My html is this:
<html>
<head>
<script type="text/javascript" src="j.js"></script>
<title>Test this<
<body>/title>
</head>
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="submit" value="Submit Form" />
</form>
<div id="status"></div>
</body>
</html>
Then, my external javascript is just a single function so far:
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
While my php just echoes the stuff back:
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
I can't find anything wrong in firebug or in chrome's toolsy thingies..
Can anybody who me what I'm doing wrong?
The whole problem is caused by the fact that you are both submitting the form and performing an AJAX call! status is for sure updated, but in the same moment the page is refreshed (notice that the <input>-values disappear)
Simply avoid the form submit by altering the markup,
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
and your code works. Or dont use a form at all. It is to no use when you are AJAXing anyway.
update
I reproduced the whole scenario before answering :
xhr.html
<html>
<head>
<title>Test this</title>
</head>
<body>
<form name="testForm" action="" method="">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="button" value="Submit Form" onclick="postStuff();" />
</form>
<div id="status"></div>
<script>
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "xhr.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
console.log(hr);
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</body>
</html>
xhr.php
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
Make the:
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<input type="submit" value="Submit Form" />
</form>
into a button tag:
<form name="testForm">
First Name: <input type="text" name="fname" id="fname" /> <br />
Last Name: <input type="text" name="lname" id="lname" /> <br />
<button type="button" onclick="postStuff();">Submit Form!</button>
</form>
The page refreshes from the form submit as far as I can see. You don't need to use a form if you're using ajax.
Also read: Why is using onClick() in HTML a bad practice? since you're enclosing the post in a function anyway.
EDIT: I just noticed your title and head tags are broken in the source you've put up.
Here's how I do it:
In your html file put <SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.js"></SCRIPT>
Then you can call this function that will call (in my case) queryDB.php script.
function queryDB(db,query,doAfter){
$.ajax({
type: 'POST',
data: { host: "localhost",
port: "5432",
db: db,
usr: "guest",
pass: "guest",
statemnt: query
},
url: 'scripts/php/queryDB.php',
dataType: 'json',
async: false,
success: function(result){
// call the function that handles the response/results
doAfterQuery_maps(result,doAfter);
},
error: function(){
window.alert("Wrong query 'queryDB.php': " + query);
}
});
};
Send post to test.php in the same hierarchy and accept the result in html variable
$.ajax(
{
type: "POST",
url: "test.php",
data: {'test': test, 'name': 0, 'asdf': 'asdf'},
success: function(html)
{
alert(html);
}
});
In PHP of the recipient, specify it as follows
<?php
echo "come here";
echo $_POST['test'];
?>
Directory structure
$ tree
.
├── a.php
└── test.php
reference
https://off.tokyo/blog/ajax%E3%81%A7post%E3%82%92%E5%8F%97%E3%81%91%E5%8F%96%E3%82%8B%E6%96%B9%E6%B3%95/
Perhaps it's best for you to use a library like jquery and then you can do something like : $('form').submit(function(){$.post('detinatnion', $('form').serialize());});
but to answer your question since you have a reason for using pure js then:
<form method="post" action="pathToFileForJsFallback.">
First name: <input type="text" id="fname" name="fname" /> <br />
last name: <input type="text" id="lname" name="lname" /> <br />
<input type="submit" value="Submit Form" />
<div id="status"></div>
</form>
JS:
function postStuff(){
var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
for (var i=0; i<activexmodes.length; i++){
try{
mypostrequest = new ActiveXObject(activexmodes[i]);
}
catch(e){
//suppress error
}
}
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
mypostrequest = new XMLHttpRequest();
else
return false;
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("result").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var fname=encodeURIComponent(document.getElementById("fname").value);
var lname=encodeURIComponent(document.getElementById("lname").value);
var parameters="fname="+fname+"&lname="+lname;
mypostrequest.open("POST", "destination.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
Again my recommendation to you is to learn js with a library like jquery, because by the time you learn how to do these stuff, these libraries, hardware and everything will be so fast that javascript code like this will become useless for practical every day use.
u need to return false at the end of the function.
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
return false;
}

Categories

Resources