How to load a view inside a div using ajax in codeigniter - php

I want to load a view in another view using AJAX in CodeIgniter. I have written this code in the view.
<button class="btn btn-primary shadow" id='add_items'>Add Items</button>
<div class="row-fluid sortable shadow">
<div id="#show"></div>
</div>
$('#add_items').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "<?=base_url();?>Items/add_items",
type: 'get',
dataType: 'html',
success: function(output) {
$('#show').html(output);
}
});
});
This is the controller from which I want to load view inside the <div id="show">
public function add_items()
{
$this->show('admin/Items/index');
}

I think this example of my code with ur Object Oriented Programming skills can help u weel .
just create an xml file content a fiew of views u need, and tage everyone of them by an unic id .
this is a part of my xml file saved on the path :
{project folder}/src/CentralAppView.xml
<?xml version="1.0" encoding="UTF-8"?>
<root>
<view id="adduser"><!-- choose ur id as libel of ur view must be unic -->
<!-- u can edit/insert everything u need here -->
<fieldset>
<form ...>
....... Content View ....
</form>
</fieldset>
</view>
</root>`
Now
1) u have to create an XMLHttpRequest instance called for example "xmlserver " be like :
var xmlserver = new XMLHttpRequest();
2) When u create this Object instance , u ll must to define for it the abstract methode called :
onreadystatechange
because u need to make a contol for every server state you get it , in this point , you need to check if u get the needed reponse for doing your traitment to your text response using tow XMLHttpRequest object attributes are changing values every server states changing :
xmlserver.status and xmlserver.readyState ( you can change 'xmlserver' by 'this' if you have something ambiguse about ) .
nice , now , u must to know which values can have there attributes and what is the best server state make you ready to do what you need by your server response .
lets begin by the attribue 'status' :
status is a integer attribute and have a values been got from the server juts to indicate the server response tag , there values may be enter an interval that accorded to your server behavior and fonctionality , for your using server , it may be 100 .. 600 , every value have an indicator .
we have a very knew value example :
404 request was not found on this server , so , 'request was not found on this server' is the indicator/meaning accorded to the value 404 of the attribute ' status ' .
200 is the indicator/meaning accorded to a succed access and response .
Now , lets move to the readyState attribute :
readyState is also an integer attribute , its just have the count of ur states got from ur server , his interval is fixed between 0..4 , 0,1,2,3 means an faild network access to ur server and the value 4 is accorded to the access connecting .
i think is also related to the server connection ping count .
Now , if u got 200 states value and 4 readystates , u ll able to do ur traitment and make ur view insert using ur server text response , because it s the only response format using for all servers ( propably) .
See the code and i think u ll understand more :
xmlserver.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
// do ur response traitment and ur view insert here
}
}
After that , u need to specify which file or which php page u need to load from it ur view contient just by using the XMLHttpRequest Object instance methode 'Open' with passing the following args :
ur sending mode : Get/POST , get is used to get data from , and post used to send text data as an argment of the send method that we ll talk about it later .
.
ur file / content path : in ur situation it must be {project folder}/src/CentralAppView.xml or the same path u used it .
Attention : wrong path can or server shutdown state can return the unwanted values that we tolk about it ago .
and
ur synchronisation level : true/false .
the code ll be :
xmlserver.open("GET", "./src/Containts_Dialogs.xml", true);
finaly in the Ajax part
call the method send to begin transaction between the server and ur browser for getting ur need view from ths server .
xmlserver.send(); // arg is undefined because we used the GET sending mode in the open methode
finaly with DOM to insert ur view in ur Div element
Using predefined XMLDocument Object instance , his getElementById() methode and innerHtml attribute .
getting the DOM element wich have the id 'show' from the XMLDocument
Object instance called document and affect it in a new variable
called for example viewelm.
Updating the view by the new Content ajax response .
Now , we just return to ower 'onreadystatechange' and insert this traitment in the comment that i make it for u , to get the code :
var xmlserver = new XMLHttpRequest();
xmlserver.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
document.getElementById("show").innerHtml = xmlserver.responseText;
}
}
xmlserver.open("GET", "./src/Containts_Dialogs.xml", true)
xmlserver.send();
Warrning : delete # from your html div id attribute element , to run the code correctly .
Good programing mate :) .

In the controller, You load the html string of the view page you want to load as :
$output = array(
'result' => $this->load->view('admin/Items/index','',true)
);
You send the output as the response to the ajax request :
print(json_encode($output));
You receive the response clientside like :
success: function(output) {
$('#show').html(output.result);
}
After the comment from #Danish, I realized the ajax expects the response to be HTML, in this implementation the server responds with json data.
To be able to use this solution, you need to change the response type of the ajax call to Json.
$('#add_items').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "<?=base_url();?>Items/add_items",
type: 'get',
dataType: 'JSON',
success: function(output) {
$('#show').html(output.result);
}
});
});
Hope This works.

Related

Cannot extract default values for json object using ajax

I'm trying to use ajax to validate a simple form but i'm using 3 parts. front side.html, back side.php, and main javascript.js. I'm also using a pseudo server. the problem lies here.
$("#InsertDefault").click(function()
{ $.ajax("backend.php?act=default", { success: function(result){
console.log($.parseJSON(result))
data = $.parseJSON(result);
document.getElementById("name").value = data["name"]
},
error: document.getElementById("errors").innerHTML = "<li>It didn't work... </li>"
}); // ajax close
}); //click close
When i call ajax, i want to enter backend.php and also set the parameter "act" to default.
// Return JSON default data if requested
if ($_REQUEST['act'] == 'default'){
$defaultData = array('name' => "Jane", 'postal' => "L5B4G6", 'phone' => "9055751212",'address' => "135 Fennel Street");
echo json_encode($defaultData);
}
if this works, i have a success option to the ajax call that takes "result" (the default values as a string) and parse it to JSON making an object called data. When i take the name from data which should be "Jane" by default and put it in the value field for my text field
<input type="text" id="name" name="name"/>
It should populate it with the name Jane, but instead it fails and does my error option "It didn't work" Have a made a mistake or failed to add something?
Thing you are missing header('Content-type: application/json'); before the echo in php part. Currently ajax things it gets plain text instead of json response.
Fix your ajax:
$.ajax({
url:"backend.php?act=default",
success: function(result){
$("#name").val(result.name);
}});
use the header header('Content-type: application/json'); in backend.php
Use . to access anything from array in javascript,
co
change
document.getElementById("name").value = data["name"]// this is in php
to
var data = $.parseJSON(result);
alert(data.name)
document.getElementById("name").value = data.name
^
data.name;// for name,
data.postal;// for postal code
..// so on

Jquery $ajax POST data and get a response mysqli_insert_id

I am posting data to a PHP page using the $.ajax in Jquery. So far all this is working fine.
Here is how all this looks in my index.html.
function send() {
$( "#send" ).show( "slow" );
var page = Page;
var title = $("#title").text();
var title_2 = $("#title_2").val();
$.ajax({
url: "save.php",
method: "POST",
data: { MyPage : page, My_Title1 : title, My_Title2 : title_2 },
dataType: 'json',
success: function(data) {
alert(data);
var result = jQuery.parseJSON(data);
alert(result.last_id);
},
error: function(output) {
alert("not working whole process");
}
});
This to sum up what I am doing, is sending some data, Html and contents in div's, to a sql database.
What I would like to do now is that once this data is posted to the save.php file, I get a response from the php sending me the ID of the page I have saved all this in. So I am using mysqli_insert_id($con); to acheive this.
Set it it looks like this.
$last_id = mysqli_insert_id($con);
When I execute all this, the Post works fine and I end up with what I want.
{"last id":265} at the end of my post.
$data['last id'] = $last_id;
echo json_encode($data);
How do I get this value back to my index.html so that I can place it inside a input. The success is not working out.
//Reply to Steves answer
# Steve. Thank you for answering. Your answer is exactly what is happening. I am sending a whole bunch of html to my save.php file so it can save it to a sql table.
Something looking like this.
Write to MySQL OK!<br>INSERT INTO Project(ID_User,Name_Project,Page_Project,Date_Project) VALUES ( 110, '\"Project name here\"', '<div class=\"file_save_container\"> <------------- HERE THERE IS A WHOLE BUNCH OF HTML ------------> </div>\n\n\n', '2015-03-19 13:10:23');<br>
This is all saving properly to my sql table. What I would like to achieve here is that when the ajax is sent to my save.php I get a response sending me the id of the newly created Project so that I can then place the response "the id" inside a . Right now mysqli_insert_id is placing this at the end of my post.
<br>{"this_id":"311"}
This is what I would like to get back as a response to my index.html file and not have it at the end of my post.
Try to set header('Content-Type: application/json'); in save.php
Write $data['last_id'] instead of $data['last id'] to match your JS.

avoid reloading xml multiple times

i want to fetch country source and destination from XML files , it works perfectly in localhost but not in server , in server it shows different destination country if i move cursor fastly on map.
in jquerymap.php I am calling price_by_countries.php file on mouseover and mouseclick event and I am also passing 2 variables in price_by_countries.php and in this file i am loading XML document , I think by loading XMLfile each and every time may cause this problem .. I am new to programming and wants to sort it out this issue asap .. thanks
jquerymap.php file code
jQuery.ajax({ type: "POST",
url: "price_by_countries.php",
data: "s="+source+"&d="+destination,
dataType: 'HTML',
success: function (msg) {
jQuery("#rightinput").html(msg);
}
});
price_by_countries file code
$xml = simplexml_load_file("rd.xml") or die("Error: Cannot create object");
function processXML($node){
foreach($node->children() as $books ){
if($books['source'] == trim(ucfirst($_REQUEST['s'])) &&
$books['destination'] == trim(ucfirst($_REQUEST['d'])))
{
echo "<pre>";
//echo $books ;
echo 'Source Country from XML file = '.$books['source'] . ' ------ Source Country from Textbox = '. trim(ucfirst($_REQUEST['s'])) ;
echo '<hr>';
echo 'Destination Country from XML file = '.$books['destination'] . ' ------ Destination Country from Textbox = '. trim(ucfirst($_REQUEST['d'])) ;
exit();
}
}
}
processXML($xml);
website url : http://realwebit.com/jquerymap/jquerymap.php
The problem seems to be bound to the datarequests on onmouseover. If you move the cursor too fast onmouseover triggers many requests at the same time to the server ! That works on localhost because there is no delay, but not ! You should install firebug for firefox and take a look at the requests made to the server.
If you dont want to load the xml every time you need a cache:
Save the response of the price_by_countries.php on the client side in an array using source & destination as keys !
If someone clicks or hovers over a country don't call the jquery ajax function right away. Check the array first if you already requested the data and return it ! If not do the ajax request. If it's successfull store the data in the array !
Lucian

Combine JQuery/PHP to log clicks into database?

The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}
You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.
This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.
Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}
Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston"
success: function(data){
alert('done');
});

Update whole page on Ajax request

I have an AJAX request that can have two possible outcomes:
The server responds with a message which I should place in a <div>
The server responds with an HTML page, in this case I need to substitute current page with a new one and change the address (the client knows the address before a request).
What would be the solution if I have the AJAX request that needs to handle both of these cases?
url = "http://example.com"
ajax.request(callback)
function callback(response) {
if (case2(response)) {
history.pushState({}, "New page", url);
document.innerHTML = response
} else {
updateDiv(response)
}
}
I'm interested in a correct way to implement the first branch, or if the server can somehow compose a headers that will make browser to handle a response as a usual HTTP response and update a page location and content, something like redirect with given content.
I understand that the server can return a link instead of a page, but in this case one additional stage will be needed on a client - redirect and then populating the new page on the server.
Quite frankly, I think that approach is basically broken by design. You shouldn't have to make that decision at that place. For example, the ajax response could only signal that a whole new page should be loaded and the new content then be generated on a second (non-ajax) request to a new URL.
In case you're forced to take the way you already go, and provided the response content is not very large, you could try Javascript-URIs. Basically, an URI in the form of javascript:"string" will load a new page which that string is the source code for. So, if response already is a string, just assigning javascript:response to window.location.href should suffice. Maybe you have to do some escaping beforehand. And I don't know, how cross-browser-compatible this approach is.
load
is also possible.
A variant of this is building the URL not with the variable name, but with the actual string data. Like
function source2url(src) {
// make valid javascript string from source text
var esc1 = src
.replace(/\\/g, '\\\\')
.replace(/\'/g, '\\\'')
.replace(/\x0A/g, '\\x0A')
.replace(/\x0D/g, '\\x0D');
// make valid url from that
return "javascript:'" + encodeURIComponent(esc1) + "'";
}
window.location.href = source2url(response);
This will, of course, generate pretty large URIs. And you'll always have the Javascript-URI in the address bar.
UPDATE
A similar approach is to use base64 encoding in a data URI. The Wikipedia entry explains how it works, including a javascript example. However, you'd have to base64-encode the content somehow. (Note: You can use data URIs with or without the base64 encoding. You have to see what gives you shorter URIs for your specific content.)
I had a similar issue once. A full error page was returned instead of a simple HTML snippet. We eventually fixed this by changing the logic, but here is one of the solutions I found:
document.open();
document.write(responseText);
document.close();
The reason we abandoned this is that on IE there were some problems. I didn't loose any time to investigate why, but it threw an 'Access denied' exception when attempting to write the string. I think there were some <meta> tags that confused IE, or maybe conditional comments, I'm not sure. (It worked when I used some simple pages...)
Bottom line is: you shouldn't have to do this, but if there is nothing else you can do (like returning an url string) the code above might work.
It's really easy if the response is valid XML.
var new_doc = (new DOMParser).parseFromString(response, "application/xml");
document.replaceChild(document.adoptNode(new_doc.doctype), document.doctype);
document.replaceChild(document.adoptNode(new_doc.documentElement), document.documentElement);
Since the request is for an updated answer, here's my solution using HTML5's History API with jQuery. It should run easily by combining the PHP and HTML parts into one file.
My solution allows for AJAX to return the following:
A message through AJAX, which updates a <div> container.
A URL, which causes the browser to redirect to the URL
A complete HTML page, which calls the History API's history.pushState() to add the current URL to the browser's history and replaces the entire HTML on the page with the HTML returned from AJAX.
PHP
This is just a sample of what the PHP script will need to return when it is invoked via AJAX. It shows how to encode flags to determine whether the AJAX call should update the container or load a new page, and how to return its result via JSON through json_encode. For completeness, I named this script test.php.
<?php
// Random messages to return
$messages = array(
'Stack Overflow',
'Error Message',
'Testing'
);
// If the page was requested via AJAX
if( isset( $_POST['ajax']))
{
$response = array(
'redirect' => // Flag to redirect
( rand() % 2 == 0) ? true : false,
'load_html' => // Flag to load HTML or do URL redirect
( rand() % 2 == 0) ? true : false,
'html' => // Returned HTML
'<html><head><title>AJAX Loaded Title</title></head><body>It works!</body></html>',
'title' => 'History API previous title',
'message' => // Random message
$messages[ (rand() % count( $messages)) ]
);
echo json_encode( $response);
exit;
}
JS
Since I am using jQuery, lets start with that. The following submits an AJAX POST to the server, to the above PHP script at URL test.php. Note that it also sets the POST parameter ajax to be true, enabling the PHP script to detect that it received an AJAX request. The dataType field tells jQuery that the server's response will be in JSON, and that it should decode that JSON to a JSON object in the response callback. Finally, the success callback, which is fired when the AJAX response is successfully received, determines what to do based on the flags sent from the server.
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
// Output the HTML
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
HTML
Here is the complete HTML source of my tested file. I tested it in FF4 - FF8. Note that jQuery provides the ready method to prevent the JS from executing until the DOM is loaded. I've also used Google's hosting of jQuery, so you do not need to upload a copy of jQuery to your server to test this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<title>Default Page</title>
<script type="text/javascript"">
$( document).ready( function() {
$('#ajax_link').click( function() {
var redirect_url = "/test.php";
$.ajax({
type: 'POST',
url: "/test.php",
data: {ajax : true},
dataType: "json",
success: function( json) {
if( json.redirect) {
if( json.load_html) {
// If the History API is available
if( !(typeof history.pushState === 'undefined')) {
history.pushState(
{ url: redirect_url, title: document.title},
document.title, // Can also use json.title to set previous page title on server
redirect_url
);
}
document.open();
document.write( json.html);
document.close();
}
else {
window.location = redirect_url;
}
}
else {
$('#message').html( json.message);
}
},
});
})
});
</script>
</head>
<body>
<div id="message">The default contents of the message</div>
<a id="ajax_link" href="#">Fire AJAX</a>
</body>
</html>
Give an id to body <body id="page"> and your other div will be <div id="message"></div> now your ajax will look like
$.ajax({
url:'myAjax.php',
data:{datakey:datavalue},
dataType:"JSON",
success: function (response) {
if(response.message=="your message")
{
$('#message').html(response.content);
}
else
{
$('#page').html(response.content);
}
}
});
as T-Bull say... the whole process is wrong here....
you simply are over-complicating things and you know that infact:
I understand that the server can return a link instead of a page, but
in this case one additional stage will be needed on a client -
redirect and then populating the new page on the server.
stop complicating and start do it well...
Client open the page first time, so, track it $_SESSION['tmp_client_id'] = 'client_'.session_id(); obviously is better if the client is already subscribed, anyway, put stuff in temp table OR into another session var etc...
Client fill in the form;
Client submit the form;
Make the AJAX request;
Store $_POST variable inside tmp_client_tbl with it's unique tmp_client_id OR just $_SESSION['client_'.session_id()] = json_encode($_POST);
Outcome #1 ? display message in a </div>
Outcome #2 ? refresh page and check if( isset($_SESSION['client_'.session_id()])) { if so let's display the form again with filled fields: } else { display empty form;
SELECT * FROM tmp_client_tbl WHERE tmp_client_id = '{$_SESSION['tmp_client_id']}' OR json_decode($_SESSION['client_'.session_id()]);
$form_data = $mysql_rows; OR $json_array;
foreach($form_data as $name => $value) { echo "<input name='$name' value='$value' />" } in a ninja way that assume you have such kind of form builder array where $form = array('text' => array('name','lastname'), 'select' => array('countries'), ... ), OR simply by <input name='lastname' value='{$lastname}' /> where the fields values are pre-polutated with empty vars;
time elapsed, error occurred, browser closed? session_destroy(); or unset($_SESSION['client_'.session_id()]);

Categories