I have all my webpages loaded with ajax, I'm not sure how to include POST data from the loaded page. The goal is to have a registration form and post that data to another php file and have it processed there.
ajaxloader.js
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
setInterval("checkURL()",250);
loadPage('#Home');
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
}
}
});
}
load_page.php
if(!$_POST['page']) die("0");
$page = $_POST['page'];
if(file_exists($page.'.php'))
echo include($page.'.php');
else echo 'There is no such page!';
?>
Any ideas?
So your load_page.php woudl look like
if(!$_POST['page']) die("0");
$page = $_POST['page'];
ob_start();
if(file_exists($page.'.php'))
include($page.'.php');
else echo 'There is no such page!';
$content = ob_get_clean();
echo $content;
This should do the job. HOWEVER, you can't just pass the whole website like that, you need to base64_encode() it make sure everything is ok. And then take a look at this
http://phpjs.org/functions/base64_decode/
Related
I am familiar of how to get ajax to go to a php page an execute a series of things and then return json data. However is it possible to call a specific function which resides in a given page?
Basically what I want is to reduce the number of files in a project. So I can put a lot of common functions in one page and then just call whatever the function that I want at the moment.
For AJAX request
Include jQuery Library in your web page.
For e.g.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Call a function on button click
<button type="button" onclick="create()">Click Me</button>
While click on button, call create function in JavaScript.
<script>
function create () {
$.ajax({
url:"test.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc#gmail.com"},
success:function(result){
console.log(result.abc);
}
});
}
</script>
On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in PHP and return in JSON format e.g.
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
// some action goes here under php
echo json_encode(array("abc"=>'successfuly registered'));
}
You cannot call a PHP function directly from an AJAX request, but you can do this instead:
<? php
function test($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo test($_POST['callFunc1']);
}
?>
<script>
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { console.log(response); }
});
</script>
As a structure for this kind of purposes, I suggest this:
PHP
<?php
if(isset($_POST['action'])){
if ($_POST['action'] == "function1") { func1(); }
if ($_POST['action'] == "function2") { func2(); }
if ($_POST['action'] == "function3") { func3(); }
if ($_POST['action'] == "function4") { func4(); }
}
function func1(){
//Do something here
echo 'test';
}
?>
jQuery
var data = { action: 'function1' };
$.post(ajaxUrl, data, function(response) {
if(response != "") {
$('#SomeElement').html(response);
}else{
alert('Error, Please try again.');
}
});
As mentioned, you can't call a PHP function directly from an AJAX call.
If I understand correctly, yes you can.
Put all your functions in one php file and have the ajax pass as a parameter which one you want to call. Then with a switch or if structure, execute the one you want.
jquery:
$(document).ready(function(){
$('#tfa_1117700').change(function(){
var inputValue = $(this).val();
var v_token = "{{csrf_token()}}";
$.post(
"{{url('/each-child')}}",
{ dropdownValue: inputValue,_token:v_token },
function(data){
console.log(data);
$('#each-child-html').html(data);
}
);
});
});
php:
public function EachChild(Request $request)
{
$html ="";
for ($i=1; $i <= $request->dropdownValue; $i++)
{
$html = $i;
}
echo $html;
}
I want to create jquery ajax success function based resp from logout.php. If users not sign in,It redirect bring them to login page.,but it's not working as I'm expected,no event occur when user is logged or not.So, what is wrong with my ajax function?
logout.php
<?php
if( !$user->is_logged ) {
echo 'true';
}else{
echo 'false';
}
?>
jquery function in index.html
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
if(resp =='true'){
document.location = '../login_test.html';
}
if(resp=='false'){
alert('U are logged');
}
}
});
});
Change some errors and made it to better view:
PHP:
<?php
header('Content-Type: application/json');
if( !$user->is_logged ) {
echo json_encode(array('status' => 'ok'));
}else{
echo json_encode(array('status' => 'bad'));
}
?>
Javascript:
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
var state = JSON.parse(resp).status
if(state == 'ok'){
document.location.href = '/login_test.html';
}
else{
alert('U are logged');
}
}
});
});
If you have no alert, and have no redirect - you have not .success callback, and problem one level above your condition. In that case show us your errors from js-dev-console from browser.
Actually I'm trying to redirect to the index after logging in with ajax button
but what is happening is strange , header is not taking me to the index.php !
i just get the HTML code of the index.php in my login.php page !!
I'm using Smarty to separate the html from php code , and I don't know how to fix the problem !
click the login and get the HTML of the index in login page !
why ?
in login.php page
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}
the ajax function :
function ajax3(Div_Submit,Div_Response,SuccessScript,Data_Submit)
{
var Type = 1;
var Aj_type = "POST";
var post_data = '';
if(!Data_Submit)
post_data = $('#'+Div_Submit+' *').serialize();
else
post_data = Data_Submit;
$.ajax({
type: Aj_type,
url: document.URL,
data: post_data,
dataType: "text",
beforeSend: function(xhr)
{
$.blockUI({ message: '<img src="images/loading.gif" />',
css: { border: 'none', backgroundColor: 'transparent' } });
xhr.setRequestHeader("Ajax-Request", "true");
},
success: function(response) {
$('#'+Div_Response).html(response+'<script>'+SuccessScript+'</script>');
},
complete: function(){
$.unblockUI();
}
});
return false;
}
the html button call :
<div class="buttons" >
<a class="positive" onclick="$('#login_action').val('login');ajax3('login_form','login_form','','')">
<img src="images/checkbox_checked.png" alt=""/>
<font size="3px"> login </font>
</a>
</div>
That wouldn't work as what you expected.
It should be something like this.
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo "success";
}
On your javascript/jquery file.
have something like this
jQuery.ajax({
url: "login.php",
success:function(data){
if(data == "success") window.location = "index.php";
}
});
With AJAX, this is the expected output. What happens is that the AJAX request itself is being redirected to index.php, which I what is then outputted and returned to that request.
If you want to redirect to index.php from AJAX, you would need to exit with a specific code, or a JSON-encoded value and catch that in the AJAX result itself.
Example:
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo json_encode(array('redirect' => 'index.php'));
exit;
}
JavaScript:
$.ajax(
url: 'your-url',
success: function(data) {
if (data.redirect) {
document.location.href = data.redirect;
}
}
);
u can get success response whenever login credentials are appropriate , at that moment change the window location using javascript or jquery..
I am using this tutorial http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_toggle
Here is the code without the style.
<script type="text/javascript">
$(document).ready(function()
{
$(".flip").click(function()
{
var panel = "open";
$(".panel").slideToggle("slow");
});
});
</script>
How would I go about saving the state of this so if I refreshed the page it would remain open or closed. I imagine a php session would be the correct way, but how do I write that in the javascript?
In JS:
var readWirite='write'; //or 'read'
$.ajax({
type: "POST",
url: "myPhpFile.php",
data: "panel="+panel+"&readWrite="+readWrite;
success: function(msg){
if(msg == '1'){
alert('Horay panel saved!');
} else {
$('#panelId').html(msg); //Write saved panel back to html
}
}
});
In myPhpFile.php:
<?php
if(!isset($_SESSION)) session_start();
if(isset($_POST['readWrite']) && isset($_POST['panel'])){
if($_POST['readWrite'] == 'write'){
$result = '0';
if($_SESSION['panel'] = $_POST['panel']) $result = '1';
echo $result;
} else if($_POST['readWrite'] == 'read') {
echo $_SESSION['panel'];
}
}
?>
I created an Ajax navigation system but I've an issue when I want to send a variable.
I've an index.php like this
<script src="navigation.js" type="text/javascript"></script>
<div id="pageContent"></div>
page1
profile
This is navigation.js
$(document).ready(function(){
checkURL();
$('a').click(function (e){
checkURL(this.hash);
});
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
}
}
});
}
And this is the load_page.php page:
<?php
if(!$_POST['page']) die("0");
$page = $_POST['page'];
include('pages/'.$page.'.php');
?>
This is the issue: when I load profile.php page I want to see values by GET... example:
<?php
$nome_utente = $_GET['user'];
if(!$_GET['user']) {
print 'Attention! You have to insert a username';
}
else
{
print $nome_utente;
}
?>
To do this I tried to change the link in index.php
profile
But this doesn't work because load_page.php doesn't find the "profile?user=test.php" page.
What do I have to do to send a GET variable at profile.php, from a link in index.php?
I've to edit JS or PHP code?
Mixing get/post variables is considered poor practice, but is easily done:
function loadPage(url) {
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php?user=whatever_you_want_here",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^---your 'get' query
The other optiont would be to add the 'user' parameter to your ajax data line:
data: { page: url, user: whatever_you_want_here }
The first one would make 'user' available in $_GET, the second one would make it available in $_POST.