I am trying to send data to php with ajax and at the same time redirect to that php file but when I redirected to the php file, the ajax didn't seem to send the data. I wanted to achieve something wherein a button is clicked and a data is sent to php using ajax and at the same time redirect to that php file to see the data sent by displaying it. The reason I didn't use something like window.location="ajaxtest.php?data=data" is because I'm gonna be using it in a google map api wherein if I click a button of a place, then I will redirect to the maps page and display the marker of the specific place depending on the id the ajax sent to the php file and the coordinates generated based on that id.
ajaxtest.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3
/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
var data = "test";
$.post("ajaxtest.php",{
data: data
},function(data, status){
window.location="ajaxtest.php";
});
});
});
</script>
<button id="button">test</button>
</body>
</html>
ajaxtest.php
<?php
if(isset($_POST['data'])){
echo $_POST['data'];
}
?>
So, that's not how HTTP, AJAX, or PHP work. There isn't any POST data when you do your redirect, because the redirect is a separate request from the AJAX post. What you want is to do an AJAX post and somehow consume the response on your page, without doing a redirect at all.
It doesn't seem like ajax is the way to go here. If you want to redirect to a different page just do window.location.href = 'ajaxtest.php?id='+locationId; and in your ajaxtest.php:
<?php
$id = isset($_GET['id']) ? (int) $_GET['id'] : null;
if ( ! $id) {
die('ID missing');
}
// Show marker
?>
Related
I would like to post data to my PHP page and then have it update the HTML page. I followed this example of using server-sent events to push updates to a webpage.
Here is what I have right now:
output.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="serverData"></div>
</body>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</html>
send_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$val = 0;
if (isset($_POST['msg'])){
$val = $_POST['msg'];
}
echo "data: $val\n\n";
ob_flush();
?>
form.html:
<html>
<body>
<form action="send_sse.php" method="post">
Message: <input type="text" name="msg"><br>
<input type="submit">
</form>
</body>
</html>
The problem is that when the form posts the value, it does not update the output.html. It does output "0" and will update whenever I manually change the value of $val and save the file. However, I want the value of $val to be determined outside of the PHP file. What am I doing wrong?
The issue you are having here is that you have missed how SSE conceptually work. Your output.html page is making a GET request to your web server and executing the script send_sse.php and opening up a connection and HOLDING that connection open and waiting for updates.
When you are posting from form.html you are sending a POST request to your web server and executing the script send_sse.php on a completely different thread.
As you have not implemented any shared persistence between these two threads it will make no difference.
So to do what you want to do you will need to have code in send_sse.php that has some form of global persistence (e.g. database) and can detect new data and then flush that down to the browser.
I am not a PHP expert, but I have written an example in Node JS that uses REDIS pub/sub to provide said persistence.
I hope that helps.
Hii Everyone,
Here is my code for facebook Signin.i got this example from http://www.codexworld.com/login-with-facebook-using-php/. here is my index page code
PHP code
<?php
include_once("config.php");
include_once("includes/functions.php");
//destroy facebook session if user clicks reset
if(!$fbuser){
$fbuser = null;
$loginUrl = $facebook->getLoginUrl(array('redirect_uri'=>$homeurl,'scope'=>$fbPermissions));
$output = '<a class="myLink" href="'.$loginUrl.'">Click Here To Proceed</a>';
}else{
$user_profile = $facebook->api('/me?fields=id,first_name,last_name,email,gender,birthday,picture');
$user = new Users();
$user_data = $user->checkUser('facebook',$user_profile['id'],$user_profile['first_name'],$user_profile['last_name'],$user_profile['email'],$user_profile['gender'],$user_profile['birthday'],$user_profile['picture']['data']['url']);
if(!empty($user_data)){
$output = 'Thanks For Register With Spark.You Should Receive Confirmation Mail Shortly';
}else{
$output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
}
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Spark Login with Facebook</title>
<style type="text/css">
h1{font-family:Arial, Helvetica, sans-serif;color:#999999;}
</style>
</head>
<body>
<div>
<?php echo $output; ?>
</div>
</body>
</html>
Here i use a href to show facebook login.after te click of href it will redirecting to facebook login instead automatically want to click and it will redirect the page.Is there any possible way to do that.If anyone know the solution for the problem please help me!!
Why not do this with header location? Here´s how that works: PHP header(Location: ...): Force URL change in address bar
For example:
$loginUrl = $facebook->getLoginUrl(array('redirect_uri' => $homeurl, 'scope' => $fbPermissions));
header("Location: " . $loginUrl);
Official docs: http://php.net/manual/function.header.php
No need for using an $output variable, or for creating a login page (if you want to auto-redirect anyway). Just redirect the user if he is not logged in yet. No need to do something shady like "auto-clicking the login button". It´s not a solution, it´s a bad workaround. Although, it would be a lot better if you would let the user click it. Redirecting to the login page without a proper intro page, where he can see what the App is about, is not a good idea.
Even better: Use the JavaScript SDK for login: http://www.devils-heaven.com/facebook-javascript-sdk-login/
If you want to change the webpage's URL, you do not need to use jQuery to click the link. Instead, there is a simpler way.
JS:
window.location = "http://www.example.com/";
By changing the window.location, you can "redirect" to a new URL.
If you want to redirect only after an event, you can put that in a function of yours.
Example:
window.location = "http://www.example.com"
i have test.html and test.php file uploaded to /var/www/html in my AWS Amazon EC2
URL of test.html is : http://ec2-11-11-111-11.ap-northeast-1.compute.amazonaws.com/test.html
URL of test.php is: http://ec2-11-11-111-11.ap-northeast-1.compute.amazonaws.com/test.php
test.html is:
<!DOCTYPE html>
<head>
<script type="text/javascript" charset="utf-8">
function myFunction(){
var url = "http://ec2-11-11-111-11.ap-northeast-1.compute.amazonaws.com/test.php";
var data = "test_data_string";
alert("Post to PHP"); //check to see if javascript is working
$.post(url, {testdata:data},
function(echo){alert(echo);});
}
</script>
</head>
<body>
<button onclick="myFunction()">Click me</button>
</body>
</html>
test.php is:
<?php
$data = $_POST['testdata'];
echo "success";
?>
I am expecting to get alert("success"); when I click the "click me" button, but I am getting nothing.
i get alert("Post to PHP"); when I click on the button. so it seems that both of the files are working except $.post();
What am i doing wrong here??
These two urls are not accessible , I am not sure what you are doing but putting the php file online does not mean that it is accessible and will run as a script.
URL1: http://ec2-11-11-111-11.ap-northeast-1.compute.amazonaws.com/test.html
URL2: http://ec2-11-11-111-11.ap-northeast-1.compute.amazonaws.com/test.php
Include jQuery library
update:
Your js does not have problem if you include the jquery library. I tested it sends the post request successfully. jsFiddle
I have made a RESTful API in PHP. To do shortly, I can register some information by calling an address like http://api.website.com/addInfos
This request is a POST request. Here my method:
File: api.php
<?php
/* Page api.php */
private function addInfos()
{
// Check if it's a POST request and if all fields are correct
// Insert data in my MySQL database
// TODO: make an automatic refresh for page named infos.php
}
?>
Second file, where the data are displayed from my database:
File: infos.php
<?php
/* Page infos.php */
// Connection to database
// Prepare the request using PDO
// Execute the request
// Display infos in a while loop
?>
My question is: How can I refresh the part of code where the data is displayed just after the function named "AddInfos" of my API is called ?
EDIT 1:
Here is what I can do:
File: index.php
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<title></title>
<script src="js/jquery.js"></script>
</head>
<body>
<div id="infos"></div>
<script>
function displayInfo(r) {
$.post("infos.php",
{ refresh : r},
function(data){
//alert("Data Loaded: " + data);
$("#infos").html(data);
}
);
}
$(document).ready(function() {
displayInfo(1);
$('a.info_link_text').click(function(){
alert($(this).text());
});
});
</script>
</body>
</html>
File: infos.php
<?php
require_once('database.php');
if(isset($_POST['refresh'])){
$selectInfos = getAllInfos();
$selectInfos->execute();
echo "<table>";
echo "<th>User</th>";
echo "<th>Email</th>";
while($row = $selectInfos->fetch(PDO::FETCH_OBJ)){
$fullname = $row->user_fullname;
$email = $row->user_email;
echo "<tr>";
echo "<td>".$fullname."</td>";
echo "<td>".$email."</td>";
echo "</tr>";
}
echo "</table>";
}
?>
When I load index.php, I can get the infos from the page infos.php. But I really don't know how can I do this when the method "addInfos" of my API is called, because I need to make a POST request on infos.php (it's OK) but put the result data on index.php (not ok, I don't know how to do that). Please, could you let me know how to achieve this ?
Thank you so much for your help.
Best regards,
Lapinou.
I think what you need is a library based on WebSocket HTML5. The server can retain and send notifications to all clients connected at the same time. Then in your javascript handler, you can process anything you want.
In PHP, you could try these examples WebSocket HTML5 PHP on Google
The other way would be to send multiple REST queries on a regular basis to the server to update your page, but it seems you want real-time updates only.
a page directs users back to a page automatically
<meta http-equiv="refresh" content="1; URL=http://localhost/mywebsite/Untitled9.php">
when it reaches 'Untitled9.php' i want it to display an alert box saying 'Message sucessfully posted'
I only want it to display when it id directed back to the page and not when first load
e.g Home - Message page = No alert
Home - message page - submit - redirect to message page = alert 'post sucessfully posted'
Can't control the DOM of a page externally.
What you could do however is pass a variable in the query string to the page you're redirecting to like this
Untitled9.php?message=success
Then on your new page have
<?php
session_start();
if ($_GET['message'] == "success" && $_SESSION['revisit'] == "0")
{
$_SESSION['revisit'] = "1";
?>
<script type="text/javascript">window.alert('Message successfully posted.');</script>
<?php
}
?>
In your first page change your code to look like this
<?php
session_start();
$_SESSION['revisit'] = "0";
?>
<meta http-equiv="refresh" content="1; URL=http://localhost/mywebsite/Untitled9.php">
If I understand your question correctly, this should work for you (assuming you alter the keys for the $_POST variables accordingly, of course):
<?php (isset($_POST['my_sub_btn'])): ?>
<script type="text/javascript">window.alert('Message successfully posted.');</script>
<?php endif ?>
Assuming you're submitting the message from a form, there should be no reason to redirect using a HTML redirect. Set the action attribute of your form to Untitled9.php and it will handle the rest...
Given your requirements, why not set a parameter on succes? Such as:
<meta http-equiv="refresh" content="1; URL=http://localhost/mywebsite/Untitled9.php?success=1">