How to include PHP file with JavaScript and pass parameters - javascript

I need to run a PHP function in a page, after the user clicks on something, in this case, a link.
First I was using onclick to run a javascript AJAX to request a PHP file with the function in it. The thing is, I need to pass a parameter to the function, and I can't seem to be able to do it with AJAX.
If it was a PHP include, it would behave like it 'appended' the other file to the current file, so this way, the included file could reference variables in the current file. Apparently, AJAX is just taking the file I need, running it's code, and displaying the results. So yeah, doesn't work for me.
So basically. I need an exact replica of PHP's 'include', on JavaScript.
OR any other workaround.
My current code:
<br> <div id="seeMore"> </div> <br>
<ul> <li style="float: left"> Ver Mais </li> </ul>
<script type="text/javascript">
function loadMore()
{ $("#seeMore").load("feedP.php"); }
</script>
This is the part of the code in the main page that im needing help with, you can see it's loading a page called feedP.php, here's it's code:
<?php
echo 'test';
require_once('functions.php'); loadFeeds($urls, 5);
?>
As you can see, I have to run a function called loadFeeds, and it requires a parameter, $urls. Witch is created back on the main page.
EDIT:
I CAN'T reload the page, or redirect the user, that's why i'm trying to 'append' the file here.

You can use the second parameter of the load function which takes parameters that can be posted to the file in question:
$("#seeMore").load("feedP.php", {
url: 'url'
});
Then, in your PHP you can make use of $_POST to access the posted data.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
Reading Material
.load

You can pass the parameters through load function. I have altered your script code as below.
<script type="text/javascript">
function loadMore() {
$("#seeMore").load("feedP.php", {urls: "<?php echo $url; ?>"});
}
</script>
In the above code $url is the php variable which you assign the url you need to pass to feedp.php

Related

Trouble posting variable from JS to PHP

I am trying to send a JS a variable to a php file. It is not happening. And there are many questions answered out there on similar situation. I probably am making some similar mistake. Though, I am not able make out what it is.
The Codes are as follows;
main.php
<script type="text/javascript"> var socialurl= "<?php echo $url;?>";</script>
JS
jQuery(function(){
alert('socialurl');
$("#smshare").click(function(){
$("#smp").slideToggle("fast");
$.post("social-media-share.php", {socialurl: socialurl });
$("#smp").load("social-media-share.php");
});
});
social-media-share.php;
<?php
$socialurl=$_POST['socialurl']
echo $socialurl."<br>";
include('conn.php');
$socialurl = $conn->real_escape_string(trim($_POST['socialurl']));
?>
<img src='images/share.png' width="30" height="30" alt='WhatsApp Share'>
The file social-media-share.php is called into the main.php with JS. Prior to which the JS variable socialurl is defined in the main.php
The variable value pops up in alert in the JS but it is not getting posted to social-media-share.php
I am sure I must be making some silly mistake. But for the life of me am not able to find out what.
Any help will be greatly appreciated.
I think the problem is you're posting to the page, but then loading it again via a GET request and so you're not loading the results of the post request itself.So unless the GET on social-media-share.php is displaying a database result I'm not sure you're actually loading what you want.
jQuery(function(){
alert('socialurl');
$("#smshare").click(function(){
$("#smp").slideToggle("fast");
$.post("social-media-share.php", {socialurl: socialurl });
$("#smp").load("social-media-share.php");
});
});
This bottom line is doing the wrong thing. $("#smp").load("social-media-share.php");
you actually want a callback function in you .post that loads the response from that
http://api.jquery.com/jQuery.post/
$.post( "social-media-share.php", {socialurl: socialurl })
.done(function( data ) {
//you might need to do some other stuff to data here
$("#smp").html(data);
});
Alternatively you might have an error in your social-media-share.php script so you could try doing a var_dump($_POST); to see what variables are actually being posted

.load() function won't load javascript

When I use the function .load(), it will load the page that I want to load in the div that is selected.
But when I want to use JavaScript/jQuery that I already have coded in other files, it wont work anymore.
It does work when I just include ''; the page static in the div.
Does anyone have an idea why this works like this?
Static:
<div id="loginCont" class="modal-body">
<?php
include 'login.php';
?>
</div>
by Javascript/jQuery
$("#memberFalse").on("click", function() {
$('#loginCont').load("/213server/_inc/login.php");
});
A PHP include that starts with "/" refers to the root of the server, unless specified otherwise in your php.ini file. Your code:
<div id="loginCont" class="modal-body">
<?php
include 'login.php';
?>
</div>
fetches "login.php" from the folder where the current page is located. You can display that location with:
<?php echo __DIR__ ?>
Your jQuery load() method should fetch the page "login.php" from that location too. There is obviously a mistake in the following path:
$('#loginCont').load("/213server/_inc/login.php");
Remember that Javascript/jQuery CANNOT fetch files outside the web root, but PHP can. For example, if your login.php file is located at "/var/_inc/login.php" and your web root is at "/var/www/", jQuery will never have access to login.php. If your login.php file is located at "/var/www/myproject/_inc/login.php", then your load() function should fetch it like this:
$('#loginCont').load("/myproject/_inc/login.php");

global variable not displayed in div

I declare a variable at the beginning of my .js file:
var option="blabla";
On page 1.html I click on a link to page 2.html where I have
<script>document.write(option);</script>
No text is displayed on 2.html. When I refresh the browser while I am on 2.html I get undefined as an output.
What do I have to do to have the text displayed straight after I click the link?
Alternatively, how can I get the following code work to output strUrl on 2.html:
on 1.html I have a link:
<a href="2.html" onclick="function1("item")">
on 2.html I have a div:
<div id="display">document.write(strUrl);</div>
then I have in my .js file:
function1(searchitem)
{
strUrl = 'http://blabla.com/'
+ '?key=' + searchitem;
}
You try to create a Javascript variable on a page and then use it on another page. This is a more-or-less broad problem, since you want to maintain values across pages. First of all, you need to decide where is this value going to be defined and where is it going to be used. If this is more like a server-side variable, then you need to define it on server-side and then generate it into your Javascript code. If you are using PHP, then you can do it like this:
<script type="text/javascript>
var foo = '<?php echo $bar; ?>';
</script>
Naturally, you need to initialize $bar to be able to do that. If the variable should be a client-side variable, then you need to use localStorage, like this on 1.html:
localStorage.setItem("option", "blablabla");
and then load it on 2.html:
localStorage.getItem("option");
Or, if you need to use it both on server-side and client-side, then you can use a cookie for this purpose. Using cookies i slightly more complex, but my answer to another question should get you going.
Let's focus on the cause this did not work for you. A Javascript variable will cease to exist when the page is unloaded, so you will not be able to use its value after that. So, you need to persist it somehow, storing it either on the server or the computer where the browser is being run.
As a side-note, I should mention that you can use Javascript variables accross pages if you load some pages inside iframes of a page, but that is a different scenario.
This is what FORMS and AJAX were invented for. If your server has a PHP processor (virtually ALL of them do), then you can rename your .html files to .php and use a bit of PHP to accomplish your goal.
A web page ending with .PHP works exactly the same as one ending in .html, except that you can now add snippets of PHP code where desired. It is not necessary to have any PHP code, but if you have some it can do stuff.
Method One: FORMs
If you want to switch to page2.html and see a value sent from page1.html, you can use a FORM construct and post the data from page1 to page2:
page1.php
<form action="2.html" method="post">
<input name="option" type="text" />
<input type="submit" name="sub" value="Go" />
</form>
page2.php
<?php
$p1 = $_POST['option'];
?>
<div>On page1 of this website, you typed: <?php echo $p1; ?>. That's what you did.</div>
Note how a <form> uses the name= attribute for the name of the variable that is sent to the other side.
Example Two: The AJAX method
HTML:
<div id=nonForm">
<input id="option" type="text" />
<input type="button" id="myButt" value="Go" />
</div>
<div id="results"></div>
jQuery:
$('#myButt').click(function(){
var opt = $('#option').val();
$.ajax({
type: 'post',
url: 'page2.php',
data: 'option='+opt,
success: function(john){
if (d.length) alert(john); //display result from Page2 in a pop-up box
$('#results').html(john); //Or, display it right on the page
}
});
});
PAGE2.PHP -- The AJAX processor file
<?php
$opt = $_POST['option'];
//Now, you can do something with the data in $opt, and then send back a result
$rtn = 'Hey, you sent: ' .$opt;
echo $rtn;
The primary (and most important) difference between the two methods is that the FORM will change pages on you. The user will be sent from Page1 to Page2, and the screen will flash as this happens.
What's exciting about AJAX is it sends data to Page2, where Page2 can do something with it (for example, a database lookup), and then Page2 sends different data back to Page1. This new data can then be displayed on the page WITHOUT the page refreshing.
Here are a couple of very basic AJAX examples, to get you going:
AJAX request callback using jQuery

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?

Can I redirect to a new php file while posting a form input?

I have a html web page which I use to get some user input. This input is then posted using jquery to a php script which in turn sends a get request to a REST API to receive json data.
My question really is: is it possible to change my php file into another webpage with embedded php and redirect to this while posting the variables to the same script, so I could display the json results in a table on a new page simultaneously.
I already receive the json in the javascript file and I know I could use this to create a table, I was just interested if I could in fact do it all in one go on the php page as I already have script written to populate a table using the json data.
I have included some basic fragments of my code to help explain what I am doing.
HTML:
<head>
<script type="text/javascript" src="collect_User_Input.js"></script>
</head>
<p> What is the unique id of the beacon? </p>
<form> <input type="text" id="uniqueId" /> </form>
<button onclick="collect_User_Input();" >Send Request</button>
JS:
var uniqueId = document.getElementById('uniqueId');
$.post("send_Request.php", { uniqueId: uniqueId.value },function(result) {
alert(result);
PHP:
$uniqueId = $_POST["uniqueId"];
(GET request using curl)
echo ($uniqueId);
I tried skipping the javascript step and submitting the form directly, but this always gave me forbidden error messages. as you may have guessed I am very new to this so any advice is welcome.
In your PHP you will most likely want to return some JSON using json_encode:
http://php.net/manual/en/function.json-encode.php
Within your JSON, you could return a success value - then depending on the value of that you can redirect using:
window.location
You could even have a second attribute that returns what page you want the user redirected to if it isn't the same as the uniqueID:
{"success":true,"location":"/your/path/here.html"}
The flip side being, if there is an error you can return this to your page with a relevant message:
{"success":false,"message":"ID not found"}
I use this process to check something is valid on the server before doing the redirect, which sounds more or less the same as what you want to do?

Categories

Resources