How to get Ajax function for onkeyup event in Codeigniter - javascript
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);
});
});
Related
AJAX logic not working
I am new to AJAX and learning it. I am searching a food item in my HTML textbox and trying to communicate with the server to know if the item is available. The respective status of the item should be shown in the div tag below the textbox but it is not showing. I haven't studied jQuery yet and would like to know the below things: How to get the response from the server in plaintext using AJAX and JavaScript, and display it in the div tag below the textbox (advise the changes to be made in the code). What change should I make in JavaScript code to send the AJAX request in POST method (I know about the changes in PHP code)? //index.html <head> <script type="text/javascript" src="food.js"> </script> </head> <body> <h3>The Cheff's Place</h3> Enter the food you want to order <input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input> <div id="underInput"></div> </body> </html> //food.js var request; function sendInfo() { var v = document.getElementById("userInput").value; var url = "index.php?food=" + v; if (window.XMLHttpRequest) { request = new XMLHttpRequest(); } else if (window.ActiveXObject) { request = new ActiveXObject("Microsoft.XMLHTTP"); } if (request.readyState == 0 || request.readyState == 4) { try { request.onreadystatechange = getInfo; request.open("GET", url, true); request.send(null); } catch (e) { alert("Unable to connect to server"); } } } function getInfo() { if (request.readyState == 4) { if (request.status == 200) { var val = request.responseText; document.getElementById('underInput').innerHTML = val; } } } //index.php <?php header('Content-Type: text/plain'); $food = $_GET['food']; $foodArray = array("paneer", "butter", "chicken", "tandoori", "dal"); if (in_array($food, $foodArray)) { echo "We do have " .$food; } elseif($food == "") { echo "Kindly enter some food"; } else { echo "We do not sell " .$food; } ?>
I ran your code. It's working fine. Just replace onkeypress with onkeyup. <input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input> Using JQuery (Assuming you have included jquery file or cdn) : Include the following snippet in script tag at the end of the body. $("#userInput").keyup(function(){ $.get("index.php", { food: $("#userInput").val() }) .done(function(data) { $("#underInput").html(data) }) });
Print PHP variables each in different fields in html
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; }
Auto Link shorting via PHP&AJAX (bit.ly)
I would like to build a form (VIA POST METHOD) with just one field (url - link shortening). Now the question is how and if is it possible to build a form that detects the value of the URL field is a link and automatically shortens it rather than waiting you click Send (for exmaple like the web of Bit.ly). The main idea is once the field is an identifier that value is a proper Hyperlink is directly sends and shortens (And the field is replaced by a shortened link) it without waiting for the click on the SEND. index.html <html> <head> <script> function showHint(str) { 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; } }; xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send(); } } </script> </head> <body> <p><b>Start typing a url in the input field below:</b></p> <form> Url: <input type="text" onkeyup="showHint(this.value)"> </form> <p><span id="txtHint"></span></p> </body> </html> gethint.php <?php // get the q parameter from URL $q = $_REQUEST["q"]; $hint = ""; if (!filter_var($q, FILTER_VALIDATE_URL) === FALSE) { // short the link $rand = rand(1,1000); $hint = 'http://domain.com/'.$rand; } echo $hint === "" ? "Not a valid URL" : $hint; ?>
I'd use jQuery for the event triggering/AJAX and https://gist.github.com/dperini/729294 for weburl regex. I'm not that at home on pure JavaScript AJAX calls, but is xmlhttp.open("GET") the right way to go at it if you want to make a POST? Anyway the main thing you're missing is function isUrl(url){ var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i; if(regex.test(url)){ return regex.test(url); }else{ return regex.test("http://"+url); } } So this should be your new index.html <html> <head> <script> var extensions = [".aero",".biz",".cat",".com",".coop",".edu",".gov",".info",".int",".jobs",".mil",".mobi",".museum",".name",".net",".org",".travel",".ac",".ad",".ae",".af",".ag",".ai",".al",".am",".an",".ao",".aq",".ar",".as",".at",".au",".aw",".az",".ba",".bb",".bd",".be",".bf",".bg",".bh",".bi",".bj",".bm",".bn",".bo",".br",".bs",".bt",".bv",".bw",".by",".bz",".ca",".cc",".cd",".cf",".cg",".ch",".ci",".ck",".cl",".cm",".cn",".co",".cr",".cs",".cu",".cv",".cx",".cy",".cz",".de",".dj",".dk",".dm",".do",".dz",".ec",".ee",".eg",".eh",".er",".es",".et",".eu",".fi",".fj",".fk",".fm",".fo",".fr",".ga",".gb",".gd",".ge",".gf",".gg",".gh",".gi",".gl",".gm",".gn",".gp",".gq",".gr",".gs",".gt",".gu",".gw",".gy",".hk",".hm",".hn",".hr",".ht",".hu",".id",".ie",".il",".im",".in",".io",".iq",".ir",".is",".it",".je",".jm",".jo",".jp",".ke",".kg",".kh",".ki",".km",".kn",".kp",".kr",".kw",".ky",".kz",".la",".lb",".lc",".li",".lk",".lr",".ls",".lt",".lu",".lv",".ly",".ma",".mc",".md",".mg",".mh",".mk",".ml",".mm",".mn",".mo",".mp",".mq",".mr",".ms",".mt",".mu",".mv",".mw",".mx",".my",".mz",".na",".nc",".ne",".nf",".ng",".ni",".nl",".no",".np",".nr",".nu",".nz",".om",".pa",".pe",".pf",".pg",".ph",".pk",".pl",".pm",".pn",".pr",".ps",".pt",".pw",".py",".qa",".re",".ro",".ru",".rw",".sa",".sb",".sc",".sd",".se",".sg",".sh",".si",".sj",".sk",".sl",".sm",".sn",".so",".sr",".st",".su",".sv",".sy",".sz",".tc",".td",".tf",".tg",".th",".tj",".tk",".tm",".tn",".to",".tp",".tr",".tt",".tv",".tw",".tz",".ua",".ug",".uk",".um",".us",".uy",".uz", ".va",".vc",".ve",".vg",".vi",".vn",".vu",".wf",".ws",".ye",".yt",".yu",".za",".zm",".zr",".zw"]; var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); function isUrl(url){ var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i; if(regex.test(url)){ return regex.test(url); }else{ return regex.test("http://"+url); } } function showHint(str) { delay(function(){ str = str.toLowerCase(); var dot = str.lastIndexOf("."); var extension = str.substr(dot); extension = extension.split('/')[0]; var found = $.inArray(extension, extensions) > -1; if (!isUrl(str)||!found) { 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; } }; xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send(); } }, 500) } </script> </head> <body> <p><b>Start typing a url in the input field below:</b></p> <form> Url: <input type="text" onkeyup="showHint(this.value)"> </form> <p><span id="txtHint"></span></p> </body> </html> edit: Say you will start typing in http://www.example.net.. The AJAX will trigger on "http://www.example.ne" and then again when you add the last letter. To avoid that, you might try "change" instead of "keyup" event. edit2: Now checks against list of valid domain extensions edit3: Now waits half a second before posting the result. edit4: Small oversight while checking for extensions, fixed with extension = extension.split('/')[0]; Also if you want to enable users to write URL's without "http://" and similar, you'll need an edited regex or write a small hack that adds that to your string before you send it into "isUrl()".
Uploading file through ajax and jquery
Good evening guys, I got a problem in the back-end of my system when I submit my form. It said Unidentified index: file1 . I can't fine the error here in my code. I'm not a newbie in javascript and seeking for help from you guys. Advance thank you. So here is my HTML form <form id="submit_form" action="<?php echo base_url()?>Homepage/add_blog" enctype="multipart/form-data" method="POST" > <input type="text" class="form-control" id="title" name="title" autocomplete="off"> <input type="text" class="form-control" id="lead" name="lead" autocomplete="off"> <input type="text" id="tags" name="tags" data-role="tagsinput" placeholder="Add tags" class="form-control" > <input type="file" id="file1" name="file1" > <textarea id="content" name="content" rows="10" cols="80"> Put the content here!!! </textarea> </form> Here is my script <script> function _(el) { return document.getElementById(el); } $(document).ready(function() { $('#submit').click(function(e) { e.preventDefault(); var file = _("file1").files[0]; var title = $('#title').val(); var lead = $('#lead').val(); var tags = $('#tags').val(); var content = $('#content').val(); if(title == '' || lead == '' || tags == '' || content =='') { $('#response').html('<br><div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div>'); $('#response2').html('<div class="panel panel-danger"><div class="panel-body"><center><span class="text-danger">All fields are required</span></center></div></div><br>'); } else { $.ajax({ url:"<?php echo base_url()?>Homepage/add_blog", method:"POST", data:$('#submit_form').serialize(), beforeSend:function() { $('response').html('<span class="text-danger">Loading...</span>'); $('#submit').prop("disabled", true); var formdata = new FormData(); formdata.append("file1",file); var ajax = new XMLHttpRequest(); ajax.upload.addEventListener("progress",progressHandler,false); ajax.addEventListener("load",completeHandler,false); ajax.addEventListener("error",errorHandler,false); ajax.addEventListener("error",abortHandler,false); ajax.open("POST","<?php echo base_url()?>Homepage/add_blog"); ajax.send(formdata); }, success:function(data) { $('form').trigger("reset"); $('#tags').tagsinput('removeAll'); $('#tags').tagsinput('destroy'); CKEDITOR.instances.content.setData(''); $('#response').fadeIn().html(data); } }); } }); $('#title,#lead,#tags,#content').focus(function(){ $('#submit').prop("disabled", false); }); }); function progressHandler(event) { _("loaded_n_total").innerHTML = "Uploaded "+event.loaded; var percent = (event.loaded/event.total) * 100; _("progressBar").value = Math.round(percent); _("status").innerHTML = Math.round(percent)+"% uploaded.. please wait"; } function completeHandler(event) { _("progressBar").value = 0; } function errorHandler(event) { _("status").innerHTML = "Upload Failed."; } function abortHandler(event) { _("status").innerHTML = "Upload Aborted."; } </script> And the problem relies here in the back-end Homepage/add_blog: $filename = $_FILES["file1"]["name"]; echo $filename; If you any more details needed to solve this. Just comment. Need to fix this as soon as possible. Thank you again.
Undefined index notice that the array $_FILES does not contain the "file1" key set. Probably the way you are trying to send the file via ajax is not working properly. I'd recommend you try to use FormData. I believe the link below is a good reference to solve your problem. How to use FormData for ajax file upload
update database server with ajax and perl
I have set of code for updating a password in the table, here I'm using AJAX to update the password and get the popup screen on corresponding execution.When using that code with my application it is executing properly but I didn't get the output(password is not updated into table). I don't get any error either. Html page Code <html> <head> <div><IMG src="karvy.jpg" ALT="image"></div> <script language="javascript" type="text/javascript"> //Browser Support Code var xmlHttp; function fetch_javaScript(usr,oldpassword,newpassword,repassword) { xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Browser does not support HTTP Request"); return; } var usr = document.getElementById('usr').value; var oldpassword = document.getElementById('oldpassword').value; var newpassword = document.getElementById('newpassword').value; var repassword = document.getElementById('repassword').value; var url="changepwd1.pl"; url=url+"?usr=" + usr; url=url+"&oldpassword=" + oldpassword; url=url+"&oldpassword=" + newpassword; url=url+"&repassword=" + repassword; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("POST",url,false); xmlHttp.send(null); } function stateChanged() { if (xmlHttp.readyState==4 && xmlHttp.status==200) { document.getElementById("ajaxDiv").innerHTML=xmlHttp.responseText; } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { //Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } </script> </head> <body bgcolor="#D2B9D3"> <form name='myForm'> <center><table> <tr><td> <div style="width:400px;height:280px;border:3px solid black;"> <center><h4>Please Enter your Password's</h4> <p><b>User Name</b>        <INPUT TYPE=text NAME="usr" id = "usr" size = "15" maxlength = "15" tabindex = "1"/></p> <p><b>Old Password:</b>   <INPUT TYPE=PASSWORD NAME="oldpassword" id = "oldpassword" size = "15" maxlength = "15" tabindex = "1"/></p> <p><b>Password:</b>         <INPUT TYPE=PASSWORD NAME="newpassword" id = "newpassword" size = "15" maxlength = "15" tabindex = "1"/></p> <p><b>Re-Password:</b>   <INPUT TYPE=PASSWORD NAME="repassword" id = "repassword" size = "15" maxlength = "15" tabindex = "1"/></p> <input type="submit" id="val" value="Submit" align="middle" method="POST" onclick="fetch_javaScript()"/><INPUT TYPE="reset" name = "Reset" value = "Reset"/> <p>Main Menu <A HREF = login.pl>click here</A></p> </center> </div> </td></tr></table></center> </form> <div id='ajaxDiv'>Your result will display here</div> <!--<div id="myDiv"></div>--> </body> </html> Perl Code #!/usr/bin/perl use DBI; use strict; use CGI; my $cgi = CGI->new; print $cgi->header; print $cgi->start_html("Password Form"); print "Content-type: text/html\n\n"; my $request; ######################################## Query String if ($ENV{'REQUEST_METHOD'} eq "GET") { $request = $ENV{'QUERY_STRING'}; } elsif ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $request,$ENV{'CONTENT_LENGTH'}) || die "Could not get query\n"; } #$request="usr=sairam&oldpassword=password123&oldpassword=123456&repassword=123456"; my $j=0; my ($i,#update_value,#value); my #parameter=split(/&/,$request); for $i (#parameter) { #value=split(/=/, $i); $update_value[$j] =$value[1]; $j++; } my $user=$update_value[0]; my $oldpward=$update_value[1]; my $newpward=$update_value[2]; my $repward=$update_value[3]; #$user = $_SESSION['username']; if ($user) { ## Database Connectivity my $DSN = q/dbi:ODBC:SQLSERVER/; my $uid = q/ivr/; my $pwd = q/ivr/; my $DRIVER = "Freetds"; my %attr = (PrintError => 1,RaiseError => 1,); my $dbh = DBI->connect($DSN,$uid,$pwd,\%attr) or die $DBI::errstr;; my $sth=$dbh->prepare("select password from rpt_account_information where username='$user'") or die("Query didn't work"); $sth->execute(); my $oldpassworddb=$sth->fetchrow(); # check pass if ($oldpward==$oldpassworddb) { # check twonew pass if ($newpward==$repward) { #success #change pass in db if (length($newpward)>10||length($newpward)<4) #Here is the code { print "<script>alert('Password must be betwwen 4 & 10')</script>"; } else { my $p_update = $dbh->prepare("UPDATE rpt_account_information SET password=? WHERE username=?"); $p_update->execute($newpward,$user); #session_destroy(); print 'Your pass has benn changed.Return to the main page'; } } else { print "<script>alert('New Pass does not match')</script>"; } } else { print "<script>alert('Old Pass does not match')</script>"; } } This is my complete code but I'm not able to find out error or output Please help me...
Assigning a value to innerHTML that contains a <script> element won't cause that script to be executed. As a work around, you could parse the JavaScript out of it in JS and then eval it, but you would be better off dealing in structured data (e.g. JSON) and leaving your presentation logic to JavaScript already in the page.