How to insert into database using AJAX, PHP and CodeIgniter? - php

Please tell me how to use AJAX with CodeIgniter. I wrote the view like this but I am not sure how to send data to model with the controller.
My view is:
<html>
<head>
<script>
function insert(fname,lname,age)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_db_php.php?fname=fname&lname=lname&age=age",true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<table>
<tr><td>First Name : </td><td> <input type="text" fname="fname"/> </td> </tr>
<tr><td>Last Name : </td><td> <input type="text" fname="lname"/> </td> </tr>
<tr><td>City : </td><td> <input type="text" fname="age"/> </td> </tr>
<input type="button" onclick="insert(fname,lname,age)">
</table>
</form>
</body>
</html>
Please help me with writing the controller and model for this case.

This is the idea:
Better use post for submitting forms using ajax:
xmlhttp.open("POST","user_ajax",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname="+fname+"&lname="+lname+"&city="+city);
Model
class user extends CI_Model{
function insert(){
$data = array(
"fname" => $this->input->post('fname'),
"lname" => $this->input->post('lname'),
"city" => $this->input->post('city')
);
return $this->db->insert("TABLE_NAME",$data);
}
}
Controller
class user_ajax extends CI_Controller{
function index(){
$this->load->model("user");
if(isset($_POST['fname'])){
$ths->user->insert();
}
}
}

Related

Enable and disable button without page load

I have a form with a dropdown box, login button, and logout button. My requirement is to insert date and time when user click on the login or logout button after username selection from dropdown. Also, when user clicks on login button, it has to enable by changing the background color without page load. Same functionality required for logout option also.
Now, I can select the user's name from the dropdown which is coming from database. I stucked on the insertion part which i need without page load.
I need to insert data without page load once click on the login button.
Any help would be appreciable. Thanks in advance.
Code:
index.php
<?php
include_once "database.php";
?>
<html>
<head>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$sql_user="SELECT * FROM users";
$result_user=mysql_query($sql_user);
?>
<form>
<select name="users" onchange="showUser(this.value)" style="width: 210px;height: 36px; font-size:17px;">
<option style="height:30px;" value="">Select a person:</option>
<?php while($row_user=mysql_fetch_array($result_user)){?><option style="height:30px;" value="<?php echo $row_user['id'];?>"><?php echo $row_user['username'];?></option><?php }?>
</select>
</form>
<br>
<div id="txtHint"></div>
</body>
</html>
getuser.php
<style>
button{
width: 100px;
height: 38px;
background:white;
color:black;
}
</style>
<?php
$q = intval($_GET['q']);
include_once "database.php";
$sql="SELECT * FROM users WHERE id = '$q'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result);
$entry=$row['entry'];
?>
<form method="post" name="">
<table>
<tr><td>
<button id="btnSave" <?php if($entry=='0'){?> style=" background:#6DAAD4;"<?php }?>> Login</button>
</td><td>
<button <?php if($entry=='1'){?> style=" background:#6DAAD4;"<?php }?>> Logout</button>
</td></tr>
</table>
</form>
in you getuser.php remove form tag and add function 'insertDateTime()' to buttons click event like:
<table>
<tr>
<td>
<button id="btnSave" onclick="insertDateTime(this,'<?php echo $q;?>');"> Login</button>
</td>
<td>
<button id="btnSave" onclick="insertDateTime(this,'<?php echo $q;?>')"> Logout</button>
</td>
</tr>
</table>
Add one function to your index.php
<script src="http://code.jquery.com/jquery-1.11.1.min.js"> </script> //better to download and us locally
<script>
function insertDateTime(obj, id)
{
$("[id^='"+obj.id+"']").css('background', '#FFFFFF');
$(obj).css('background', '#6DAAD4');
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "id="+id;
xmlhttp.open("POST","insertdate.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//alert(xmlhttp.responseText);
}
}
xmlhttp.send(params);
}
</script>
and write your code in insertdate.php to insert date and time in database. You can get your id using $_POST['id']; in insertdate.php.
Bind onclick = "func()" in button
inside func method, change the color this way :
document.getElementById("formID").style.backgroundColor="lightblue";

PHP Ajax with a form

I have a form that let user to choose where them come from..
I have list out the country list by select box..
and i success to do it onchange and use ajax to read out all the state list..
actually i have two php file.. one is the main one that contain all the code include the form.. another one is generate state list.. my ajax code and form are in the main php
this is the one that generate state list...
$cID = $_GET["country"];
$sql = "SELECT * FROM States WHERE CountryID=$cID";
$result = $db->get_results($sql);
if (isset($result)) {
foreach ( $result as $states ) {
?>
<input type="checkbox" name="chkState[]" value="<?=$states->StateID?>" /> <?=$states->StateName?><br />
<?php
}
}
this is part of my code that read out..
but my problem is...
where i submit the form..
i only get the variable of country.. i cannot take the data of state that use ajax to generate out...
sample of my form
<form action="" name="place">
<select name="cboCountry" class="drop" onchange="showState(this.value)">
//some php code the list out the country
</select>
<div id="txtHint">
</div>
<input type="submit" name="submit" value="submit" />
</form>
and here my ajax code
<script>
function showState(str)
{
alert('xxx');
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","state_list.php?country="+str,true);
xmlhttp.send();
}
</script>
so when i submit the from with a save button... i only get the date of country and state are missing.. any body can help me? or having any way to do what i want?

Script Not Being Reached After onChange fired

HTML code :
<form>
<tr><td align="center">
<p><select size="1" id="breed_list" name="D1" onChange="editBreed(this.value);">
<option>Select Cattle Breed</option>
<?php while(list($id, $breed)=mysql_fetch_row($result1)) {
echo "
<option value=\"".$id."\">".$breed."</option>";
} ?>
</select></p>
</td></tr>
</form>
Javascript code :
<script type="text/javascript">
function editBreed(str){
alert("Made it to Edit Breed"+ str);
if (str=="" || str=="Select Cattle Breed") {
document.getElementById("animal_data").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("animal_data").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","editbreed.php?d="+str+,true);
xmlhttp.send();
}
</script>
If I modify the select to read onChange="alert(this.value);">, it displays the correct record, for some reason though it's not going to the function and showing me the alert that's there.
Thanks
On the second to last line in your function, there is a syntax error that is causing the function not to run at all.
xmlhttp.open("GET","editbreed.php?d="+str+,true);
remove the + after str
xmlhttp.open("GET","editbreed.php?d="+str,true);

Modification For AJAX Instant Search

I have build an instant search with AJAX using this tutorial, I am getting instant result but the problem is the div in which result comes stays open there.
I want to modify it like after getting instant result, then
when clicked anywhere on page the result(div) should disappear.
and when mouse-over again on input field result(div) should reappear.
AJAX Code
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
{
document.getElementById("search-result").innerHTML="";
document.getElementById("search-result").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("search-result").innerHTML=xmlhttp.responseText;
document.getElementById("search-result").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","instant-search.php?keyword="+str,true);
xmlhttp.send();
}
</script>
HTML Code
<div id="search">
<form action="" method="get" id="search-form" >
<input name="" type="" size="" id="search-input" onkeydown="showResult(this.value)"/>
<select name="" id="search-select">
<option value="all" >All</option>
<input type="hidden" name="" value="" />
</select>
<input type="submit" value="Search" id="search-btn" />
</form>
</div>
<div id="search-result"></div>
PHP Codes are simple MySQL Full Text Search query.
I tried like adding this but nothing happens
<input name="keyword" type="text" size="50" id="search-input" onkeydown="showResult(this.value)" onclick="(this.value==this.defaultValue) this.value='';" onmouseout="showResult(this.value='';)"/>
Please suggest any way of doing this.
Thanks.
A nasty way
<body>
<div id="main" onclick="fx(0)">
<div id="search">
<form action="" method="get" id="search-form" >
<input name="" type="" size="" id="search-input" onkeydown="showResult(this.value)"/>
<select name="" id="search-select">
<option value="all" >All</option>
<input type="hidden" name="" value="" />
</select>
<input type="submit" value="Search" id="search-btn" />
</form>
</div>
<div id="search-result" onclick="fx(1)"></div>
</div>
</body>
<script>
function fx(var flag)
{
// document.getElementById(theIdYouWantToShowHide).style.display="none" or inline or block ...
}
</script>
Got it finally, hope this helps others too.
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
{
document.getElementById("search-result").innerHTML="";
document.getElementById("search-result").style.border="0px";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("search-result").innerHTML=xmlhttp.responseText;
document.getElementById("search-result").style.border="1px solid #A5ACB2";
document.getElementById("search-result").style.display="block";
document.getElementById("search-input").onmouseover = function(){show_box()};
}
}
xmlhttp.open("GET","instant-search.php?keyword="+str,true);
xmlhttp.send();
}
function close_box(){
document.getElementById("search-result").style.display="none";
}
function show_box(){
document.getElementById("search-result").style.display="block";
}
document.onclick = function(){close_box()};
</script>

How to integrate RESTful webservice with php and ajax

I have a profile create page like this.
<html>
<head>
<script>
function validateMe(){
var xmlhttp;
var userEmail = document.getElementById("email").value;
var userPwd = document.getElementById("pwd").value;
//alert(userEmail);
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
}
document.getElementById("responds").innerHTML=xmlhttp.responseText;
}
xmlhttp.open("POST","api.php?email="+userEmail+"&pwd="+userPwd,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table>
<tr><td colspan="2">Login</td></tr>
<tr><td>Username:</td><td><input type="text" name="email" id="email"/></td></tr>
<tr><td>Password:</td><td><input type="text" name="pwd" id="pwd"/></td></tr>
<tr><td><input type="button" value="Submit" name="submit" onclick="validateMe();"/><td></td></tr>
</table>
<div id="responds"></div>
</form>
</body>
</html>
I need to use the RESTful web service with php and ajax to insert these data into my MySql database.
How can I implement this. Can anyone help me out to do this.
First, I suggest you to use the jQuery Javascript framework. With it, it made dead simple to make AJAX requests and getting the input values (without worrying of the web browser, etc).
Second, I don't see any RESTful web service here. It's a simple POST form.
So please, details your question :)

Categories