How to receive data in php sent from javascript [duplicate] - javascript

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am sending some data from my pain page to app.php using javascript
$(document).on('click', '.app' , function(){
var data=$(this).attr("id");
window.location="application/app.php?data="+data; //data send in this statement
});
my php code is this :
<?php
if($_GET['data'])
{
echo $app_id=$_GET["data"]; receiving data
}
?>
It works sometime but now it is giving Notice in an alert box: Undefined index data in app.php. But it is showing the echo.
I want to know how I can receive the data I need using $_POST or $_GET. like we receive by making an Ajax call. But I haven't specified something like this in Javascript. is there any way to this?
I want to clarify that the data exists and it is non empty because echo is successfully printing that on the page

Try this:
<?php
if(!empty($_GET['data']))
{
$app_id = $_GET['data']; // receiving data
}
?>
Please be aware that passing data without validation is not secure. Reccomended reading: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project

use isset() to first check if the key exists. data won't exist in $_GET when it's not passed via a parameter in the url
you probably want some logic that looks like this:
if (isset($_GET['data'])) {
if (!empty($_GET['data'])) {
$appId = $_GET['data'];
}
else {
// data exists, but it's empty
}
}
else {
// data does not exist
}
and maybe you even want to check if it's a valid id, like being numeric or something

Related

How to receive echoed data from a php file via URL? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to get some basic Javascript and PHP working for a coding challenge I'm taking part in and I need to receive a JSON object from a PHP file to use in my Javascript that displays the current date on a HTML page. I've tried a few different methods and can't seem to get any to work, is there something I'm missing here?
I've tried using jQuery getJSON as well as running the PHP in the same HTML file as the Javascript.
This is the PHP file and its output:
echo json_encode([
"date" => getthedate()
]);
function getthedate() {
return date("Y/m/d");
}
{"date":"2019\/07\/04"}
This is what I've most recently been trying in Javascript:
function getDate() {
var theDate = $.getJSON(
"http://localhost/coding-challenge/get-date.php",
function(data)
);
JSON.parse(theDate);
document.getElementsByClassName("date")[0].innerHTML = theDate;
}
I was expecting this Javascript to retrieve the JSON object that the PHP file echoes and then display it in the HTML file's "date" class, an empty paragraph. However this just results in a blank space where the date paragraph is.
$.getJSON is asynchronous, so you should set the data inside it's success callback:
function getDate() {
$.getJSON("http://localhost/coding-challenge/get-date.php", data => {
document.getElementsByClassName("date")[0].innerHTML = data;
});
}
Try to send the correct HTTP resonse header for JSON. Then jQuery will parse the response for you.
header('Content-Type: application/json');
echo json_encode([
'date' => getthedate()
]);
function getthedate() {
return date("Y/m/d");
}
JS
$.getJSON("http://localhost/coding-challenge/get-date.php", function( data ) {
console.log(data);
alert(data.date);
});

Passing a Jquery array of objects into a php array

I have an array in jQuery that I am trying to convert to a PHP array by using Post:
$.post("http://www.samepage.com", {final_slip: JSON.stringify(final_slip)});
When I pass this dynamically created array "final_slip" into it :
[final_bet_game { final_user_id="1", final_game_id="1", final_game_type="spread_2",final_price="10", final_odds="1.8"}, final_bet_game { final_user_id="2", final_game_id="3", final_game_type="spread_2",final_price="1", final_odds="2.8"}, final_bet_game { final_user_id="3", final_game_id="14", final_game_type="spread_32",final_price="140", final_odds="1.8"}, final_bet_game { final_user_id="4", final_game_id="1", final_game_type="spread_2",final_price="10", final_odds="2.8"}, ]
I get this php outputted :
$data = $_POST['final_slip'];
print_r ( $data);
[{\"final_user_id\":\"1\",\"final_game_id\":\"1\",\"final_game_type\":\"spread_2\",\"final_price\":\"211\",\"final_odds\":\"1.8\"},{\"final_user_id\":\"1\",\"final_game_id\":\"2\",\"final_game_type\":\"spread_2\",\"final_price\":\"212\",\"final_odds\":\"1.8\"},{\"final_user_id\":\"1\",\"final_game_id\":\"parlay\",\"final_game_type\":\"\",\"final_price\":\"021\",\"final_odds\":\"\"}]
I tried to use the json_decod, but Im not getting any results. How can I get this to a usable php array? Would I be better off using ajax?
$.post("http://www.samepage.com", {myJsonString: JSON.stringify(myJsonString)});
But when I then try to access it in PHP I am not seeing any results.
And that tells you that you have another problem - PHP is not reporting errors. You want to turn error_reporting on.
In this case the likely cause is that your data is arriving into the $_POST array, and $myJsonString is not defined (automatic definition of parameters has been deprecated since PHP 5.3.0, and no longer available since PHP 5.4.0).
You should either do
if (array_key_exists('myJsonString', $_POST)) {
$myJsonString = $_POST['myJsonString'];
} else {
die("myJsonString not in _POST");
}
or try straight
$result = json_decode($_POST['myJsonString'], true);
The problem was the backslashes in the outout needed to be stripped out:
$result = $_POST['json_string'];
$test = urldecode(str_replace("\\","",$result));
$test2 = (json_decode($test,true));
print_r($test2);

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

How to call php codes inside javascript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I want to check the inputs of a form if they are empty and then i want to use php codes for user registeration.
<script>
$('#submitbutton').click(function(){
if($('#usernameinput').val() == ''){
alert('Input is blank');
}
else {
//here i want to use php codes for example;
$bgl = new mysqli("localhost", "root", "", "users");
if ($bgl->connect_errno) {
echo "Failed to connect to MySQL: (" . $bgl->connect_errno . ") " . $bgl->connect_error;
}
$username = mysql_real_escape_string($_POST['username']);
.....
.....
..... /and so on..
}
});
</script>
In this case you most likely want to use $.ajax() to call a PHP page that supplies this information.
jQuery.ajax()
There is no such thing as php and javascript working together like that. Javascript in run on client side and php is run on server side. The best you can to is to pass and retrieve values to and from a php page and then use those values as intended.
You have a few options here. The first is to post the form to a PHP page after the JavaScript validations (just use the form action) or use Ajax and call the PHP page, as Robin says.
That's not posible, you can embed javascript into php code but not vice versa.
The best way to implement that is developing a REST service and retrieving data with AJAX.

Using PHP in javascript's IF Statement [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to make a confirm box which will desire which php code will be executed.
Heres my code:
<script type="text/javascript">
var answer = confirm('Are you sure?');
if(answer==true)
{
<?php $confirmation = 1; ?>
}
else
{
<?php define("CONFIRMATION", 1, true); ?>
}
alert('<?php echo $confirmation; ?>')
alert('<?php echo defined("CONFIRMATION"); ?>')
</script>
The problem is , even if i click YES, $confirmation and boolean from defined() function returns 1.
Whatever I click, (cancel or ok) one of them should be 0 (I've already declared $confirmation before)
But both of codes at if and else blocks are used!
Normally it works like this
You fundamentally misunderstand what PHP is doing.
PHP is evaluated on the server before the page is sent to your browser. By the time the browser sees it and executes the javascript, all the PHP is gone.
Use your browser's "view source" on the browser window with this code in it. You'll see it looks like this:
<script type="text/javascript">
var answer = confirm('Are you sure?');
if(answer==true)
{
}
else
{
}
alert('1')
alert('1')
</script>
You either need to implement what you want to do in javascript to run on the browser, or you need to send a new request to the server and get a new page back (either directly or indirectly) with your response.
That will never work because PHP is processed before the output is sent to the browser. If you really need to modify something in PHP then try using an AJAX call.
http://ajaxpatterns.org/XMLHttpRequest_Call
Or try using jQuery's $.ajax(); function. Start by looking here.
Here is a quick example:
<script type="text/javascript">
var answer = confirm('Are you sure?');
$.ajax({
type: 'GET',
url: '/path/to/script.php',
data: 'answer=' + answer,
success: function(response) {
alert(response);
}
});
</script>
Contents of script.php:
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
// ...
}
You can't trigger a PHP code exection without a post/get request.
For your needs, you should choose between a form submisssion or load a page-link with parameters stuffed in the query string on confirmation.
P.S.
the query string parameters are the ones following the "?" in the format variable=value
for example:
index.php?answered=1
you will be then able to retrieve these vatiable/values using PHP $_POST, $_GET or $_REQUEST variables in a way like this:
if ($_REQUEST['answered'] == 1) { //confirmed
...
}
You are misunderstanding the order of what will happen here.
Firstly, PHP will output the javascript layer. Your if block will then look like this:
if (answer == true)
{
}
else
{
}
The javascript engine should then optimise that out and totally ignore it. Consider using AJAX if you need to get PHP to process something with an input from the javascript layer.
Normally it works like this
No, it never works like this. PHP is executed before the javascript so it will never work like this.
I think from what I see you would want something like
Your link
This will go to the current page with $_GET['confirmation'] set to "1".
php executed before javascript so you can't do this because
when you check it via javascript if else statement php is already executed so you can't do it
but however you can use ajax for it

Categories

Resources