Loading content AJAX Jquery - Need to send data to loaded page how? - javascript

I have some content on my page that I require to be loaded via ajax. The page that I want to load is requesting some php variables I have stored on the main page.
How can I send these variables to the page then load the page via ajax?
Code so far:
$('#microblogposts').load('posts.php', {postmessage: "+ postmessage +"& from_user: "+ from_user +"& from_username: "+ from_username });
Is there a better more efficient way to do this?

// Main Page say main.php
<?php
$postmessage = "msg";
$from_user = "ayaz"
?>
<script>
var pm = <?php echo $postmessage; ?>
var fu = <?php echo $from_user; ?>
$(function(){
$.post("posts.php",{postmessage: pm, from_user: fu}, function(data){
$('#microblogposts').html(data):
});
});
</script>
This code might give you idea to implement in your scenario.

Related

Get Json_encode to a different jQuery page

I am working on a little project to learn more about JSON, but I am kinda stuck. I did a PHP query to get content from my database and I want to pass that data to a different jQuery page with JSON (optional).
Here is my process.php file:
<div id="msg" class="msg">
<?php
$query = "SELECT id, d_prijs, code, artikelNL FROM artikel";
$json = array();
$result= $conn->query($query);
while($row = $result->fetch_assoc()){
$json[]= $row;
}
echo json_encode($json);
?>
</div>
This echo works fine and it gives a result, but I want to pass that result to another page and show it on that page.
Here is my jQuery file:
<script>
$(document).ready(function(){
$("button").click(function(){
var mycontent = $('div.msg').text();
console.log(mycontent);
});
});
</script>
But this doesn't seem to work, it doesn't give an error either. Any ideas on how I can improve?
You need to make AJAX call to the process.php page. Try the following code:
`<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax( {
type : 'GET',
url:'process.php',
success:function(mycontent) {
console.log(mycontent);
}
});
});
});
</script>`
If you have a single page application and when you say page you mean hidden/displayed content, your code should work. But if you have actual pages, this will never work because your source div does not exist in the DOM once you have switched pages

Get a page's source with PHP, manipulate with JavaScript

JavaScript cannot get an arbitrary page's source code, last I knew. But PHP can pretty easliy.
//get page source code with php
<?php
url = 'http://www.thesaurus.com/browse/strong?s=t';
$src = file_get_contents($url);
?>
PHP is not good at manipulating the DOM, but jQuery is great for that!
I would like to do something like
//manipulate source code with javascript
<script>
html = '"' + <?php echo $src;?> + '"';
listItems = $(html + " li");
printLists = '';
$.each(listItems, function(ind, el) {
printLists += el.innerHTML + "<br/>";
});
document.write(printLists);
</script>
But, any time I echo $src into the script tag, it gets interpreted as HTML immediately and the page becomes a live mockery of the actual site.
//Actually just shows me thesaurus.com#strong
<body>
<div id="holder" style="display: none;"></div>
<script>
holder = $("#holder");
nodeNames = [];
html = $.parseHTML(<?php echo $src;?>, holder, false);
</script>
</body>
The phrase 'virtual DOM' sounds right, though I really don't want any of the copied source code to show up at all. I just want to extract certain parts of it : to run a script from the console, search a few thesaurus sites for a term, take the results, and save them to JSON accessed by a local thesaurus script.
I have a solid idea of how to do everything else, didn't expect this to be the tricky part!
Any suggestions on preventing the browser from parsing HTML?
(I would prefer this to run just as a script file without a browser anyway, but had trouble loading jQuery in a thesaurus.js file.)
You could run a php script to get file contents and echo the results to a textarea with readonly/disabled on, then query that php file through ajax to display the resulting textarea on the page.
For example, output.php:
<?php
$str = '<p>I am a paragraph.</p>';
echo '<textarea readonly="readonly">'.$str.'</textarea>';
?>
AJAX call in the original file:
$.ajax({url: 'output.php', success: function(data) { $('#result').html(data); }});

Jquery and AJAX script to run a PHP script in the background to avoid any refreshing

I have built a follow/unfollow Twitter like system using PHP. Now I would like to run the follow-unfollow PHP script in the background using AJAX/JQUERY to avoid refreshing the page when you follow/unfollow a user. To make things simpler, I will be here just using the example of “unfollow”. As you notice, I am running an iteration to output all the members in the database. I am outputting here (as well for simplicity) just the member’s name and an unfollow button to each one.
This is the code using php.
members.php
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member->name; ?></p>
<p class="follow_button">Unfollow</p>
<?php } ?>
unfollow.php
<?php
if($_GET['unfollow_id']){
$unfollow_id=$_GET['unfollow_id'];
$unfollow=Following::unfollow($id, $unfollow_id); //Function that will make the changes in the database.
// $id argument will be gotten from a $_SESSION.
}
I am trying to achieve the same result running unfollow.php in the background to avoid any refreshing. This is what I have come up with, as you might imagine it is not working properly. I am including the Jquery script inside the iteration which I think is the only way of obtaining the $member->id property to then assign it to the Jquery variable.
members.php THE NEW ONE THAT TRYS TO RUN THE SCRIPT WITH AJAX JQUERY
<?php foreach($members as $member){ ?>
<p class="member_name"><?php echo $member_name; ?></p>
<button type="button" class="unfollow_button" id="unfollow">Unfollow</button>
<script type="text/javascript">
$(document).ready(function(){
$("#unfollow").click(function(){
// Get value from input element on the page
var memberId = "<?php $member->id ?>";
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data){
// Success
});
});
});
</script>
<?php } ?>
Can you provide me any help for this to work?
Thanks in advance.
Remember, in HTML, id attributes have to be unique.
Because you're rendering multiple members on a single page, you should not use an id selector in jQuery, but a class selector (e.g. button.unfollow). If you use #unfollow, you'll run into ID conflicts between each of the members' buttons.
First, render all of your members with unfollow buttons without ids. I'm adding the member_id in the markup using a data attribute called data-member_id.
<?php foreach($members as $member) { ?>
<p class="member_name"><?=$member_name?></p>
<button type="button" class="unfollow_button" data-member_id="<?=$member->id?>">Unfollow</button>
<?php } ?>
Then add a single click handler for all button.follow buttons, which extracts the member_id from the clicked button's data-member_id attribute and sends it to the server.
<script type="text/javascript">
$(document).ready(function() {
$("button.unfollow_button").on('click', function() {
// Get value from input element on the page
var memberId = $(this).attr('data-member_id');
// Send the input data to the server using get
$.get("unfollow.php", {unfollow_id: memberId} , function(data) {
// Success
});
});
});
</script>
On a side-note, you should probably look into building a RESTful service for this, to which you can post proper HTTP requests using http://api.jquery.com/jquery.ajax/.
See here for an intro on REST in PHP I wrote a while back:
Create a RESTful API in PHP?

on page load grab php variable and send it to another page using ajax

this code is in page1 i have to send this variables to page2 where
i can get this variables using post method i have tried many to do but its so tough to it
calls();
function calls(){
function calls(){
var l="<?php echo $abc ; ?>";
var u="<?php echo $cdf ; ?>";
var ajax = ajaxObj("POST", "page2.php");
ajax.send("u="+u+"&l="+l);
}
this ajax variables have to be sent to page2 on page load automatically
If you are loading page two anyway why not just use a form submit
<input type ="hidden" value="$abc" name="l" />
Then just pick it up on page two
$_POST['l']

Passing a SESSION variable to JS

Okay, here's something that may seem rather trivial, but it's been giving me a headache, and I must have some sort of mental block now.
I want to pass a SESSION variable into JS, and then ultimately onto another page... It's only the first part that I'm worried about for now, because I can't even get a good "alert". The variable is blank... "the page at xxxxx says ____", even though the username shows up in the HTML span tag.
So, here's the applicable code on my page.
EDIT - For those asking why I would do this, I read it on (this) post...
EDIT: Solved. The method to do this is best done with:
var player = "<?php echo $_SESSION['username']; ?>";
Didn't need jQuery or other code. It is simple and direct, and shame on me for just sticking with one proposed solution from the other post.
In answer to some other questions: I did already have start session() at the top of the file. The script was after the HTML/PHP code. ***
... HTML stuff...
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
...more HTML...
<script>
function rollpublic()
{
... some declarations...
var player = document.getElementById("username").innerHTML;
alert (player);
more JS }
</script>
Edit
Sidenote: One reason which may be the cause of your session name not appearing, may be because session_start(); is not present in your pages, nor is there any mention of it in your posted code.
Without seeing FULL code, is hard to pinpoint it.
However, here is a successful test that I performed using the following codes: (page 1 & page 2)
Page 1:
<?php
session_start();
$_SESSION['username'] = "USERNAME";
?>
Check session name
Page 2: (sessions_check.php) which will echo and alert the session name.
<?php
session_start();
?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
var player = "<?php echo $_SESSION['username']; ?>";
alert (player);
});
</script>
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
Appearing in HTML source: var player = "USERNAME";
and You are <span id='username'>USERNAME</span></div>
N.B.: session_start(); needs to be inside all of the pages using sessions in order for this to work properly.
(Original answer) This worked for me:
<?php
session_start();
$_SESSION['username'] = "USERNAME";
?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
var player = "<?php echo $_SESSION['username']; ?>";
alert (player);
});
</script>
You are <span id='username'><?PHP echo $_SESSION['username']?></span></div>
You may call session by ajax:
function getSession(){
var session;
$.get('someUrlThatReturnSession', function(sessionData) {
session = sessionData;
});
return session;
}
You can assign SESSION variable to javascrip variable..
<script>
function myFunction(){
var a = <?php echo $_SESSION['var'] ?>;
alert(a);
}
</script>
If you need more help let me know..
If you're using Angular JS, you can use this approach. (Provide the PHP var to the ng-init param of a hidden input)

Categories

Resources