Fetch variable from php with javascript - php

I have a php file which contains the following code:
function render() {
//fetches all the data from input.
$date = date("Y-m-d H:i:s");
$con = mysql_connect("127.0.0.1","root","");
$database = mysql_select_db("guestbook");
$name = $_POST['name'];
$email = $_POST['email'];
$post = $_POST['post'];
$sql = "INSERT INTO gast(name, email, post, date) VALUES('$name','$email','$post','$date')";
$input = mysql_query($sql);
mysql_close($con);
}
With javascript, I'd like to retrieve those variables, something like this:
document.getElementById('button').onclick = clicked;
function clicked() {
var name = document.render.name.value;
var post = document.render.post.value;
var email = document.render.email.value;
}
I have included that javascript code in my body, but it doesn't work. How do I get the value?

Use AJAX. With jQuery you can get any data from the server very easy.
$.get('test.php', function(data) {
alert(data);
});

You can't really, unless the js and php code is on the same page, then you could do
var namn = "<?php echo $name; ?>";
but unless the php is passing the variables to the file that your js is in, you can't really do anything.

Related

PHP/MySQL/AJAX - Refresh query values with AJAX

I want my header to be consequently refreshed with fresh values from my database.
To achieve it i have created an AJAX post method:
AJAX (edited):
$(document).ready( function () {
function update() {
$.ajax({
type: "POST",
url: "indextopgame.php",
data: { id: "<?=$_SESSION['user']['id']?>"},
success: function(data) {
$(".full-wrapper").html(data);
}
});
}
setInterval( update, 5000 );
});
It should pass $_SESSION['user']['id'] to indextopgame.php every 10 seconds.
indextopgame.php looks like that:
PHP PART (edited):
<?php
session_start();
$con = new mysqli("localhost","d0man94_eworld","own3d123","d0man94_eworld");
function sql_safe($s)
{
if (get_magic_quotes_gpc())
$s = stripslashes($s);
global $con;
return mysqli_real_escape_string($con, $s);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$id = trim(sql_safe($_POST['id']));
$data = "SELECT username, email, user_role, fbid, googleid, fname, lname, avatar, energy, energymax, health, healthmax, fame, edollar, etoken, companies, workid, city, function FROM members WHERE id = $id";
$result = mysqli_query($con, $data);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$_SESSION['user']['user_role'] = $row["id"];
$_SESSION['user']['fbid'] = $row['fbid'];
$_SESSION['user']['googleid'] = $row['googleid'];
$_SESSION['user']['created'] = $row['created'];
$_SESSION['user']['lastlogin'] = $row['lastlogin'];
$_SESSION['user']['username'] = $row['username'];
$_SESSION['user']['fname'] = $row['fname'];
$_SESSION['user']['lname'] = $row['lname'];
$_SESSION['user']['email'] = $row['email'];
$_SESSION['user']['avatar'] = $row['avatar'];
$_SESSION['user']['energy'] = $row['energy'];
$_SESSION['user']['energymax'] = $row['energymax'];
$_SESSION['user']['health'] = $row['health'];
$_SESSION['user']['healthmax'] = $row['healthmax'];
$_SESSION['user']['fame'] = $row['fame'];
$_SESSION['user']['edollar'] = $row['edollar'];
$_SESSION['user']['etoken'] = $row['etoken'];
$_SESSION['user']['companies'] = $row['companies'];
$_SESSION['user']['workid'] = $row['workid'];
$_SESSION['user']['city'] = $row['city'];
$_SESSION['user']['function'] = $row['function'];
}
echo $_SESSION['user']['energy'];
}
}
?>
Still this wouldn't update the header with values i want, instead it just makes the header disappear. What's wrong with this code? Maybe there are other, more effective methods to refresh values from MySQL?
EDIT:
I've edited the AJAX / PHP code samples - it's working like that! But how may I echo all those variables? Echoing one after another seems to cause error again, since values will disappear from my header.
EDIT2:
Solved, I made a silly mistake with syntax... Thanks everyone for contributing!
You are not using the data that is sent back from the server in your ajax call:
success: function() {
$(".full-wrapper").html(data);
}
});
Should be:
success: function(data) {
^^^^ the returned data
$(".full-wrapper").html(data);
}
});
You should also check that your php script actually echoes out something useful.
data options is missing in success method
success: function(data) {
$(".full-wrapper").html(data);
}
Also you should have to echo that content in php file which you want to show in header.

reference a php string in jquery?

I am using the following code to generate a random string in php, and then am storing this in my database like so:
<?php $allowance_promo = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 8); ?>
I am then using my query to store this value into the database:
$query = sprintf("UPDATE internal_users SET allowance_promo = '$allowance_promo' WHERE user_id ='{$_SESSION['id']}'");
$result = mysql_query($query);
I then use another query to retrieve the value:
$query2 = sprintf("SELECT * FROM internal_users WHERE user_id ='{$_SESSION['id']}'");
$result2 = mysql_query($query2);
while ($row = mysql_fetch_array($result2)) {
$check = $row['allowance_promo'];
Then i am trying to use jquery to check if the value entered into my input field matches the one in the database like so:
<script>
$(document).ready(function() {
$('.promo_check').click(function() {
var discountCode = "<?php echo $check; ?>";
var codeEntered = $("input[name='promo']").val();
if (discountCode == codeEntered) {
$('#submit').removeAttr("disabled");
}
});
});
</script>
However i am having some difficulty getting it to work using a php string. If i use normal text like var discountCode = '123'; then it works, but when i try and use var discountCode = "<?php echo $check; ?>"; it wont work. Can someone please show me what i am doing wrong. Thanks,
Replace your script by the script below. Put discountCode outside the click event handler and remove $(document).ready();
<script type="text/javascript">
var discountCode = "<?php echo $allowance_promo; ?>";
$('.promo_check').click(function() {
var codeEntered = $("input[name='promo']").val();
if (discountCode == codeEntered) {
$('#submit').removeAttr("disabled");
}
});
</script>

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

Trouoble with Ajax submitting to database

I have this form:
<form method = \"get\" action = \"\" onsubmit = \"return addBeer('$user','$id','$name','$abv','$ibu','$icon','$style','$brewery','$breweryID','$icon')\" >
<p> <input type = \"submit\" value = \"Go Fishing\" /> </p>
</form>
which calls this JavaScript function:
function addBeer(user,id,bname,abv,ibu,icon,bstyle,brewery,breweryID,icon)
{
//get elements
alert('userID' + user);
alert('beerid'+id);
alert('beername'+bname);
alert('style'+bstyle);
alert('brewery'+brewery);
alert('abv'+abv);
alert('ibu'+ibu);
alert('brewery id'+ breweryID);
alert('icon'+icon);
//run ajax
var ajaxSettings2 =
{
type: "POST",
url: "addBeer.php",
data: "uID="+user+"&bID="+id+"&bName="+bname+"&bStyle="+bstyle+"&bBrewery="+brewery+"&abv="+abv+"&ibu="+ibu+"&breweryID="+breweryID,
success: function()
{
$('#sbutton').remove();
alert('Load was performed.');
},
error: function(xhr, status, error) { alert("error: " + error); } };
$.ajax(ajaxSettings2);
}
All the alerts work so I know for a fact that the information is getting passed fom the form to the function, but it fails on the ajax call to addBeer.php because it runs the error function and pop up the error alert. Unfortunetley nothing is reported in the pop up.
This is the addBeer.php file that is called to add to the database:
<?php
require_once('myConnectDB.inc.php');
require_once('page.inc.php');
session_start();
//add beer to database code
$userID = $_POST['uID'];
$beerName = $_POST['bName'];
$beerID = $_POST['bid'];
$brewery = $_POST['bBrewery'];
$style = $_POST['bStyle'];
$abv = $_POST['abv'];
$ibu = $_POST['ibu'];
$breweryID = $_POST['breweryID'];
//$icon = $_POST['icon'];
//get brewery icon
$uri3 = "http://api.brewerydb.com/v2/brewery/$breweryID?key=myKey&format=json";
$response3 = file_get_contents($uri3);
//parse xml
$myBrew = json_decode($response3);
$iconBrew = $myBrew->data->images->medium;
//add above data to database
$db = new myConnectDB();
$beerName = $db->real_escape_string($beerName);
$beerID = $db->real_escape_string($beerID);
$brewery = $db->real_escape_string($brewery);
$style = $db->real_escape_string($style);
$userID = $db->real_escape_string($userID);
$abv = $db->real_escape_string($abv);
$ibu = $db->real_escape_string($ibu);
$breweryID = $db->real_escape_string($breweryID);
$icon = $db->real_escape_string($icon);
$query3 = "INSERT INTO tableName (userID,beerID,beerName,beerStyle,beerBrewery,abv,ibu,breweryID,icon, brewIcon) VALUES ($userID, '$beerID', '$beerName', '$style' , '$brewery', '$abv','$ibu','$breweryID', '$icon', '$iconBrew')";
$db->query($query3);
?>
I took out my api key and table name for security.
I have checked the network tab in chrome under inspect element and when I click on addBeer.php call and look under headers it shows in form data that the information is being passed.
Update:
I am escaping my quotes because its being printed from php
After lots and lots of frustration, I figured out my problem. The information I was sending, I was querying from another database and all that info was not always complete.
If I clicked submit and it and one of the variables in the function call was an empty string it did not like it.
You have your method as GET in the form but POST in your Ajax.

passing data from javascript to php using Jquery

Maybe this question has been asked before but I am struggling in doing this. I have got a php file which does not include any piece of php code (might be in the future),it includes just javascript and some html. What I want to do is clicking a button in this php file to send some amount of data to another php file.
put it this way..
1-I have got a saveProfile function in a.php and a button is calling this function
function saveProfile (){
var variableD = 'sample data';
$.post("dbConn.php", { js: variableD});
}
2-I have got another php which is called dbConn.php that receives data and stores in a database table.
I have found so many examples. I have applied them but it still does not work and is driving me nuts. I am a java programmer but new in php.
Any help is appreciated.give me some clean sample code or if you see any mistake please kindly warn me. Thanks to all in advance...
Regards.
Ozlem.
Take a look at the accepted answer to "Javascript Post Request like a Form Submit".
It provides javascript for for:
function post_to_url(path, params, method) {
...
}
I think this will do what you want.
Thanks for all the answers. I have solved the problem. The data had being passes but I was not able to handle it properly. I just add a dummy code to test it.It worked. I will upload the code after I have finished.Thanks to all.
This function is in a PHP file, but is full of JS code. The last line passes the data to another PHP file which saves the data into a database.
function saveProfile (){
var _profileId = 0;
var _profileName = document.getElementById('nameProfile').value;
var queryArr=[];
$(markersArray).each(function (index){
//alert(markersArray[index].name);
var _locationId = index;
var _locName = markersArray[index].name;
var _markerLat = markersArray[index].marker.getLatLng().lat();
var _markerLng = markersArray[index].marker.getLatLng().lng();
var locations = {
profileName: _profileName,
locationId:_locationId,
locationName:_locName,
lat:_markerLat,
lng:_markerLng }
queryStr = { "locations": locations}
queryArr.push(queryStr);
});
/*for ( var i=0; i<markersArray.length; i++){
alert(queryArr[i].locations.locationId+"--"+queryArr[i].locations.locationName +"--"+queryArr[i].locations.lat);
}*/
$.post('dbConn.php', { opType:"saveAsProfile" , data: queryArr}, showResult, "text");
}
This is dbConn.php, which is called by the saveProfile method. The data is handled as follows:
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'google_map_db';
$opType = $_POST['opType'];
//SAVE PROFILES WITH A PROFILE NAME
if(!strcmp($opType, "saveAsProfile") ){
$res = $_POST['data'];
$connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error() );
mysql_select_db( $db_name ) or die( mysql_error() );
$queryString = "";
for($i = 0; $i < sizeof($res); $i++){
$profileName = $res[$i]['locations']['profileName'];
$locationId = $res[$i]['locations']['locationId'];
$locationName = $res[$i]['locations']['locationName'];
$lat = $res[$i]['locations']['lat'];
$lng = $res[$i]['locations']['lng'];
$sp = " ";
$queryString = $queryString . "(0 ".",'".$profileName."',".$locationId.",'".$locationName."',".$lat.",".$lng.") ";
if($i<sizeof($res)-1)
$queryString = $queryString . ", ";
}
$qInsertUser = mysql_query(" INSERT INTO `map_locations` (`profileId`, `profileName`, `locationId`, `locationName`, `lat`, `lng`)
VALUES ".$queryString." ");
if ($qInsertUser){
echo "successfully added!!!";
} else {
echo "Error";
}
}

Categories