Retrieving JS data in PHP - javascript

I am recording the information using the data() method
optionScope.data().stage = 'a';
where optionScope = $(this);
where I would like to store this value in my php code:
<?php
include("functions/db.php");
$format = "Online Course";
$stage = GETTING THIS DATA;
$topic = "Idea Generation";
$resources = "select * from resources where format LIKE '".$format."' and stage LIKE '%".$stage."%' ";
$run_query = mysqli_query($con, $resources);
while($row = mysqli_fetch_array($run_query)) {
$stage = $row['stage'];
echo "$stage <br>";
}
?>
Update:
How the data is being sent
optionScope.data().stage = 'b';
$.ajax({
url: "functions/contact.php",
type: "post",
data: {stage: optionScope.data().stage}
});
How the data is being retrieved
<?php
$stage = $_POST['stage'];
echo $stage;
?>

you can use the AJAX method. This is the only way you can transfer your JS data into PHP script.you will get the Jquery data in GET or POST variables.
jQuery AJAX has the various method you can choose as per your requirement.
http://api.jquery.com/category/ajax/

You can't directly transfer data between JS and PHP (unless you use string interpolation inside <script> tags which is a big no-no), since JS deals in the client-side and PHP on the server-side.
You need to make a request to the server and then manipulate the data there.
Take a look at AJAX requests.
For the easiest implementation of this, see JQuery's AJAX method.

Related

how to decode jQuery json data posted to php

I have a web page that sends form data to php using jQuery. I want to decode the data array and loop through it, displaying each of the four values using php print_r.
Here is the jQuery function to post the data to php:
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
</script>
Here is the php function echo_test:
<?php
$obj = json_decode($_POST['post']);
print_r($obj['firstname']);
?>
I think json_decode is wrong because the data posted is not json format.
When I click the button that calls the jQuery function, the php page opens in the browser but it's blank, with nothing echoed back. Ideally I would I loop through $obj to display each of the four values on the screen.
Ultimately I will post the data to Postgres on a cloud server. For now, I'm testing it locally to verify the data because I'm new to passing data to php from jQuery.
Thanks for any help with this.
What you need to do is use parse_str, but correctly:
<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>
form.serialize() send data in query string format. The parse_str() function parses a query string into variables.
<?php
parse_str($_POST['post'], $obj);
print_r($obj);
?>
What you need to do is use parse_str:
https://php.net/manual/en/function.parse-str.php
<?php
parse_str($_POST['post'], $obj);
print_r($obj['firstname']);
?>

Pass javascript class to php as json / alternative way

I am beginner in this stuff, but I am learning quite quick so I would appreciate any kind of help.
On example i have something object like
function shape(name, size)
{
this.name = name;
this.size = size;
// some functions
}
and I am creating an array of this (this is just example)
var shape1 = new shape("Square", 10);
var shape2 = new shape("Circle", 5);
var array_of_shapes = [shape1, shape2];
I need to send all shapes (name and size values in this case) into php in json or any other format that will allow me to send it to MySQL database
I don't know how jQuery / Ajax works, so I am trying to avoid this way if possible
I am not sure if title is correct when I am calling this a "class" actually
When you got shapes values in array.. now you can send all values on server using AJAX..
$.ajax({
url: 'http://www.domain.com/xyz',
dataType: 'json',
data : JSON.stringify(array_of_shapes),
success: function(data){
//server response in data variable
}
})
and on the server side you can receive json data as
<?php
$json_data = file_get_contents("php://input");
$json_array = json_decode($json_data, true);
echo '{msg: "data posted"}';
die;
?>
kinldy follow and check the link hopefully you will get to understand what you are trying to achieve.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_native_JSON
after value get returned as json you can save it to PHP variable.

How to convert javascript variable into php variable?

Im new in programming and Im trying to make a program that would register a selected space in my database. I want to convert js variable str into $phpvar php variable. Please help me
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
<?php
include "accounts/config.php";
$phpvar='"+str+"';
mysql_query("INSERT INTO sample (sample) VALUES ('".$phpvar."')");
//echo $phpvar;
?>;
})
});
As the previous speakers already explained, you need to think in terms of client-side running code and server-side running code.
Whenever you want to share a state between those two parts of your application you need some communication mechanism.
Client -> Server
For this you need to make a HTTP request. This can either be a post or a AJAX call. For the latter one just have a look at jquery.ajax as you're obviously already using jQuery anyway.
$.post({
"savesample.php",
{myPostVar: str}
}).done(function() {
alert("sample saved.");
});
Of course you need a serverside script to handle this request:
<?php
$yourVar = $_POST["myPostVar"];
// TODO use mysqli::escape_string or similar!!
mysql_query("INSERT INTO sample (sample) VALUES ('".$yourVar."')");
?>
Server -> Client
This is a lot easier. You can of course use ajax again (GET requests on your php file, which generates a nice javascript-compliant output like JSON).
Or just write your variable to an inline-script-tag:
<script>
<![CDATA[
var yourJsvar = '<?= $yourPhpVar ?>';
]]>
</script>
Further Reading
As your php file is an open gate for all kinds of misuse you should secure it using one-time authorization tokens. Once you are used to the basic concepts, go on with the following topics:
CORS
SQL injection
Authenticated AJAX calls
You'll want to POST to a PHP listener. You don't want PHP tags inside of a JS function in this way. The only reason for PHP tags inside of a JS function would be if you were getting data from PHP to JS, not the other way around.
Look up Jquery post for more information.
The order in which languages run is PHP -> HTML -> CSS -> Javascript. You can NOT go backwards from that order.
On the other hand, you can send Javascript information through an AJAX call. AJAX is an Asynchronous Javascript call which can communicate with PHP!
So for instance (using JQuery)
$.ajax({
url:"someurl",
type:"POST or GET",
data:{query:"SELECT * FROM table"}, //Any data to pass along? Like strings or data?
datatype:"JSON", //This is the return type of the information you want if any
success: successfulHandlerfunction()
error: errorHandlerfunction()
});
That is just some basic grounds. You can find more information on AJAX calls through http://www.w3schools.com/ajax/
I hope this helps!
JS
$('#btnShowNew').click(function () {
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
str.push(item);
});
$.ajax({
type: "POST",
url: "save.php",
data: {items: str},
success: function(responce) {
alert(responce);
}
});
});
Create save.php file
<?php
include "accounts/config.php";
$items = $_POST['items']; // Validation HERE!!!
foreach ($items as $item) {
// Insert to DB
}
echo 'Saved';
?>
Separate languages = separate files. (if you can...)
In PHP always check user input.
Use PDO.
This is not possible because the js code is client side and php is server side. What you would need to do is to make an ajax request to a php script in order to send the data for the variable. Here is an example:
Client(browser):
$.ajax({url:"http://domain.com/accounts/config.php?variableToSend=variableValue",success:function(result){
alert("Variable was successfully sent.");
}});
Server(Apache)
config.php
<?php
$varToSend = $_GET["variableToSend"]
//Do whatever you want with the variable
?>

Run JavaScript from PHP from Ajax

Is it possible to run a JavaScript function from PHP using an Ajax call.
For example, if I have a html page in php with an ajax call. The ajax post gets sent to a php engine:
index.php
<script>
Ajax.post('http://example.com/ajaxEngine.php', { data: "someData" });
</script>
Then in the PHP engine, can I run a JavaScript function like this:
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
<script type="text/javascript">
var php_var = "<?php echo data ?>";
function doSomething(php_var) {
// do something with data
}
</script>
Lastly, If the JavaScript function needs to return a value, how would you then transfer that back to php? Could I post to the same page and then get it as a variable with PHP?
Short answer: No.
Your code in ajaxEngine.php would just output that snippet of javascript. This will be transfered back to your page, so you could insert it into a script tag or eval it, if you like it to execute. But this would then happen on the client side not on your server. The script would have the dynamic data from the php, though. So if this is everything you need, it would work that way.
Beware: That would NOT hide your script. It would be visible for any client.
Try this function
function includetext(text,onlyone)
{
var d=document.createElement('script');
if(onlyone)
{
var ds=document.getElementById('onlyonesscript');
if(ds)
removeElement(ds);
d.id='onlyonesscript';
}
d.innerHTML=text;
document.body.appendChild(d);
}
text - returing text of script from ajax.
onlyone use for just one script node, this will help you.
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
var php_var = "<?php echo data ?>";
// do something with data

$jquery.post() PHP and Mysql

So I half got jQuery's ajax ($.post) to work. But, for some reason, I haven't been successful with finding the right online article to explain to me how PHP retrieves the ajax data that is sent. I've found some stuff on json_decode, but upon me doing that to basically decode it, it wont work (and yes, I am using json for the $.post command).
Here is my javascript code
$.post("notificationNum.php", {"user":"1"},
function(data){
$(".example-number").html(data.amount);
}, "json");
Here is my PHP code
<?php
session_start();
//link to db info here
$user_id_got = json_decode($_REQUEST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>
Mind you all, I've also tried using the $_POST command instead of the $_REQUEST. Any ideas how to send data to the PHP file so I can use it?
"json" in your jQuery call is how your php should write its output, not how jQuery sends it. Use normal $_REQUEST in your php:
$user_id_got = $_REQUEST['user'];
try this
notificationNum.php
<?php
//link to db info here
$user_id_got = intval($_POST['user']);
$checknoti = mysql_query("SELECT * FROM notifications WHERE notification_users = '".$user_id_got."' AND notification_viewed= '0'");
echo json_encode(array("amount"=>mysql_num_rows($checknoti)));
?>

Categories