I am a starter in PHP language. I was trying to develop a small application. For that (lets say, page 1) I was posting some data to a PHP file from the page 1 through an Ajax call.Then I want to access the same value from that PHP file in another HTML file through another Ajax call (let's call page 2).
So I used the session variable for this. I was able to access the values easily in my local-host. Then I uploaded the files in my hosting server. But the application is not working. From the page 1 the data is sending and I am getting the Ajax response accordingly. but am not getting the data in the page2.
Page 1 code is as follows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'GET',
url: 'main.php',
data: {type : 'test' },
dataType:'html',
success: function (data) {
location.assign("mains.html");
}
});
return true;
});
</script>
page 2 is as follows
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$.ajax({
type: 'GET',
url: 'main.php',
data: { test: 'value' },
dataType:'json',
success: function (data) {
alert(data);
}
});
});
</script>
the server file is as following,(of course its a PHP file)
<?php
session_start();
if(isset($_GET['type'])){
$_SESSION['type'] = $type = $_GET['type'];
echo $_SESSION['type'];
}
if(isset($_GET['test'])){
echo $_SESSION['type'];
}
echo $_SESSION['type'];
?>
Change the extension of your HTML file to .php, then start the file with
<?php
session_start();
?>
In other words: session_start() needs to be called in every PHP file you use.
Related
I'm new to php so please bare with me. I have an ajax function that creates a post request to send data to server side php and echo it and my code should work fine. The problem is the php echo is proccessing before the create() function is ran so an error that the variables are not found is only displayed. Is there a way in php to make the echo proccess wait untill the ajax function is ran. Any help is appreciated. Thanks in advace.
function create() {
$.ajax({
url: "test.php",
type: "post",
dataType: 'json',
data: {
registration: "success",
name: "xyz",
email: "abc#gmail.com"
},
success: function(result) {
console.log(result.abc);
}
});
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button onclick="create()">click me</button>
<?php
$registration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];
if ($registration == "success"){
echo json_encode(array("abc"=>'successfuly registered'));
}
?>
UPDATE: Checked if there is a POST request inorder to proccess the script but no echo.
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 src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<button onclick="create()"> Click me</button>
<? php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$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'));
}
}
?>
Assuming your script and button tags live in the same file as the php script the way it's shown in your question: Your code runs out of order because, as you point out yourself, you run the PHP code before your create function runs. Just because you wrote the code in order doesn't mean it will run in order.
Here's what happens, in order:
script and button tags are rendered
Your php code runs
The result of steps 1 and 2 is sent to the browser
Then somebody clicks the button
What you need to do is move the php script to a separate route that you only request upon button blick. For example test.php, assuming the code you show in your q doesn't already live in that fileāin that case, you'll need to put the php code in a different file.
I've the SET the following AJAX request. The url is actually a file called "Controller.php", and from this it can be understood that, it is a MVCish styled project.
$.ajax({
url: "http://127.0.0.1/Controller/fetch",
method: "POST",
data: {
function: 'fetch'
},
success: function(data){ var string = JSON.stringify(data); var json = JSON.parse(string);
$("#div#id").html(json);
}
});
This is the code in the "Controller.php":
<?php
class Controller extends Base_controller{
public function fetch(){
if(isset($_POST['function'])){
// Execute a SQL Query and return data
echo json_encode($result_of_the_query);
}
}
}
The request works perfectly and fetches the requested data, but also brings some unwanted HTML code from a page (index.php - everything is routed from here), as shown below: I tried echo strip_tags(json_encode($result_of_the_query));, as mentioned here AJAX returns HTML code with output. But it didn't work. What modification should I do in my code??
<!DOCTYPE html> <!-- <script src="http://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> --> <script src="/vector/js/jquery-3.5.0.min.js"></script> [{"column_one":"14-Jun-2020","column_two":null,"column_three":null},{"column_one":"07-Jun-2020","column_two":null,"column_three":null}]
My bootstrap.php file is very similar to:
// Load Config (database)
require_once 'config/config.php';
// Load Helpers
require_once 'helpers/url_helper.php';
require_once 'helpers/session_helper.php';
// Autoload Core Libraries
spl_autoload_register(function($className){
require_once 'libraries/' . $className . '.php';
});
On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?
I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue
I have a problem that my Js file is not recognizing a php variable built by ajax.
Here is an example:
index.php:
<script src="js.js">
</script>
<?
include('build.php');
<div id="brand">
<?
echo $brandinput;
?>
</div>
//....more code
?>
build.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function(data){
$("#result").html(data);
}
});
</script>
<?php $brandinput='<div id="result"></div>';
?>
js.js:
$(document).ready(function(){
//dosomething with div's in index.php
}
So, I'll try to explain this in the easiest way. My index.php includes a build.php which as you can see calls ajax to retrieve data from another server. This data is located in a php variable ($brandinput) which will contain many <div>,<input>,... etc. Then index.php echo $brandinput, showing all the content of the variable. But I have a js.js which change appearances in div's, input's, etc.. and is this js which is not recognizing the content of the variable $brandinput.
I'd like to know if you have more ideas or what am I doing wrong...
All the code is working well, I tested many times (except for what I said before)
The ajax call work well and Index.php displays $braninput correctly.
p.s. $brandinput is something like this:
<div id='BlackBerry'><img src='..\/images\/supporteddevices\/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
and yeah it works well too.
Actually this is how it supposed to be working, what you need to do is to wait for the ajax request to finish first before executing the functions in js.js
try this way
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
//dosomething with div's in index.php
}
});
});
or (assuming js.js is loaded after the script within build.php, or js.js has to be loaded after it)
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
}
});
});
// in js.js
$(document).ready(function () {
promise.then(function (data) {
//dosomething with div's in index.php
});
});
P.S
$brandinput just hold the string whatever assigned to, and will never be changed with ajax request, where ajax success handler just manipulate the rendered DOM directly in the client side.
You can try moving your <script> tag to after your php codes like this:
<? include('build.php'); ?>
<div id="brand">
<? echo $brandinput; ?>
</div>
<script src="js.js"></script>
//....more code
On a slightly different note, you should consider avoid embedding/intermixing PHP codes with HTML and Javascript. Take a look at this post for better ways way "passing data from PHP to Javascript".