I'm using php and ajax to validate a html form.
Currently, when I submit my form, js print my php variables in html as one string, but I want to print them in different places, for that I've prepared span tags below each form field. For example, I want print $nameErr in the below name field, $numberErr in the below number field... etc.
For this my logic says I need first to save all my error variables in one array and then call it with ajax, but I don't know how to do this.
I would like to use pure js.
JS
submitBtn.addEventListener('click', function(){
myForm.onsubmit = function(event){
event.preventDefault();
}
var phpRequest = new XMLHttpRequest();
phpRequest.open('POST', 'form.php');
phpRequest.onload = function(){
phpMessage.insertAdjacentHTML('beforeend', phpRequest.responseText);
}
phpRequest.send();
});
PHP
$nameErr = $numberErr = '';
$fieldsErr = array($numberErr, $numberErr);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if(empty($_POST['name'])){
echo $nameErr = 'Name is required';
}else{
$name = test_input($_POST['name']);
}
if(empty($_POST['number'])){
echo $numberErr = 'Number is required';
}else{
$number = test_input($_POST['number']);
}
}
HTML
<form method="post">
<label>
<input type="text" name="name" placeholder="Your name*">
<span class="status-field-message"></span>
</label>
<label>
<input type="text" name="number" placeholder="Your phone number*">
<span class="status-field-message"></span>
</label>
</form>
submitBtn.addEventListener('click', function(){
myForm.onsubmit = function(event){
event.preventDefault();
}
var phpRequest = new XMLHttpRequest();
phpRequest.open('POST', 'form.php');
phpRequest.onload = function(){
phpMessage.insertAdjacentHTML('beforeend', phpRequest.responseText);
}
phpRequest.send();
response = JSON.parse(phpRequest.responseText);
document.getElementById('/name error div id/').innerHTML = response.nameError
document.getElementById('/number error div id/').innerHTML = response.numberError
});
This assumes the json response has an array defining nameError and numberError as key-value pairs.
Output variables as json in php with json_encode.
For example in php:
$errors = [];
if(empty($_POST['some])) {
$errors['some'] = 'empty';
}
echo json_encode($errors);
and handle this data in pure js:
var xmlhttp = new XMLHttpRequest();
var url = "http://someurl.net/page.php?param=123";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("POST", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].some;
}
document.getElementById("id01").innerHTML = out;
}
Related
I have a form that gets data from the database using a server-side code when the user inserts the "user_id" field.
I have many fields on my form, the main field is the User ID field, when the user inserts his user ID all the other fields will get the user data from the database. I managed to do all of that but I cannot do one thing which is to auto-populate the fields when the "User_id" field is filled by a link parameter. Please follow that link: https://aaa-wa.com/form-new/?user_id=2 and you will see that the user ID field on my form is filled by the link parameter 2, but the data doesn't get auto-populated until you remove the number 2 and type it in on by your keyboard.
I need when the user follows the link I send to him like: aaa-wa.com/form-new/?user_id=2 I need all of his data to be filled automatically without the need to type in his user id by the keyboard
So the JavaScript should get the user ID from the query parameters, and use that in the AJAX call.
My HTML Code
<form name='form1'>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>User Id</label>
<input type='text' name="user_id"
id='id' class='form-control'
placeholder='Enter user id'
onkeyup="GetDetail(this.value)" value="">
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<label>First Name:</label>
<input type="text" name="first_name"
id="first_name" class="form-control"
placeholder='First Name'
value="" required >
</div>
</div>
</div>
Javascript code
<script>
// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(str) {
if (str.length == 0) {
document.getElementById("first_name").value = "";
document.getElementById("last_name").value = "";
document.getElementById("phone_number").value = "";
return;
}
else {
// Creates a new XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
// Defines a function to be called when
// the readyState property changes
if (this.readyState == 4 &&
this.status == 200) {
// Typical action to be performed
// when the document is ready
var myObj = JSON.parse(this.responseText);
// Returns the response data as a
// string and store this array in
// a variable assign the value
// received to first name input field
document.getElementById
("first_name").value = myObj[0];
// Assign the value received to
// last name input field
document.getElementById(
"last_name").value = myObj[1];
// Assign the value received to
// last name input field
document.getElementById(
"phone_number").value = myObj[2];
}
};
// xhttp.open("GET", "filename", true);
xmlhttp.open("GET", "/wp-includes/gfg.php?user_id=" + str, true);
// Sends the request to the server
xmlhttp.send();
}
}
</script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#saveusers").on('click', function(){
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var email = $("#email").val();
var phone_number= $("#phone_number").val();
$.ajax({
method: "POST",
url: "/wp-includes/test1/saverecords_ajax.php",
data: { "first_name": first_name, "last_name": last_name, "email": email, "phone_number": phone_number},
}).done(function( data ) {
var result = $.parseJSON(data);
var str = '';
var cls = '';
if(result == 1) {
str = 'User record saved successfully.';
cls = 'success';
}else if( result == 2) {
str = 'Some of the fields are required.';
cls = 'error';
}else if( result == 3) {
str = 'Enter a valid email.';
cls = 'error';
}else if( result == 4) {
str = 'Enter a valid phone number.';
cls = 'error';
}else{
str = 'User data could not be saved. Please try again';
cls = 'error';
}
$("#message").show(3000).html(str).addClass('success').hide(5000);
});
});
});
</script><script>
function acceptParam() {
var hashParams = window.location.href.substr(1).split('?'); // substr(1) to remove the `#`
hashParams = hashParams[1].split('&');
var p = hashParams[0].split('=');
document.getElementById('id').value = p[1];
}
</script>
Call getDetail() in acceptParam(). And call acceptParam() when the page loads.
function acceptParam() {
var hashParams = window.location.href.substr(1).split('?'); // substr(1) to remove the `#`
hashParams = hashParams[1].split('&');
var p = hashParams[0].split('=');
document.getElementById('id').value = p[1];
getDetail(p[1]);
}
document.addEventListener("DOMContentLoaded", acceptParam);
I am trying to send both form data and a POST variable and I have no idea how to do it. I've tried to do this below:
const formthing = document.getElementById("theform");
function submitfunc(e){
e.preventDefault();
const thing = new XMLHttpRequest();
thing.open("POST", "edit.inc.php", true);
thing.onreadystatechange = function(){
if (thing.readyState == 4 && thing.status == 200){
var message = thing.responseText;
$("#theform").html(message);
}
}
var videoid = "watever";
thing.send(new FormData(formthing), "videoid="+videoid);
}
But it does not work as the php script returns "jo"
<?php
if (isset($_POST['videoid']){
}
else{
echo "jo"
}
?>
When I take a look in network it only looks like it is passing the form:
what I see
If anyone has any ideas, feel free to let me know! If anything needs to be made clear, please ask.
HTML:
<form id="my-form" action="/" method="post">
<input type="text" name="videoid"><input type="submit" value="Submit">
</form>
<div id="output"></div>
JS:
let myForm = document.querySelector( "#my-form" );
let output = document.querySelector( "#output" );
myForm.addEventListener( "submit", function(e) {
e.preventDefault();
let formData = new FormData( myForm );
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200 ) {
output.innerHTML = this.responseText;
}
}
xhr.open( "POST", "edit.inc.php" );
xhr.send( formData );
});
I am creating a site for listing TV shows and I am using TVMaze api for it. I am beginner in working with JSON so maybe my problem is that, but here is the weird thing happening.
My table is generated with this code:
var keyword = "";
var $url = "";
$('#submit').on('click', function (e) {
//e.preventDefault();
keyword = $('#search').val();
window.sessionStorage['keyword'] = keyword;
});
if (!window.sessionStorage['keyword']) {
$url = " http://api.tvmaze.com/shows?page=1";
} else {
keyword = window.sessionStorage['keyword'].toString();
keyword = keyword.toLowerCase().replace(/\s/g, "");
$url = "http://api.tvmaze.com/search/shows?q=" + keyword;
//alert($url);
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var $obj = JSON.parse(this.responseText);
for (var i = 0; i <= $obj.length - 1; i++) {
var $item = '<div> \
<div>\
<h2>' + $obj[i].name + '</h2> \
<div> ' + $obj[i].rating.average + ' </div>\
<p>' + $obj[i].summary + '</p>\
Track\
</div>\
</div>';
$('.show-items-container').append($item);
}
}
};
//alert($url);
xmlhttp.open("GET", $url, true);
xmlhttp.send();
So first it checks if there is keyword entered in a search bar and if there isn't it sends a request to the /page=1, and if there is a keyword entered, it should print the show. But, in my case, it reads to url like it is supposed to, but nothing shows up. And if I search that link in the browser it lists the correct show.
For example if I put 'kirby' in the search bar, it reads this url -> http://api.tvmaze.com/search/shows?q=kirby , but nothing shows in the table and there are no errors in the console. If you enter that same url in the browser, it works.
Can anyone tell me what the problem is?
Looks like onclick you are not making the xhr request. You call xmlhttp.open and xmlhttp.send outside of the click event so nothing happens on click. Also I noticed you were accessing the wrong property it should be $obj[i].show.___ vs $obj[i].___
var keyword = "";
var $url = "";
var xmlhttp = new XMLHttpRequest();
function makeRequest() {
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// clear the current search results
$('.show-items-container').empty();
var $obj = JSON.parse(this.responseText);
for (var i = 0; i <= $obj.length - 1; i++) {
// make sure you access the correct property
var $item = `<div>
<div>
<h2> ${$obj[i].show.name} </h2>
<div> ${$obj[i].show.rating.average} </div>
<p> ${$obj[i].show.summary} </p>
Track
</div>
</div>`;
$('.show-items-container').append($item);
}
}
}
// make the xhr request on click
xmlhttp.open("GET", $url, true);
xmlhttp.send();
}
$('#submit').on('click', function(e) {
keyword = $('#search').val();
$url = "https://api.tvmaze.com/search/shows?q=" + keyword;
// call on click
makeRequest();
});
// call on page load
makeRequest();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='search' />
<button type="button" id='submit'>Submit </button>
<div class="show-items-container">
</div>
I have 2 files in VIEW folder: addcustomer.php and phoneError.php.
addcustomer.php
<input type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>
<script type="text/javascript" >
function showHint(str) {
var base_url = <?php echo base_url(); ?>
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
// Get $p from phoneError.php
(xmlhttp.open("GET", "phoneError.php?p=" + str, true));
xmlhttp.send();
}
}
</script>
<input type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>
phoneError.php
<?php
defined('BASEPATH') || exit('No direct script access allowed');
$p = $_REQUEST['p']; // required
$string_exp = "/^[0-9]{3}[0-9]{3}[0-9]{4}$/";
if ($p == !preg_match($string_exp, $p)) {
echo $error_message .= '<span style="color:red">Oops! The Phone you entered does not appear to be valid.</span>';
}
?>
I want to add Ajax function into onkeyup event in addcustomer form to check valid phone number entered. I called addcustomer method and also loaded phoneError in Controller but did not work. I am not sure I put correct url for xmlhttp.open "GET".
Well if your are using Codeigniter you should know basic structure of it.
So put php code in same controller file which loads your view and name it as
public function phoneError(){
// your php code..
}
In html side
change id of span as id should be unique in same page.
Replace
<span id="txtHint"></span>
with this
<span id="txtResult"></span>
In input tag remove onKeyUp attr.
So replace with this
<input type="text" id="textHint" name="phone" placeholder="1235558888">
And some change in js
So basically your view file is as
addCustomer.php
<input type="text" id="textHint" name="phone" placeholder="1235558888" value="">
<span id="txtResult"></span>
<script type="text/javascript" >
$(document).ready(function () {
$("#textHint").keyup(function () {
var str = $(this).val();
$.get("http://localhost/sitename/controllername/phoneError?p=" + str, function (data) {
$("#txtResult").html(data);
});
});
});
</script>
Now try with this.
You can use this jquery code for your purpose. This code do exactly same that you want.
$("#textHint").keyup(function () {
$.get("phoneError.php?p=" + $(this).val(), function (data) {
$("#txtHint").html(data);
});
});
I need the onkeyup to fire more than once, but it seems to be only firing once!
When I enter something into the input box, it searches, but then whenever I backspace and search something else, the div stay's the same..
Here is my code:
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'dam_search.php?dam_text=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
Here is dam_search.php
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
ALSO: I am wondering how I can put the return of the name's it has searched into a dropdown from the input box instead of into the div, so when I click on one of the names, it auto fills the input box.
Thank you!
Still not sure about your issue with the keyup only firing once per page-load. That's very hard to speculate reasonably on without seeing more code. Never-the-less, here's an example I just threw together of how you can present the returned data in a more useful way.
The code requires that you download the AjaxRequest library I mentioned in an earlier comment.
(http://ajaxtoolbox.com/request/)
Here, I demo a few principles.
Arranging the data into a php class
constructing an array of instances of this class
returning this array as JSON
catching the JSON text and turning it back into an object in JS
Processing the data
I've given 2 very simple example - the first simply loads all filenames in the current directory (that holds jsonDir.php) into a select element. Choosing a filename results in it being copied into a text input next to the button.
The second, only retrieves names of png files. It chucks them all into a select element too. This time however, when an item is selected it is used as the src for an image. In each case the filenames are only grabbed if/when the corresponding button is pressed. There's a bit of redundant/otherwise crappy code I could have done better, but after 20 hours awake, I'm ready for bed!
Hope it's useful for you. Any questions, just ask. :)
1. jsonDir.php
<?php
class mFile
{
public $name, $time, $size;
}
if (!isset($_GET['wildcard']))
$wildCard = "*.*";
else
$wildCard = $_GET['wildcard'];
foreach (glob($wildCard) as $curFilename)
{
$curFileObj = new mFile;
$curFileObj->name = $curFilename;
$curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
$curFileObj->size = filesize($curFilename);
$fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>
2. readDir.html
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script/ajaxRequestCompressed.js'></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function myGetAjaxResponseWithCallback(url, target, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target); }
}
);
}
function getResults1()
{
var url = "jsonDir.php";
var target = byId('resultsDiv');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived1);
}
function getResults2()
{
var url = "jsonDir.php?wildcard=*.png";
var target = byId('resultsDiv2');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived2);
}
function jsonDataReceived1(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mStr = "There were " + resultObject.length + " records returned" + "<br>";
var mSel = newEl("select");
mSel.addEventListener('change', doAutofill, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = mStr;
targetContainer.appendChild(mSel);
}
function jsonDataReceived2(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mSel = newEl("select");
mSel.addEventListener('change', showSelectedImg, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = '';
targetContainer.appendChild(mSel);
}
function doAutofill(e)
{
var curSelIndex = this.value;
var curText = this.options[curSelIndex].label;
byId('autofillMe').value = curText;
}
function showSelectedImg(e)
{
byId('previewImg').src = this.options[this.value].label;
}
</script>
<style>
img
{
border: solid 2px #333;
}
</style>
</head>
<body>
<button onclick='getResults1()'>Get *.* dir listing</button> <input id='autofillMe'/>
<div id='resultsDiv'></div>
<hr>
<button onclick='getResults2()'>Get *.png dir listing</button> <img id='previewImg' width='100' height='100'/>
<div id='resultsDiv2'></div>
</body>
</html>
Found out my problem. The query wasn't correctly being processed!
I had the variable $dam_text as the LIKE statement, when it should have been $dam:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
Also, the variable $dam wasn't being submitted inide the function, so I moved it from the 'if' statement, into the function:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
getSuggest($text);
}
function getSuggest($text) {
$dam = $_GET['dam_text'];
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
The above code works perfectly! Turns out it wasn't onkeyup after all! Thanks for all your help!
OnKeyUp will only fire once per event. pressing 'A' 'B' and 'C' will result in three calls to suggest1();
To make sure your browser is working correctly try this
<script type="text/javascript">
function suggest1() {
document.getElementById('myDiv').innerHTML = document.getElementById('dam').value;
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
You should see the div change for every keystroke that occurs in the input.
There is two many unknowns for me to directly point at your actual issue.
Your PHP will output nothing for a zero entry query, and will only output 1 item if you query LIKE only matches one thing. I think your problem lies elsewhere, an not with onkeyup
T test to onkeyup on your system/browser:
Try adding some debug header like echo strlen($text).'<br />'; to your PHP file. You should see the number change with out relying on your SQL query for every key press that adds or deletes text (that includes the backspace key).
Your code looks fine. And runs fine for me using the public HTTP GET echo service at http://ivanzuzak.info/urlecho/
Swapping out your PHP for the echo service works fine (with a bit of a typing delay)
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'http://urlecho.appspot.com/echo?body=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>