Codeigniter AJAX Example - php

I've been looking for a week now for a decent full working example of how to use AJAX with Codeigniter (I'm an AJAX novice). The posts / tuts I've seen are old - all the programming languages have moved on.
I want to have an input form on a page which returns something to the page (e.g. a variable, database query result or html formatted string) without needing to refresh the page. In this simple example is a page with an input field, which inserts the user input into a database. I'd like to load a different view once the input is submitted. If I could understand how to do this I'd be able to adapt it to do whatever I needed (and hopefully it would help others too!)
I have this in my 'test' controller:
function add(){
$name = $this->input->post('name');
if( $name ) {
$this->test_model->put( $name );
}
}
function ajax() {
$this->view_data["page_title"] = "Ajax Test";
$this->view_data["page_heading"] = "Ajax Test";
$data['names'] = $this->test_model->get(); //gets a list of names
if ( $this->input->is_ajax_request() ) {
$this->load->view('test/names_list', $data);
} else {
$this->load->view('test/default', $data);
}
}
Here is my view, named 'ajax' (so I access this through the URL www.mysite.com/test/ajax)
<script type="text/javascript">
jQuery( document ).ready( function() {
jQuery('#submit').click( function( e ) {
e.preventDefault();
var msg = jQuery('#name').val();
jQuery.post("
<?php echo base_url(); ?>
test/add", {name: msg}, function( r ) {
console.log(r);
});
});
});
</script>
<?php echo form_open("test/add"); ?>
<input type="text" name="name" id="name">
<input type="submit" value="submit" name="submit" id="submit">
<?php echo form_close(); ?>
All that happens currently is that I type in an input, updates the database and displays the view "test/default" (it doesn't refresh the page, but doesn't display "test/names_list" as desired. Many thanks in advance for any help, and for putting me out of my misery!

Set unique id to the form:
echo form_open('test/add', array('id'=>'testajax'));
I assume that you want replace a form with a view:
jQuery(document).ready(function(){
var $=jQuery;
$('#testajax').submit(function(e){
var $this=$(this);
var msg = $this.find('#name').val();
$.post($this.attr('action'), {name: msg}, function(data) {
$this.replace($(data));
});
return false;
});
better way if you return url of view in json response:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$this.load(data.url);
},"json");
from your last comment - I strongly not suggest to replace body, it will be very hard to support such code.
but here is anser:
$.post("<?php echo base_url(); ?>test/add", {name: msg}, function(data) {
$('body').replace(data);
});

Related

How do you pull a php variable into a js object's property via jQuery AJAX?

I want the user to type an answer ('zebra') in the input area. If they get it correct, then they are alerted that it is correct.
This answer will be pulled from a database eventually. For this simple example, I'm just pulling it into the object from another php file via jQuery AJAX.
It seems to pull in the php variable okay, but it still says 'incorrect answer' in the example I'm doing here =
https://michael-r-oneill.ie/development/random/Testing/testing.php
https://michael-r-oneill.ie/development/random/Testing/collectDataTesting.php
Below is the html / php file
<!-- head -->
<head>
<!-- jQuery library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js">
</script>
<title>Testing</title>
</head>
<script>
var AnswerSubmitted;
var quizes;
function quizesFunction(animal)
{quizes = [{bigPicture: animal},{bigPicture: 'tokyo'}]}
$(function() {
$.ajax({type: "POST",
url: 'collectDataTesting.php',
data: {},
dataType: "text",
success: function(data) {
quizesFunction(data);
}
});
$(document).on('click', '.submit', function() {
AnswerSubmitted = $('#typedAnswer').val();
if (AnswerSubmitted == quizes[0].bigPicture)
{
$('.test').html('correct answer').css("color", "green");;
$('.AnswerSubmitted')
.html('Answer submitted is ' + AnswerSubmitted);
$('.objectProperty')
.html('Object property is now ' + quizes[0].bigPicture);
}
else
{
$('.test').html('incorrect answer').css("color", "red");
$('.AnswerSubmitted')
.html('Answer submitted is ' + AnswerSubmitted);
$('.objectProperty')
.html('Object property is now ' + quizes[0].bigPicture);
}
});
});
</script>
<p class="objectProperty"></p>
<p class="AnswerSubmitted"></p>
<p class="test"></p>
<input type="text" id="typedAnswer" />
<button class="submit" id='AS'>enter</button>
Below is the 'collectDataTesting.php' php file I'm going to to collect the data
<?php
echo 'zebra';
?>
If I am reading this right, then it looks like the data passed to quizesFunction(data) when the ajax request is completed is not of the type that you expect.
Remember that if you don't provide the dataType setting to $.ajax (which you don't), jQuery will try to "guess" the type for you (https://api.jquery.com/jQuery.ajax/).
You can either set the dataType to text or simply follow the advice given by the other members and have PHP return JSON (which jQuery will interpet as a JavaScript object).
So as recommended by a contributor above, I managed to begin solving this issue by replying back to AJAX with JSON.
Here are the updated testing pages =
https://michael-r-oneill.ie/development/random/Testing/testing3.php
https://michael-r-oneill.ie/development/random/Testing/collectDataTesting3.php
and code below =
html =
<p class="AnswerSubmitted"></p>
<p>Type 'dog' in the input area and hit enter</p>
<input type="text" id="typedAnswer" />
<button class="submit" id='AS'>Enter</button>
js =
var AnswerSubmitted;
var AnswerCollected;
var quizes = [{bigPictureAnsw: 'answer here', bigPHint : 'hint here'},
{bigPictureAnsw: 'answer here', bigPHint : 'hint here'}]
$(function() {
$.ajax({
type: 'GET',
url: 'collectDataTesting3.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
var x = 0;
$.each(data, function(index, element) {
quizes[x].bigPicture = element.answer;
quizes[x].bigPHint = element.hint;
x++;
});
}
});
$(document).on('click', '.submit', function() {
AnswerSubmitted = $('#typedAnswer').val();
if (AnswerSubmitted == quizes[0].bigPicture)
{
$('.AnswerSubmitted').html('correct answer');
}
else
{
$('.AnswerSubmitted').html('not correct');
}
});
});
external page ('collectDataTesting3') =
[ { "answer" : "dog", "hint" : "not a cat" },
{ "answer" : "dublin", "hint" : "capital city" }]

Search data from dynamically created table

I have created one application in that there is one text box for searching information from table. Although i have written the code when we enter the character in search text box, after accepting one character control goes out of textbox.
this is my code for searching`
<script type="text/javascript">
$(document).ready(function()
{
var minlength = 1;
$("#searchTerm").keyup(function () {
value = $(this).val();
if (value.length > minlength )
{
searchTable(value);
}
else if(value.length < minlength)
{
searchTable("");
}
});
});
function searchTable(value)
{
$.ajax({
type: "GET",
url: "dispatient.php",
data:({search_keyword: value}),
success: function(success)
{
window.location.href = "dispatient.php?search_keyword="+value;
$("#searchTerm").focus();
},
error: function()
{
alert("Error occured.please try again");
},
complete: function(complete)
{
$("#searchTerm").focus();
},
});
}
<input id="searchTerm" Type="text" class="search_box" placeholder="Search"
value = <?php echo $_GET['search_keyword'] ?> >
`
Please suggest to me..
thanks in advance..
value is default attribute of javascript try to change the variable name of value into something like searchData
In your success callback, you are redirecting the page to dispatient.php. I believe, this is the same page that has the search functionality. Once you redirect, the page is reloaded again and there is no point in writing:
$("#searchTerm").focus();
Since, you are already using AJAX, try loading the data from success on to your page through JavaScript/jQuery without reloading the page.
create one div and load your data in that instead of reloading entire page.
try something like this instead of ajax Call
<div id="searchResult"></div>
$("#searchResult").load("search.php?search_keyword=value",function(){
//your callback
});

Show DIV with AJAX in PHP After Saving Data to Mysql

I Have a problem here. I try to show up the information box using DIV after successfully save the data to mysql.
Here my short code.
// Mysql insertion process
if($result){?>
<script type="text/javascript">
$(function() {
$.ajax({
$('#info').fadeIn(1000).delay(5000).fadeOut(1000)
$('#infomsg').html('Success.')
});
}
</script>
<?php }
How can DIV appear? I tried but nothing comes up. Any help? Thank you
a basic jQuery ajax request:
$(function() {
$.ajax({
url: "the url you want to send your request to",
success: function() {
//something you want to do upon success
}
});
}
lets say you have a session of ID and you want to retrieve it in your database.
here is: info.php
<input type="hidden" name="id"><input>
<input type="submit" onclick="showResult(id)" value="Click to Show Result"></input>
function showResult(id){
$j.ajax(
method:"POST",
url:"example.php",
data: {userid:id},
sucess: function(success){
$('#infomsg').html(Success)
});
}
<div id= "infomsg"></div>
example.php
$id = $_POST['userid']; ///////from the data:{userid :id}
//////////config of your db
$sql = mysql_query("select * from users where id = $id");
foreach ($sql as $sq){
echo $sq['id']."<br>";
}
the "infomsg" will get the result from the function success and put it in the div.

AJAX post function not working properly after first call to the function

I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

Categories