I want to send POST request with jquery AJAX to PHP function
but it don't give any respond.
JQuery
$.ajax({
url: 'ListProduk.php/SelectData',
type: 'POST',
success: function(data)
{
console.log(data);
}
});
PHP
<?php
include 'database.php';
function SelectData(){
$sql = "SELECT * FROM MsProduk";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
return json_encode($arr);
}
?>
Any ideas how to fix it?
When not using url rewriting (google mod_rewrite and pretty URL's), your parameters typically are going to be passed as a normal HTTP GET request. Here is an example of how your URL structure might look:
url: 'ListProduk.php?action=SelectData'
And then, in your PHP, you might handle it based on the action that is requested (Note: The action parameter is not something specific to web development, it's just an arbitrary name I assigned. It could be foo=SelectData as well)
if ($_POST['action'] == 'SelectData') {
// Run the code for selecting data
}
Finally, you wouldn't want to "return" the JSON data. You need to output it with the correct headers. It would look something like this:
header('Content-Type: application/json');
echo json_encode($data);
Related
Hello I tried to transfer variable from ajax to php, but php file keeps throwing me the following:
Undefined index: vals in /Applications/XAMPP/xamppfiles/htdocs/fang_sophie/project/sign in-out/bin/readall2.php
Ajax reads like this:
<script>
var var_data = "Hello World";
$.ajax({ url: 'bin/readall2.php',
data: {'vals' : var_data},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
</script>
Php reads like this:
<?php
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
?>
Why doesn't it work? Please help :)
One problem here is that you're trying to output JSON dataType:'json', where you don't have JSON to start with. Consult my footnotes also.
You need to use a text data type.
dataType:'text',
By the way, this won't echo anything at all (in the alert), since $hello is empty:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
You (may) want to echo the session array taken from the POST array, which is the logical thing to do:
echo($_SESSION['hello']);
Reference:
http://api.jquery.com/jquery.ajax/
Foonotes:
If by any chance you may be trying to access that (PHP) file directly, or your entire code is in the same file, then you need to use a conditional statement for it.
I.e.:
session_start();
if(!empty($_POST['vals'])){
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($_SESSION['hello']);
}
That, and/or use two separate files.
In regards to JSON; if you really want/need to use it, then set it back to dataType:'json', but use json_encode() for it and replacing echo($_SESSION['hello']); with and assigning the $hello variable to the session array:
$hello = $_SESSION['hello'];
echo(json_encode($hello));
<?php
//first start session
session_start();
//set header to json and UTF-8 encoding
header('Content-Type: application/json;charset=utf-8');
//check if $_POST['vals'] is set first using isset() to prevent notice
//undefined index
if(isset($_POST['vals'])){
echo "value of vals is: ".$_POST['vals'];
}else{
echo "vals not set";
}
?>
In your ajax request, the format of return is expect to be JSON. and you are returning a string.
You just need to add json_encode in your return line of php:
session_start();
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo(json_encode($hello));
The correct answer is you are reading the wrong variable:
$hello = '';
$_SESSION['hello'] = $_POST['vals'];
echo($hello);
It should be:
echo $_SESSION['hello'];
If you want the session data. For the undefined index, var_dump out your $_POST variable: var_dump($_POST);
If the $_POST variables do not match, or you get back an empty array, it was never transmitted to the server.
Original wrong answer:
When JQuery has "processData" flag set to false, it doesn't encode the data and requires the user reads it from the php://input stream.
Unencoded JSON is not sent into POST requests. For the quickest fix, try this:
parse_str(file_get_contents("php://input"), $vars);
// This will fill $vars with any data sent over to PHP.
var_dump($vars);
$vars should now be populated with the data you want. If $vars is empty, you are not transmitting the data.
I want to pass the results of a query to javascript (I want to make an interactive quiz about fish species). This seems to be easy with json_encode, but the structure of my php array makes it difficult to access? Even console.log does not work, so there is probably an error, though I have been checking this code more than i would like to admit. I am pretty sure the error is in the small javascript part though. The code (this is all in a .php file):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<?php
$con = new mysqli("localhost", "root", "", "marinefish");
$query = "SELECT Commonname, Scientificname FROM allseafish";
$result = $con->query($query);
while ($row = $result->fetch_array()){
$rows[] = $row;
}
/*
Structure rows:
array(544) {
[0]=>
array(4) {
[0]=>
string(7) "Allfish"
["Commonname"]=>
string(7) "Allfish"
[1]=>
string(11) "Omni pisces"
["Scientificname"]=>
string(11) "Omni pisces"
}
*/
mysqli_free_result($result);
mysqli_close($con);
?>
<title>Untitled</title>
</head>
<body>
<script type="text/javascript">
var ars = <?php echo json_encode($rows) ?>;
console.log(ars);
alert(ars[0][0]);
</script>
</body>
</html>
Any suggestions, or easy-to-understand links/ tutorials are very welcome!
I tried: http://www.dyn-web.com/tutorials/php-js/json/multidim-arrays.php which seems very clearly explained, but couldn't help me. I also have tried to simplify the structure of the php array, but without success.
And I tried to change the echo json_encode($rows) into print(json_encode($rows)).
As you may have noticed, I am new with this, so all basic tips will be a great help.
Thank you!
A better solution would be to separate your javascript from PHP through post/get requests by creating a new PHP page (e.g. Query.php) that is specific for Database response:
... MYSQL CODE ...
echo json_encode($rows); // Echo everything into body
And Using jQuery (or equivalent Ajax request):
$.ajax({
type: "GET",
url: 'query.php',
dataType: "json",
success: function(your_php_reponse_as_json){
console.log(your_php_reponse_as_json);
}
});
Note that this code will be essentially asynchronous as the request for the MYSQL Query is sent in another page using async JavaScript. Additionally you can customize your query reponse with $_POST & $_GET:
PHP Code:
$get1 = $_GET['js_sent'];
// Alternatively
$post1 = $_POST['js_sent'];
Edit: You'll need to serialized data before sending.
For the complete jQuery solution refer here jQuery Ajax POST example with PHP
$.post("checkproduct.php", {"useremail" : emailVal}, function(data) {
//use data returned from checkproduct.php.the value returned from checkemail.php is retrieved as data.
});
The above code post method to post variable to checkproduct.php here we are passing useremail and the value is emailVal and this is also a variable. and in checkproduct.php you need to echo/return your result. and resultant data can be use in the function as data
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;
Im trying to trying to return a PHP variable which is made of a SQL query to the same database using jquery.
At the moment my method does not work but i cant figure out why. Currently getting the following messages on the PHP response along with the error alert configured in the js function:
Warning: Illegal offset type line 55
{"average":null}
Im very new to PHP and server side programming, so an explanation of where i am going wrong would be really good. I am sure it is just a really simple misunderstanding i have with how i am going about this.. its baffling me so far though!
javascript function to make ajax call to PHP page
so here i have defined an array and added 2 values to it to post to the PHP page.
once recieved i want PHP to change the value to one it will get by doing an SQL query
var javascriptvalue = []
javascriptvalue["id"] = "the id";
javascriptvalue["name"] = "the name";
function averageRecall() {
$.ajax({
type : 'POST',
url : 'recall.php',
data: JSON.stringify(javascriptvalue),
dataType : 'json',
success : function (result) {
console.log(result); // see too what we get in the request
console.log(result.average);
},
error : function () {
alert("error");
}
PHP:
Here PHP should run a query against the DB and return a single value into the variable $avg which will be passed to an array, coded to JSON and then echoed back into my JS callback function.
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$avg = $conn->query("SELECT AVG(`Answer`) AS AvgAnswer
FROM (
SELECT `multi1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi5` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio5` AS Answer
FROM `zc_Answers`
) AS s1");
if (!$avg) {
echo 'Could not run query: ' . mysql_error();
exit;
}
header('Content-Type: application/json');
$avg2 = array('average' => $_POST[$avg]
);
echo json_encode($avg2);
$conn->close();
?>
First , try adding this to your php file because it doesn't return a JSON response :
header('Content-Type: application/json');
$avg = array(
'average' => $avgcalculation // you can try sending just a number to see if the script works excluding your query
);
echo json_encode($avg);
then , in your success function of javascript you have :
dataType : 'json',//So we need to do the header() step in php
success : function (result) {
console.log(result['average'])// ???????
},
You try to get an item of a javascript array by string index ... which is not possible.
1) You write dataType:json <<< So, the result variable is a object ! So you can access average value with :
success:function(result){
console.log(result); // see too what we get in the request
console.log(result.average); // thats all
}
UPDATE : in order to help you ._.
your php script is failing too because you are retrieving POST values that doesn't exist because you are not sending them !
Please read the documentation of $.ajax() here.
Try first with a simple script in php to see if your javascript works. Comment everything just let 2 lines.
header('Content-Type: application/json');
$avg = array(
'average' => $_POST["javascriptvalue"]
);
echo json_encode($avg);
then in your javascript file add the data tag (because you need to retrieve data in your server !)
data:{
javascriptvalue:"I'm sending this to php so it can be retrieved in my php script"
},
Finally your success javascript function should be executed without problem with :
success:function(data){
console.log(data);//an object with average property (data.average)
}
It should work anyway this is not dificult, read the documentation
"data: avg" in the Ajax call is the data you want to send to the PHP (your page form values) that's why "avg" needs to be defined in the javascript before making the ajax call, that's why you get "avg is undefined".
You need to create the variable and somehow fill it with the form values.
For the PHP if it is on a server you need to work a little bit more like Carlos explained.
I give you some example code from a project I'm working on:
JS CLIENT SIDE
//jsonvar is an array
jsonvar["id"] = "the id";
jsonvar["name"] = "the name";
$.ajax({
url: url_webservice,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(jsonvar), //turn jsonvar into json to send to the php server
})
.done(function(result) {
console.log("Show the result from the PHP in the console", result);
// Do all you want with the result
})
.fail(function(err) {
console.log(err.responseText);
// Do all you want in case of error
});
});
PHP SERVER SIDE
header('Content-Type: text/html; charset=utf-8');
//Get the data from the POST
$input_data = json_decode(file_get_contents("php://input"), FILE_USE_INCLUDE_PATH);
if(is_null($input_data))
{
trigger_error('Error empty input data in server.php', E_USER_WARNING);
}
//Do what you want with input data, sorry not familiar with mysql code.
echo json_encode($result); //Back to the client
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