How to send variable from javascript to PHP on azure websites? - javascript

To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.

you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});

Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.

Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!

Related

Receiving data from JavaScript into PHP

Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.

Display an alert based on a json data

I am having 2 portions of code (php and javascript).
In the PHP file, I use the function json_encode() to create a JSON data which will be sent to the Javascript file.
PHP FIle
<?php
if(isset($_GET["remove_code"]) && isset($_SESSION["products"]))
{
$product_code = filter_var($_GET["remove_code"], FILTER_SANITIZE_STRING); //get the product code to remove
if(isset($_SESSION["products"][$product_code])) {
unset($_SESSION["products"][$product_code]);
}
$total_items = count($_SESSION["products"]);
if($total_items == 0){
unset($_SESSION["products"]);
}else{
//Calculate total of items in the cart
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
$product_price = $product["price"];
$product_quantity = $product["quantity"];
$subtotal = $product_price * $product_quantity;
$total += $subtotal;
}
}
die(json_encode(array('items'=>$total_items, 'total'=>$total)));
}
?>
Javascript File
<script>
$(document).ready(function(){
$(".contentwrapper .content").on('click', 'a.removebutton', function() {
var pcode = $(this).attr("data-code"); //get product code
$.getJSON( "phpfile.php", {"remove_code":pcode}, function(data) {
alert(data.items);// the total number of item
});
});
</script>
Anytime the query $.getJSON( "phpfile.php", {"remove_code":pcode}... is successful, an alert is displayed showing the data.items. The problem I am facing is that, when data.items is greater than or equal to 1 the alert is prompted, but when data.items is equal to 0, no alert is prompted.
Kindly help me solve this problem
Looks like a PHP error. $total variable is only declared inside the 'else' condition, so when ($total_items == 0) $total is undefined. But as you've called die(json_encode(array('items'=>$total_items, 'total'=>$total))); the server doesn't have a chance to complain (maybe returning no data and hence no alert). If you try declaring $total = 0 before your condition it should also fix the issue, without having to die early.
One possibility is that actually data variable is undefined/null e.t.c., see this for example, second alert is not shown. Instead an error is shown on the browser console.
var data = {items:0};
alert(data.items);
data = null;
alert(data.items);
Adding die(json_encode(array('items'=>$total_items))); at the end of the condition if($total_items == 0) and it solves the problem. But I really can't explain what is happening. Up to now I do not really know the origin of the problem. Any explanation will be welcomed

Pass coordinates via ajax to php server-side, and retrieve to javascript after they were processed

I want to transfer some coordinates to php (server-side) from javascript (client-side) via Ajax, and after processing (filter, etc) I want to retrieve the result to javascript, for use. The pass to php working, but I don't know how get and use the processed result from php. Any help is highly appreciated.
The php part script is:
$dbconn = pg_connect ("host=localhost port=5432 user=postgres password=xxxxxxx dbname=yyyyyyyy") or die('can not connect!'.pg_last_error());
//The nearest point of Start point
$ss='';
if (isset($_POST['kuldes_st'])){
$kuldes=$_POST['kuldes_st'];
$latk=$_POST['lat_st'];
$lngk=$_POST['lng_st'];
$query = "SELECT ST_X(the_geom), ST_Y(the_geom) FROM tbl_mypoints ORDER BY ST_Distance(the_geom, ST_GeomFromText('POINT($latk $lngk)', 4326)) LIMIT 1";
//$result = pg_query($query) or die('The query failed: ' . pg_last_error());
$result = pg_query($dbconn,$query);
if (!$result) {
die('The query failed: ' . pg_last_error());
}
else {
while ($line =pg_fetch_row($result))
{
$latitude=$line[0];
$longitude =$line[1];
$ss .= "L.latLng(".$latitude.", ".$longitude.")";
}
}
echo json_encode($ss);
}
Javascript code:
map.on('click', function(e) {
var container = L.DomUtil.create('div'),
startBtn = createButton('Start from this location', container),
destBtn = createButton('Go to this location', container);
nearestBtn = createButton('Find and go to nearest parking', container);
//Start
L.DomEvent.on(startBtn, 'click', function() {
control.spliceWaypoints(0, 1, e.latlng);
var lats=e.latlng.lat;
var lngs=e.latlng.lng;
$.ajax({
url : 'index.php',
type : 'POST',
async : true,
data : { 'kuldes_st':1,
'lat_st': lats,
'lng_st': lngs
},
success: function(data,response) {
if (response == 'success') {
alert("Post working fine");
alert(response);
console.log(data);
} else {
alert("Post don't working");
console.log(data);
}
}
});
map.closePopup();
});
I think the main problem is how to use return value.
in index.php file , you can return value without html tags. for example, if you wants to return array of number, just use code like this:
echo implode($array,",");
the data that return by ajax function is some things like this:
1,2,4,2
you can split this string to a javascript array with code like this:
var result = data.split(",");
after it, you can use the array result every where you want in jquery code.
My PHP is a bit rusty but I think the issue is that you are returning a string that is not JSON but trying to pack it up like JSON.
I think you want something more like
$ss = array();
while ($line =pg_fetch_row($result))
{
$latlng = array();
$latlng["lat"] = $line[0];
$latlng["lng"] = $line[1];
array_push($ss,$latlng);
}
echo json_encode($ss)
Forgive my PHP if it's wrong, but hopefullly from this you get the idea. At this point, the thing the server will return should look like real JSON like (
[
{"lat":46.5,"lng":24.5},
{"lat":46.5,"lng":24.5},
...
]
Then in the javascript, you can just deal with it like an array.
var latitudeOfTheFirstEntry = data[0].lat;
var longitudeOfTheSecondEntry = data[1].lng;
Do you know what L.latLng is supposed to be providing. This solution I've outlined is not using that and if that is needed, there maybe more work to figure out where that is supposed to happen.
Hope this helps

Something's wrong when I use $.post

Having some strange issue that I've been looking at for a couple of days now, and even with Googling can't solve.
I have this piece of JS that is called when a button is pressed. I cab tell this function really is called because the alert("1") pops up. I also know for sure the rarray is populated.
<script type="text/javascript">
function process_match() {
var rarray = new Array();
$x = $("input[name=pair]:checked").val();
$left = $x.charAt(0);
$rite = $x.charAt($x.length-1);
$car1a = document.getElementById("car"+$left+"_"+$rite+"_1").value;
$car1b = document.getElementById("car"+$rite+"_"+$left+"_1").value;
.....
$hsb = document.getElementById("hs"+$rite+"_"+$left).value;
rarray[0] = $left;
rarray[1] = $rite;
rarray[2] = $car1a;
rarray[3] = $car1b;
.....
rarray[15] = $hsb;
alert("1");
$.post("./updpoule.php",
{'results': rarray},
function(data) {
alert("2");
}
);
}
</script>
Then, I have the following php file :
<?php
$f = fopen("/tmp/q", "w");
$array = $_POST['results'];
fwrite($f,"AAA");
fwrite($f, $array[0]);
fwrite($f, $array[1]);
fclose($f);
?>
I have seen this code all over as solutions to similar problems, but I can't get it to work.
If I run the code, the alert("1") pops up. After that nothing happens. No file /tmp/q is being created. BUT, if I debug the page, and set a breakpoint where the $.post is, and then step through, a file /tmp/q IS created, just not with the right content..
Any suggestions are more than welcome.
Thanks,
Hans
Try to return something from your php script.
For example, add this to the end of the file:
echo 'OK';
?>
And, in you JS:
$.post("./updpoule.php", {'results': rarray}, function(data) {
if (data === 'OK') {
alert('ok');
} else {
console.log(data);
alert('error');
}
});
If you'll get popup with error, check the console on the data you've got from php.

Sending multiple GET variables in URL with Javascript

I'm trying to retrieve multiple $_GET variables within PHP. Javascript is sending the URL and it seems to have an issue with the '&' between variables.
One variable works:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
echo $coinSymbol
OUTPUT: LTC
With two variables:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
$type = $_GET['type'];
echo $coinSymbol
echo $type
OUTPUT: price
It just seems to ignore everything after the '&'. I know that the PHP end works fine because if I manually type the address into the browser, it prints both variables.
http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC
OUTPUT ON THE PAGE
priceLTC
Any ideas? It's driving me nuts - Thanks
UPDATE - JAVASCRIPT CODE
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load(price);
});
function refresh() {
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price).fadeIn('slow');
refresh();
}, 30000);
}
Separate the url and the data that you will be sending
var price = "http://<site>/realtime/bittrex-realtime.php";
function refresh() {
var params = {type:'price', symbol: 'LTC'};
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price, params).fadeIn('slow');
refresh();
}, 30000);
}
And in your PHP use $_POST or you can do it like this
$coinSymbol = isset($_POST['symbol']) ? $_POST['symbol'] : $_GET['symbol'];
Refer to here for more information jquery .load()

Categories

Resources