Autocompleting textboxes with AJAX using variables from a PHP file - php

I am doing a project where I need to make sure that my form instantly autofills 2 textboxes based on input from the first textbox. Right now I am just testing. I can't use database entries to populate my form, only PHP variables. My logic needs to be like this: user types in a specific 10 digit number into a textbox on my form (specified in a PHP file), then the other two textboxes get autofilled with specific entries after an AJAX call to that PHP file. This is definitely one of the more complex tasks that I've encountered so far (noob). My code doesn't work, so I would really appreciate any help with getting it to function properly.
HTML is like this:
<!--load scripts, libraries, etc.-->
<form method="GET">
Number: <input type="text" name="num" id="num">
First Name: <input type="text" name="first" id="first">
Last Name: <input tupe="text" name"last" id="last">
</form>
PHP:
<?php
$num=$_GET["num"];
$first=$_GET["first"];
$last=$_GET["last"];
if ($num=="0123456789")
{
$fill = array(
'firstname' => $first["John"],
'lastname' => $last["Smith"],
);
echo json_encode($fill);
}
else
{
echo "Bad input.";
}
?>
jQuery:
$(document).ready(function () {
$("#num").keyup(function () {
var el = $(this);
if (el.val().length === 10) {
$.ajax({
url: "http://localhost/test.php",
cache: false,
dataType: "json",
type: "GET",
data: "npi=" + el.val(),
success: function (result) {
$("#first").val(result.firstname);
$("#last").val(result.lastname);
}
});
}
});
});

in ajax change like this it'll be easy to understand
type: "GET",
data:{num: el.val()},//if multiple then like this->data:{attr:val1,attr2:val2,...},
in php
<?php
$first["John"]="john";//i hope you have these two values defined
$last["Smith"]="smith";
$num=$_GET["num"];
if ($num=="0123456789")
{
$fill = array(
'firstname' => $first["John"],
'lastname' => $last["Smith"],
);
echo json_encode($fill);
}
else
{
echo "Bad input.";
}
?>
explanation
see the process is like
first the number will go to php with the help of ajax(through the
ajax request)
type: "GET",,
data: {num: el.val()},
so as we are sending the number as GET request to php, in php we get this number with $_GET['num'] so now this value will have 0123456789 value in it.
now we are checking with if condition in php
if ($num=="0123456789")
{
//here we need to send the firstname and lastname values BACK TO THE AJAX REQUEST
so we need to have these first and last names here in php defined somewhere manually or get it from database(if you have these first,last names in DB)
echo json_encode($fill);
}

Related

Ajax in CI not working

This is the first time I am working with CI+AJAX+JSON.
I have a controller Admin.php inside controllers directory of Codeigniter. The controller code is as under:
public function getmylist()
{
$users_arr[] = array("sno" => "1", "myname" => "hello");
echo json_encode($users_arr);
}
Then, in views, I have a view with the following code:
<select class="form-control" name="mod_countries" id="mod_countries">
<?php
if(isset($countrylist))
foreach($countrylist as $c)
echo "<option value=" . $c->cname . ">".$c->cname;
?>
</select>
Then my target select which i need to populate from ajax is
<select class="form-control" name="mod_newlist" id="mod_newlist">
</select>
My ajax is as under:
$(document).ready(function() {
$('#mod_countries').change(function(event) {
var cname = $("select#mod_countries").val();
alert(cname);
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>" + "Admin/getmylist",
dataType: "json",
data: {mcname: cname},
success: function(res){
if(res) {
var len=res.length;
$("#mod_newlist").empty();
for(var i=0; i<len; i++)
{
var sno=res[i]['sno'];
var myname=res[i]['myname'];
$("#mod_newlist").append("<option value='" + sno + "'>"+myname+"</option>");
}
}
else
{
console.log('hitting');
}
},
error: function(res, status, error) {
var err = res.responseText;
alert(res.Message);
alert(status);
alert(error);
}
});
});
});
When I select an item from the first dropdown list, I get the selected item. Now I expect the second drop downlist to get an item from the controller's code. but, my code goes into error block and alert shows following error messages for each alert line of code:
undefined
parsererror
SyntaxError: Unexpected token I in JSON at position 0
Please tell me where I am making a mistake?
Also, please help with regards to how should I return the sno->name pair from model because at lat, i want to populate the new select from database.
Remove debug/garbage data from response, like I am called. If still not work then parse JSON in success as following
var res = $.parseJOSN(res);
if(res) {
.....
You are not passing data correctly.
it should be like
data:{
"key" : value
//use " " to encapsulate string values, only in case of variable You pass value without ""
}
I am using CodeIgniter for last two months now. And earlier I had a lot of trouble working with ajax. But my friend suggested me to use AngularJs. It took me just one day to learn Angular and it turned out to be extremely helpful.
It will save a lot of time. And make your work so easy. At first, it may sound difficult but if u spend some time coding then it is going to make your life a lot better. I learned it from JavaTpoint.com and it was very well explained.
Do not try to understand everything at once and practice as you learn.

php+jquery get values from serialized form with input name array

I'm developing a PHP+jQuery application. I'm quite noob with PHP.
Anyway, I'm trying to send a serialized form to a PHP page that will store data to session, via jQuery.
This is a dynamic form, where I could have many input like this:
<input type="text" name="name[]" />
And this is an example of my serialized form:
name[]=name1&name[]=name2
I've tried to get the array with $_POST["name"] from the PHP page, but it did not work.
How can I get this array from the PHP page?
Are you doing something like this???
$(function() {
$('.submit').click(function() {
var names = $('input[name="name[]"]').map(function(){
return this.value;
}).get();
$.ajax({
type: 'POST',
url: url,//this should link to your page
data: {
'name[]': names,
// other data
},
success: function() {
}
});
});
});
</script>

I can't send full data through ajax script on php language. (code igniter)

<script language='javascript' type='text/javascript' charset='<?=$page_charset?>'>
$(document).ready(function(){
$('#btn_login').click(function(){
$.search_keyword();
});
});
here is the script
<form name='frm_search_keyword'>
<table style='width:250px;'>
<tr>
<td style='width:100px;'>
Search
</td>
<td>
<input type="text" name="web_keyword" />
</td>
<td>
<input type="submit" id="btn_login" name="btn_login" value="search!" />
</td>
</tr>
</table>
</form>
here is the form
search_keyword:function(type)
{
$.ajax({
type: 'POST',
url: '/web_keyword',
data: {'b_type':type},
cache: false,
async: false,
success: function(result){
if(result == 12001)
{
alert('please choose your interest.');
location.href = '/account/interest';
}else
location.href = '/'+type+'/'+result;
}
});
}
It successfully sends 'web_keyword' to db query and get result.
but I can't get type data through ajax script.
Can you help me to 'type' data from the form table to ajax script?
Thank you.
I'm not exactly sure if this is the problem, but it is suspect:
$('#btn_login').click(function(){
$.search_keyword();
});
Where is "type" supposed to come from? What is "type" referring to? Is "type" a value returned from your DB query? Or is it something selected by the user when they perform the search?
If type is something within your form element, then use Javascript or jQuery, or whatever, to "harvest" that value from the page, and then you will need to pass that data to the AJAX functionality.
$('#btn_login').click(function(){
//First get the "type" value, for example if "type" is retrieved from the form element
var type = $('#btn_login').attr('type'); //this is for example's sake, since you did not assign an id to this form element...
search_keyword(type);
});
You just need to get "type" from where ever it is being generated and/or stored and pass it to your AJAX function.
Also, maybe this is irrelevant, but your "search_keyword()" function definition looks odd to me...
Instead of:
search_keyword:function(type){...}
Should be:
search_keyword = function(type){...}
One final thing, could you tell us which Javascript library you are using?
Try adding
" dataType: 'json'," like
$.ajax({
type: 'POST',
url: '/web_keyword',
dataType: 'json',
data: {'b_type':type},
});
and return the date using
$data['return1']='true';
echo json_encode($data);
success: function(result){
if(result.return1 == 12001)
{
alert('please choose your interest.');
location.href = '/account/interest';
}else
location.href = '/'+type+'/'+result;
}
you should remove async:false
Setting this option to false is strongly discouraged, as it can cause the browser to become unresponsive.

Storing selected checkboxes in array and use it with facebox

I'm having some trouble using jQuery's plugin Facebox to process some data from a form.
What I'm trying to accomplish is basically get the values of the number of selected checkboxes into an array and have it available in my popup to process it with PHP.
I have something like this on a form page:
form.html
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="button" name="replace" onClick="replace_equip()" />
There are more checkboxes, but I think these are enough to get started.
Here is replace_equip()
function replace_equip() {
var nArr = new Array();
$("input:checkbox[name=equip]:checked").each(function() {
nArr.push($(this).val());
$.facebox(function() {
$.ajax({
data: { name : nArr },
error: function() {
$.facebox("err");
},
success: function(data) {
$.facebox(data);
},
type: "post",
url: "test.php"
});
});
});
}
I'm trying to save the selected checkboxes into an array, in a way that I can use it for PHP processing in test.php.
I'm just getting started with jquery and javascript in general, so forgive any monster mistakes you may find!
To get started, there are a few stylistic issues with your code. First, you should opt not to use new syntax with Arrays, Objects, etc. Instead, declare your Array with something like var array = [];. Second, you're using an inline onClick, which should be avoided if you're using jQuery already. Instead, use something like $('input[name="replace"]').on('click', function() {...});. You should also consider using camelCase with your functions, and if you like underscores, use them with vars.
Now onto the meat of your question. I refactored your code like so:
$('input[name="replace"]').on('click', function() {
replaceEquip();
});
function replaceEquip() {
var array = [];
$("input:checkbox[name=equip]:checked").each(function() {
array.push($(this).val());
});
$.facebox(function() {
$.ajax({
type: "POST",
url: "test.php",
data: { name : array },
error: function() {
$.facebox("err");
},
success: function(data) {
$.facebox(data);
}
});
});
}
In your PHP code, you would json_decode() this array and work with it how you want. I also moved the type and url params to the top, as your error and success functions may get quite lengthy.
I would consider reading JavaScript Patterns (at least the Essentials chapter).

Ajax and php Question

Finally got my domain checker working. Now the question is I have a form (search-domains) when user types and submits at the moment it passes the query to process.php and that out puts:
echo "$Domain is/isn't available"
What I want is this to return on my results page (the results page also has a search form on it so if someone searches there it would display on same page). At the moment when user clicks it passes http://example.com/process.php?domain=domain.com(etc...).
What i think i need is Ajax to pull this url before it goes to process.php then ajax runs the query process sends result back to ajax an it outputs on the results page. Also I have another php script which displays the domain with different tlds and displays id they are available or not. So i also need ajax to run this and display aswell.
I am very new to ajax but looking for tutorials but most of them are for displaying success messages after contact forms and the like. If someone could point me in the right direction id much appreciate it.
EDIT
This is what i have but itsd still re-directing me to process.php
HTML
<form method="get" id="form">
<input type="text" class="searchdomains" onclick="if (this.value =='Domain Name Search...'){this.value=''}" value="Domain Name Search..." name="domain" id="search-domain-input">
<input type="image" src="<?php bloginfo('template_url'); ?>/inc/img/btn_up_search.png" class="search" name="Search" id="Submit">
</form>
JQuery
$.ajax(
{
type: 'GET',
url : "http://example.com/process.php?domain=",
// here you pass js object in convention: { 'query_string' : 'its value' }
data : { 'domain' : $('#search-domain-input').val() },
success: function (data) {
$("#results").html(data);
}
}
);
PHP
if(isset($avail)){
echo '<p>'.$avail.' is available to be registered</p>'
} else {
echo '<p>'.$avail.' is taken register with us for price</p>'
}
Thanks
Joe
in jquery (http://jquery.com/) you can make ajax requests by using the function :
$.ajax(
{
url : "url to fetch",
success: function (data) {
// data is variable that is returned from server as HTML by default, or you can use JSON format
$("#content").html(data);
}
}
);
If you dont want to use jquery javascript library, you need to create xmlhttprequest object and make helper functions for it, which i do not recommend, since jquery can be used for more stuff than just ajax calls.
EDIT :
#comment
simply create process.php where you will accept "domain" as query string - which will check if the domain exists, if not it should echo <p>'$result.'is/isn't available</p>, than in $.ajax({...}); pass that url and "data" will be available to you.
To pass GET params with $.ajax() you can use the following setting:
$.ajax(
{
type: 'GET',
url : "url to fetch",
// here you pass js object in convention: { 'query_string' : 'its value' }
data : { 'domain' : $('#domain_name_input_field').val() },
success: function (data) {
// data is variable that is returned from server as HTML by default, or you can use JSON format
$("#content").html(data);
}
}
);

Categories