Get Json_encode to a different jQuery page - javascript

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

Related

How can I place a drop-down list made in php in a specific HTML form?

I have some php that connects to a database and creates a drop down list. I have a specific form in the HTML that I'd like to put the list in.
<body>
<form>
// some text inputs
// where i'd like the drop down to go
<?php makeList(parameter1, parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList(arg1, arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>
The only languages I'm allowed to use (apart from the sql) are php, html and javascript. As it is right now, makeList() returns an empty list. When I include opening and closing form tags in the function it returns a fully functional list, but then it acts as it's own form and I need to to be a part of the original form. Thanks.
EDIT: Sorry, forgot to mention the makeList function works fine when called within the php tags. It's when I call it in the HTML that it returns an empty list.
Firstly, you have some syntax issues with your script. It's not a valid HTML file, not a valid PHP file, and not a valid JS file.
If it were up to me, I'd define the PHP function at the stop of my script. Be careful to balance your opening and closing PHP tags. Something like this:
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option">;
echo $row[$column];
echo "</option>";
echo '</select>';
}
?>
And only after that would I start to output my HTML.
Now there are a couple of important things to note about that script I just posted:
the database code is not in here...I don't see any connection or query getting run or anything
In your script, this function doesn't look valid. arg1 and arg2 need a $ in front of each to be a valid PHP function. If it's a JS function you want then well, you are very confused and probably need to go back and figure out why this is not a valid JS function.
Your function refers to a variable, $result, that you have not bothered to define. It is not mentioned anywhere else in your script. It is most certainly not mentioned anywhere inside your function. For $result to be defined inside your function, you either need to pass it in as an array or declare it as a global:
global $result
Your function doesn't return anything at all. It just echoes stuff. This doesn't mean you can't use it, but it does mean that the function has no return value. Echoing the result of makeList won't output anything at all
So after that script above, you might have something like this:
<body>
<form>
// some text inputs
<?php makeList($parameter1, $parameter2); ?>
// submit button
</form>
Depending on what your parameters ($parameter1 and $parameter2) are this should work.
<body>
<form>
// some text inputs
<?php echo makeList($parameter1, $parameter2); ?>
// submit button
</form>
<?php
// connect to database
function makeList($arg1, $arg2) {
echo '<select>';
while ($row = mysqli_fetch_array($result)){
echo "<option>";
echo $row[$column];
echo "</option>";
echo '</select>';
}
</body>

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?

Change href depending on php response

I want to change the href of morestorieslink depending on the data received from mysql database i.e. if there is no row returned from server then the href for DOM element morestorieslink should change
I am using this for changing the href value
if (mysql_num_rows($result) == 0) {
?>
<script type="text/javascript">
document.getElementById("morestorieslink").href="select.php?<?php echo $selecturl?>=<?php echo $select; ?>&select=Continue";
</script>
<?php
echo "Url Changed";
}
In this case javascript doesn't work but the echo is displayed, I also tried embedding javascript inside php echo.
Thankyou
if (mysql_num_rows($result) == 0) {
?>
<script type="text/javascript">
// wait for dom to finish loading properly.
document.addEventListener("DOMContentLoaded", function(event) {
document.getElementById("morestorieslink").href="select.php?<?php echo $selecturl?>=<?php echo $select; ?>&select=Continue";
});
</script>
<?php
echo "Url Changed";
}
Put this at the last of your page make it a point that no java script is executed after this. Rest all looks good.
Hope that helps.
Note :
the href you mentioned will append to the exsisting url.
Also check that $selecturl or $select is not null and isset.
You can also check the page source to check wether the link is generating properly or not (using Firebug in mozilla)
you can use ternary operator. Something like:
<?php echo $select ? $selecturl.$select : $otherURL;?>
I assumed your url is changing based on value of $select

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)

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

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.

Categories

Resources