Get Ajax content and filter it - php

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.

Related

load partial page using AJAX in PHP page

I'm trying to figure out how I can load a partial page (div) into another div using AJAX in my php page.
basically I have a div with some php output stuff, and I need to put that div's content into another one using ajax but my code doesn't do anything (it doesn't put the div's content into the other one).
this is my current code:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
$("#issomeone").html($(response).find("#notis"));
setTimeout(load, 4000);
}
});
}
load();
});
</script>
so the #notis div holds the php output and the #issomeone div is the div that i need to put the stuff in using ajax.
is there something missing in my code or I'm just doing it all wrong?
any help would be appreciated.
Thanks
EDIT:
THIS DOESN'T DO ANYTHING:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
//$("#issomeone").html($(response).find("#notis"));
$('#issomeone').load("<?php echo $actual_link; ?> #notis");
setTimeout(load, 4000);
}
});
}
load();
});
</script>
You are finding the DOM element and then trying to set that as target element's innerHTML with html(). You in essence have a type mismatch.
You would need to get the innnerHTML of #notis to pass as the parameter to this function so:
$("#issomeone").html($(response).find("#notis").html());
Alternately, you could append the node if you want to keep the whole #notis element
$("#issomeone").append($(response).find("#notis"));
But really, since you are using a straight GET, you might be better off simply doing:
$('#issomeone').load('<?php echo $actual_link; ?> #notis');
This provides a more simple abstraction to what you are trying to do more manually with .ajax()
I would however encourage you to not get in the habit of loading full HTML pages and then scraping them for some particular element. It is better design architecture to have the AJAX target script serve up only content that is needed when possible.

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.

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

PHP jQuery ajax request is not responding

This jQuery ajax request is not working. The form submit just reloads the page, there are no alerts, nothing. Where am I going wrong?
$("#newfolder").submit(function() {
alert("1")
$.ajax({
type : "POST",
url : "<?php echo $cfg->wwwroot ?>/pages/media/async/newfolder.php",
data : $(this).serializeArray(),
success: function(data) {
alert(data)
//$.fancybox(data);
}
});
return false;
});
This can have several causes.
Ensure that you've included jQuery as one of first <script>s in HTML <head>.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Ensure that you're calling this function when the document is ready loading.
<script>
$(document).ready(function() {
// Here.
});
</script>
Ensure that the element with id="newFolder" is present in HTML DOM tree and supports the submit event.
<form id="newFolder">

How load a PHP page in the same window in jQuery

I have a PHP file, Test.php, and it has two functions:
<?php
echo displayInfo();
echo displayDetails();
?>
JavaScript:
<html>
...
<script type="text/javascript">
$.ajax({
type:'POST',
url: 'display.php',
data:'id='+id ,
success: function(data){
$("#response").html(data);
}
});
</script>
...
<div id="response">
</div>
</html>
It returns the response from jQuery. The response shows as <a href=Another.php?>Link</a>. When I click the Another.php link in test.php, it loads in another window. But I need it to load the same <div> </div> area without changing the content of test.php, since it has displayInfo(), displayDetails(). Or is it possible to load a PHP page inside <div> </div> elements?
How can I tackle this problem?
If I understand correctly, you'd like for the a link to cancel navigation, but fire the AJAX function?
In that case:
$("#mylink").click(function() {
$.ajax({ type: "POST", url: "another.php", data: {id: "somedata"}, function(data) {
$("#response").html(data);
});
return false;
});
Krof is correct,
One possible unwanted behavior of this however is that it will query the data every time the link is clicked. You can set the event to only call the ajax query once by using one.
$("#mylink").one('click', function() {
// ajax call
return false;
});
Don't forget to set href="javascript:{}" in your link so after the event is fired once the link wont do anything;
You could just use MooTools and class Request.HTML.

Categories