Can't get PHP variable to JavaScript file using AJAX - javascript

While looking at tons of examples of how to get a PHP variable sent to a JavaScript file, I still haven't had success getting it.
My PHP file is:
$title = $json["title"];
echo json_encode($title);
And my JavaScript file app.js is:
$.ajax({
url : 'index.php',
type : 'GET',
data : film,
dataType : 'json',
success : function (data) {
alert(data.title);
console.log(data.title);
},
})
I would like to know the right code to get the PHP $title variable to the ajax call in app.js.
Thanks

For this example there are two files. One has the JQuery ajax method. The other file is a PHP script that returns the requested information.
show_title.html
<!-- JQuery library already loaded -->
<script>
$.ajax({
url : 'get_title.php', // requesting a PHP script
dataType : 'json',
success : function (data) { // data contains the PHP script output
alert(data.title);
console.log(data.title);
},
})
</script>
get_title.php
<?php
$json["title"] = 'a title';
echo json_encode($json);
?>

If you'd want a .title property on the response, then you should create an array then encode that instead. You got the other way around. Something like this:
PHP
<?php
$title = 'Yahoo!';
$json['title'] = $title;
echo json_encode($json);

Related

Passing variable from JS using ajax to PHP undefined variable

I want to pass variable rating_index to the PHP code and send to database. Rating_index is set I'll not pass the code here because it is long, but right before AJAX i console.log(rating_index) and it has value(int). Add-review is a button that after click should send variable. In js script I am using AJAX :
$('#add-review').click(function(){
$.ajax({
url:"rating-data.php",
method:"POST",
data: {
rating_index: rating_index
},
success:function(data)
{
console.log(data);
}
})
}
in my php file rating-data.php:
<?php
include 'connection.php';
echo "work";
echo $_POST["rating_index"];
?>
I got a console.log ('work') from PHP file and this error:
Notice: Undefined index: rating_index in /Applications/XAMPP/xamppfiles/htdocs/bookwarm-app/rating-data.php on line 4
So it is getting my to php page but the variable are not passing correctly.
I was trying everything and I have no idea what is wrong and why this variable is undefined in php file. Thanks for any clue
This is the problem in your code, sir
$user_name = $_GET["user_name"];
$user_rating = $_GET["rating_index"];
$user_review = $_GET["user_review"];
you're doing a $_POST request from Ajax and in php file you're getting values from $_GET.....?

Trying to use AJAX to grab parameter of function and pass to PHP code

I have an HTML input with a function and parmeter set to it like so
<input onclick='myFunc($count)' type='button' value='ClickMe'>;
I also have script references to JQuery and my script file
<script src="jquery.js"></script>
<script src="myscript.js"></script>
Inside my myscript.js file I have the contents as such
function myFunc(x) {
alert(x);
$(document).ready(function() {
$.ajax({
url: "myphp.php",
method: "post",
data: { param1: "x" },
dataType: "text",
success: function(strMessage) {
}
})
})
}
Here is my myphp.php file
<?php
$param1 = $_GET['param1'];
echo $param1;
?>
As you can see in the javascript file, I have alert(x); to test that the function is grabbing the $count variable and so far that is working (the correct value appears in the alert box). However, I want to pass that x parameter to the PHP script but my PHP script won't echo anything, I assume the line where I have param1 is wrong. Any tips?
In your AJAX call you are using a POST method, so in order to catch the variable in PHP you need to access it from $_POST:
<?php
$param1 = $_POST['param1'];
echo $param1;
?>
You're making the XHR with POST method
method: "post",
and youre looking for it in the GET array
$_GET['param1'];
Change either to post or get (keeping in mind your scenario) and you should be good imo.
read more here to know about the different methods of sending http requests: https://www.guru99.com/php-forms-handling.html
You are using post method in AJAX but trying to grab the value in $_GET which is wrong.
In your PHP code, just replace $_GET['param1'] with $_POST['param1'] and it works.
or If you like to use $_GET in your PHP code then change the method in AJAX or use $.get. Examples can be found on W3School.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp

Echo php content into API javascript?

I would need to echo php variables (from the server and related to service behaviour) into javascript. For example, "ssl" => "true" and adapt accordingly in javascript. The thing is I'm doing this for some API files I'm writing and I want the client to have direct access to these files (<script src="... .js">) and this forces me to hardcode info that might change in the future across multiple file references. What I'd like to do was something like this, is it possible? (the content to fetch must remain completely private - from the server folders to the php script files - and so it is really not an option to fetch this info using javascript):
api.js
<? //PHP here. (I know...)
(...)
?>
//some javascript
var is_secure = <? echo "true"/"false" ?>
(...)
So that when doing <script src="api.js"/> the user only fetches:
var is_secure = "true";
(...)
or
var is_secure = "false";
(...)
Any idea on how I could do something similar? Thank you very much...
You could just create your PHP file with this line before everything :
header("Content-Type: application/javascript");
EDIT:
I did misunderstood the question. If you want js in an php file, you should do it like this:
header("Content-Type: application/javascript");
OLD ANSWER:
I don't know if you know, but client can't see your php code...
So if You'd:
echo "Something"
The client would only see Something.
It's not clear, what you're trying to do...
If you don't want to see Something when you go directly into your "secret" php page, then you should do it like this:
JS:
jQuery.ajax({
type: "POST",
url: 'secretfile.php',
dataType: 'html',
data: {apiRequest: 1},
success: function (response) {
yourVar = response;
}
});
PHP:
If ($_POST['apiRequest']==1){
echo "Something";
}
yourVar would be = "Something"
If you'd go to this page, it wouldn't display anything;

How to use AJAX and JSON to get data returned from a PHP file

For starters this website is being run on a Debian machine.
I have a SQLite3 database that has current news articles in it. I am trying to use PHP to query the database for these articles, and pass it as JSON to AJAX, so it can be displayed on my webpage. Right now nothing is being shown and I don't know where the error is.
Here is the PHP code to get the information from the database:
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('website.db');
}
}
$db = new MyDB();
$result = $db->query('SELECT * FROM news');
echo json_encode($result);
?>
Here is the JavaScript where the AJAX is located:
<script type="text/javascript">
function getNews()
{
console.log("firstStep");
$(document).ready(function()
{
console.log("secondStep");
$.getJSON("http://localhost/getNews.php",function(result){
console.log("thirdStep");
$('news').append(result); // display result
});
});
}
I think the error is occurring around $.getJSON("http://localhost/getNews.php",function(result), as in the console, thirdStep is never being outputted.
This is the HTML it should be appending to:
<div id = "newsEntry"> <news> test </news> </div>
Any help would be appreciated.
To find out what's going on, you might want to add an error handler:
$(document).ready(function() {
$.ajax({
url: "http://localhost/getNews.php",
dataType: "json",
success: function(result) {
console.log("thirdStep");
},
error: function(err) {
alert(err);
}
});
})
By default, the web server serves content as application/html. So when you simply echo a JSON string, it's treated like text on a html page. To really return JSON from your server, you need to specifically set it.
Include this line before your echo:
header('Content-Type: application/json; charset=utf-8');
Edit
On inspection of you PHP code, you are missing one line. Note that $db->query() returns you an SQLite3Result. You need to call:
$array = $result->fetchArray(SQLITE3_ASSOC); // get an associative array first
$json = json_encode($array);
header('Content-Type: application/json; charset=utf-8');
echo $json

Using Ajax to require different php page

I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');

Categories

Resources