Load PHP page in div when I click link - php

I'm trying to figure out how to load a seperate php page into a div when I click on a div button.
Ie: #div1 opens up #display with one.php within, #div2 opens up #display with two.php, etc..
Any suggestions?

You could use AJAX For this:
$('#div1').on("click",function(){
var url= "page1.php"; //insert your URL
$.ajax({
url: url,
success: function(data){
$('#div1').html(data); //copy and paste for your special case
}
});
});
Documentation:
http://api.jquery.com/jQuery.ajax/

There are several ways. By "load PHP page in div", I will suppose you mean "load the output of a PHP page in div".
The simplest way, if you really just want to load some HTML response (without the need of generating a POST request), is to use jQuery's load function.
$(document).ready(function () {
$('#div1').click(function() {
$('#display').load('one.php');
});
$('#div2').click(function() {
$('#display').load('two.php');
})
$('#div3').click(function() {
$('#display').load('three.php');
})
});

try like below
$('#div1').click(function(){
$('#display').load('one.php', function() {
alert('Load was performed.');
});
});
$('#div2').click(function(){
$('#display').load('two.php', function() {
alert('Load was performed.');
});
});

Use ajax for this: http://api.jquery.com/jQuery.ajax/ , or load: http://api.jquery.com/load/

Use jquery's load method to load content on click event.
http://api.jquery.com/load/

Use Ajax for that:
$.post("GetData.jsp",
{ name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
}
);

Related

Get Ajax content and filter it

i have this script that does ajax using jquery but i want to update with specific content, when I did it return undefined..
<script type="text/javascript">
$(document).ready(function(e) {
$.ajax({
url:'n.php',
cache:false,
type:"GET",
success: function(data){
$('.list-ball').html($(data).find(".count").html());
console.log($(data).find(".count").html());
}
});
});
</script>
Start with console.log(data);
This way you can see the returned data.
From there you can populate an element like so:
$("#myElement").html(data);
You can use $(selector).load() function that will replace content:
$(document).ready(function() {
// [url] [any valid css selector]
$('.list-ball').load('n.php .count > *'); // Find `.count` content and place it instead of `.list-ball` content
});
If .list-ball element is not presented in DOM, than no ajax will be executed.

Using $.post with CodeIgniter URL issue

I have one page in CodeIgniter with URL http://127.0.0.1/FOLDER/data/getList.
On that page, there is list of enteries. On that list, in every item there is a link on which by clicking I need to fetch some data using $.post jQuery.
I have used this code:
$(".class_name").click(function() {
$val = $(this).attr('val')
$.post("class/func", {val:$val}, function(data) {
alert(data);
});
});
The issue is with the URL to be used with $.post.
If I use, "/class/func", it sends the requsts to http://127.0.0.1/class/func (FOLDER is not getting in).
If I use, "class/func", it sends the request to
http://127.0.0.1/FOLDER/data/class/func (here data gets inserted which is class for the current page).
How should I resolve this error? Should I be using <?php echo base_url() ?>class/func; is it the correct way of doing it?
If your JavaScript code is between <script></script> in your view:
$.post("<?php echo site_url("class/func") ?>", {val:$val}, function(data) {
alert(data);
});
If your JavaScript is on a separate .js file:
In the footer of your page:
<script>var baseUrl = "<?php echo base_url() ?>";</script>
And then:
$.post(baseUrl + "index.php/class/func", {val:$val}, function(data) {
alert(data);
});
Alternative :
Set a data-attribute to your item
Go!
And then:
$.post($(this).data("ajaxurl"), {val:$val}, function(data) {
alert(data);
});
I had a separate js file from where I had to call the function in a controller "Verifypass.php". I had something like this in the $_post():
$.post( "verifypass", { pass: $("#password").val() }, function(data){
});
This did not work for me, So all I did was to add index.php at the beginning of the controller name as:
$.post( "index.php/verifypass", { pass: $("#password").val() }, function(data){
});
And it worked then.

Get div content with jQuery for PHP

UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.

Jquery function not loading after refreshing div using Ajax

I have a several divs that a refreshed using Ajax after the user clicks on a link on the page.
Here's my code for the Ajax refresh div:
<script type="text/javascript"><!-- AJAX CALL FOR MY PICTURES -->
$(document).ready(function() {
$('#pictures_wrapper a.delete_image').live('click', function(e){
$('#pictures_wrapper').load( $(this).attr('href') + ' #pictures_wrapper' );
e.preventDefault();
});
});
</script>
On this same page, I am loading this Jquery effect:
<script type="text/javascript"><!-- HOVER OVER ITEMS CHANGE BG COLOR -->
$(document).ready(function() {
$(".item_control_box").hide();
jQuery('.each_item_container').hover(function() {
jQuery(this).find('.item_control_box').show()
}, function() {
jQuery(this).find('.item_control_box').hide();
});
});
</script>
My issue is that when the user click on the link to refresh the Divs, this jquery effect breaks and no longer works. I'm thinking that I have to "reload" this function some how since only the div is being reloaded and not the whole page. How can I keep this Jquery function working after refreshing a div?
You should use the callback function of the load, means u recall the jquery after loading has completed.
$('#pictures_wrapper').load( $(this).attr('href') + ' #pictures_wrapper', , function () { //hover effect function } );
Hope this help :)
Your code should work if you change your .bind() calls to .live():
jQuery('.each_item_container').live('mouseenter', function() {
jQuery(this).find('.item_control_box').show()
}).live('mouseleave', function() {
jQuery(this).find('.item_control_box').hide();
});
.hover() is the same thing as using .bind('mouseover', function () {...}) and .bind('mouseout', function () {...})
When you want to bind event handlers to elements not yet in the DOM you can use .live() or .delegate(): http://api.jquery.com/live/, http://api.jquery.com/delegate/
Attach an event handler for all elements which match the current
selector, now and in the future.
As of jQuery 1.7 you should be using .on() as .bind(), .live(), and .delegate() are depreciated: http://api.jquery.com/on/
Better put the code in a custom function with a name
function effectLoad(){
$(".item_control_box").hide();
jQuery('.each_item_container').hover(function() {
jQuery(this).find('.item_control_box').show()
}, function() {
jQuery(this).find('.item_control_box').hide();
});
}
then put the function in your ajax success function
$.ajax({
url: 'your_php_file.php',
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
effectLoad();
}
});
Hope it will work.
Thanks
as #Guillaume Cisco mentioned in the comments you have to rebind the hover effect to dynamically inserted elements in the DOM, you can do it like
$(".item_control_box").live(
{
mouseenter:function(){
jQuery(this).find('.item_control_box').show();
},
mouseleave:function(){
jQuery(this).find('.item_control_box').hide();
}
});

How to request page content by clicking a div with jQuery mobile?

I am trying to fetch data form a callback page (php) and load it into a html div with jQuery mobile. This should happen if a user clicks on another div.
What I actually got is
$.('#home-button').bind('vclick', function( e ) {
$.get('homeCallback.php',function(data){
$('#displayContent').append(data).trigger('create');
},'html');
});
Where #home-button is the div that should trigger the event and #displayContent the div where the content should be put in.
The request should be able to pass some parameters, too. Like homeCallback.php?param=1 but it could also use the post method.
The callback does not have to be html only, it could also be possible that the callback php script provides JSON data or anything.
I am not a JS crack so I have problems solving this issue. Thanks for your help!
Edit:
So I found a solution on my own:
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajaxLoader = '<img src="images/ajax-loader.gif" alt="loading.." />';
var loadUrl = "homeCallback.php";
$('#home-button1').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option1',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
$('#home-button2').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option2',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
});
And this is what homeCallback.php simply does..
<?php
if( isset($_GET["option1"] ))
echo "option1";
if( isset($_GET["option2"] ))
echo "option2";
So far.
$.('#home-button').bind('click', function() {
$.ajax({
url: "homeCallback.php",
type: "POST",
data: ({param: 1, param2: 2}),
success: function(html){
$("#displayContent").html(html);
}
});
});

Categories