I am designing a php application using AJAX and PHP.
But the if statement in my php file behaves unexpectedly.
The request method is 'POST';
Ajax code is
function fetchData(){
var recipename = document.getElementById("recipe").value;
var calorie = false;
createRequestObject();
//window.alert(calorie);
var url = "reciepinfo.php";
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
window.alert(calorie);
xmlHttp.send("recipe="+recipename+"&calorie="+calorie);
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState===4 && xmlHttp.status===200){
document.getElementById("target").innerHTML = xmlHttp.responseText;
}
}
}
And php code is:
<?php
$_SESSION['flag']=false;
if($_SESSION['flag']==false){
session_start();
$_SESSION['flag']=true;
}
$recipename = $_REQUEST['recipe'];
$calorie = $_REQUEST['calorie'];
echo $calorie;
$calorietemp = 0;
//echo $recipename;
$database = "nutrition";
$link = mysqli_connect('localhost','root','',$database);
$query = "select * from recipestb where name='$recipename'";
//$result = mysqli_query($link,$query);
//$obj = mysqli_fetch_object($result);;
if($link){
$result = mysqli_query($link,$query);
$obj = mysqli_fetch_object($result);
//$arr = mysqli_fetch_array($result);
//$names = "";
if(is_object($obj)){
echo "<i/>";
echo "<font size='5'>";
echo "Recipe name: ".$obj->name;
echo '<br/>';
echo "Carbohydrates : ".$obj->carbs." grams";
echo '<br/>';
echo "Proteins: ".$obj->protein." grams";
echo '<br/>';
echo "Fat: ".$obj->fat." grams";
echo '<br/>';
echo "Calories: ".$obj->calorie." cal";
$calorietemp = $obj->calorie;
echo '<br/>';
}else{
echo "non object";
}
}else{
echo "Connection failed";
}
if($calorie==true){
echo $calorie;
$_SESSION['caloriecount'] = $_SESSION['caloriecount'] + $calorietemp;
echo "Total calorie in diet :".$_SESSION['caloriecount'];
}
My session handling is weird i accept, but neglecting that, even the variable calorie is explicitly set to false, the if block executes.The echo $calorie statement also executes and it displays $calorie as false.
And i am not getting what is going wrong exactly.
Almost irritated with this.
Can anybody help?
EDIT1:
The php code is fine...
Ajax code has some problem...
When i set the $calorie to false in php code..
It behaved properly..
Leaving the session handling aside, the $calorie problem ...
You pass the data via AJAX as strings.
$calorie = 'false';
var_dump((true == $calorie));
You will get always bool(true). Using your AJAX example above, try this snippet instead (and use POST instead of REQUEST):
$calorie = ('true' == $_POST['calorie']);
var_dump($calorie);
// produces `bool(false)`
As a beginner i was unaware that the java-script variable with value false is passed as a string "false" to a server side script like PHP.
If we use a boolval(), in PHP this issue can be resolved.
PHP boolval()
I set the $calorie in my java-script to 0 or 1 as per my need.
When i wanted the false value to be sent to PHP script ,i set $calorie in java-script to 0 and the boolval() in corresponding PHP script evaluated it as false.
So the issue was resolved.
Related
So I am having an issue with re-populating data into a dropdown box after the form is submitted with Ajax. This is to remove an object from the dropdown, the initial script works fine, its just getting the new data and populating. My PHP script builds a JSON array to output to Ajax for parsing but when I check the PHP script the only thing that returns is }.
PHP Code:
$jasonData = "{";
include_once("../php_includes/db_connect.php");
$sql = "SELECT * FROM orginfo";
$user_query = mysqli_query($db_connect, $sql);
$count = mysqli_num_rows($user_query);
for($i = 0; $i < $count; $i++){
$rows = mysqli_fetch_array($user_query);
$id = $rows["id"];
$orgname = $rows["orgname"];
$orgphone = $rows["orgphone"];
$jasonData .= '"option'.$id.'":{ "id":"'.$id.'","orgname":"'.$orgname.'","orgphone":"'.$orgphone.'" },';
}
$jsonData = chop($jsonData, ",");
$jsonData .= "}";
echo $jsonData;
AJAX Code:
function getorgs(){
var getorgs = ajaxObj("POST", "engine.php");
getorgs.onreadystatechange = function() {
if(ajaxReturn(getorgs) == true) {
var remresponse = JSON.parse(getorgs.responseText);
alert (remresponse);
}
}
getorgs.send("getorgs");
}
I have been building this off of several tutorials kind of piece meal along with things I have already learned and am using. The current lack of sanitation is because of testing, want to make sure things are working and then add it in to narrow down any issues.
Any help would be appreciated.
Thanks in advance for taking a look.
Try the following:
<?php
header('Content-Type: application/json;charset=UTF-8');// this line must reside on top (before any output)
$jasonData = array();
$user_query = mysqli_query($db_connect, 'SELECT*FROM`orginfo`');
while ($row = mysqli_fetch_assoc($user_query)) {
array_push($jasonData, $row);
}
echo json_encode($jasonData, JSON_FORCE_OBJECT);
mysqli_close($db_connect);
Let me know if the above doesn't work out!
ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...
Alright I've been trying to find an answer to this for hours already but I couldn't resolve it myself.
I'm trying to call a Javascript parent function from a PHP function, however, it is not getting called.
When using the onclick method onclick='parent.dosomething(); everything seems to work fine but if I try to call the function by echo'ing it out, it would just fail for some reason.
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
Here's the PHP function:
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" );
$actualtime = time();
$timetoseconds = $actualtime - $timeposted;
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this is what is not getting called
}
}
}
}
}
And this is my Javascript function at the parent page:
function reloadprofmessages()
{
$('#friendrequests').load('showprofmessages.php?username=<?php echo $actualuser; ?>').fadeIn("slow");
} //refreshes messages
I pressed CTRL + Shift + I in Google Chrome to get to the developer tools, Network > page that does the request that calls the PHP function > Preview and this was what I received:
<script>parent.reloadprofmessages();</script>
However, the function is not getting called.
Resolving this would solve me a lot of problems, to me it is actually still a mystery to know why it doesn't work since it has worked in other cases.
Thank you for your help in advance.
It's not a good idea to fetch javascript and execute it with AJAX. What I would suggest is to firstly change your PHP to this:
if($activity_type == 1) //Messages
{
echo "1";
}
else {
echo "0";
}
Then change your Javascript to this:
function reloadprofmessages()
{
var can_reload = $.ajax({ url: "showprofmessages.php?username=<?php echo $actualuser; ?>" });
if (can_reload) {
parent.erloadprofmessages();
}
}
Hope that helps
Add the type attribute for script tag
echo "<script type='text/javascript' >parent.reloadprofmessages();</script>";
and remember to define the javascript function before this line
So here is what was wrong: (Showing errors)
function checkactivity($username)
{
//These are just queries being executed (irrelevant)
$querystats = "SELECT users.fullname, activity.id, activity.sender, activity.receiver, activity.type, activity.dateposted, activity.seen, activity.related FROM activity, users WHERE activity.receiver = '$username' && activity.seen = '0' ORDER BY id DESC LIMIT 1";
$resultstats = mysql_query($querystats);
$num_stats = mysql_num_rows($resultstats);
$rowactivity = mysql_fetch_assoc($resultstats);
//End of queries
if($num_stats > 0) //If there are registries
{
$user = $_SESSION['Username'];
$activity_date = $rowactivity["dateposted"];
$activity_type = $rowactivity["type"];
$activity_sender = $rowactivity["sender"];
$timeactivity = strtotime( "$activity_date" ); //$timeactivity was not being used
$actualtime = time();
$timetoseconds = $actualtime - $timeposted; //$timeposted doesn't even exist, in other words I wasn't even converting the $activity_date timestamp to time.
$timetominutes = floor($timepassedtoseconds/60);
if($timetominutes < 2)
{
if($activity_sender != $user)
{
if($activity_type == 1) //Messages
{
echo "<script>parent.reloadprofmessages();</script>"; //this was not the correct way of calling a function from the parent page.
}
}
}
}
}
About the Javascript function:
This is what I ended with:
var auto_refresh = setInterval(
function reloadstring()
{
$.get("checknewactivity.php?vprofile=<?php echo $actualuser; ?>", function(activity){
if (activity == 1)
{
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $actualuser; ?>').fadeIn("slow");
}
});
}, 1000); // refresh every 1000 milliseconds
And now it works, thank you for your help, I really appreciate it, and as usual, I always get to a safer solution after asking it here.
Let me start off by saying while I'm pretty good with PHP and HTML, I don't know much about javascript/jquery. I also apologize if this has been answered before, but I haven't had much luck finding anything in the search.
I'm working on a project where we have a form of undetermined size that I want to build some autocomplete functionality into. The form fields and necessary div's are being named using a counter as you can see in the code below.
$set_b = 'upl_band'.$count;
$sugbox = $set_b."sug";
$autobox = $set_b."auto";
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup='bandlookup(this.value,'$set_b');' onblur='bandfill();'></div>";
echo "<div class='suggestionsBox' id='$sugbox' style='display: none;'><img src='upArrow.png' style='position: relative; top: -12px; left: 30px;' alt='upArrow' /><div class='suggestionList' id='$autobox'> </div></div>";
I'm trying to pass the main value - $set_b into my javascript onkeyup. However, somewhere along the line I'm losing my values. If I setup my form with concrete id's this code works fine, but when I make my id's variable I'm getting lost. My javascript is below. The post call to band.php is my lookup script.
function bandlookup(bandString, boxName) {
if(bandString.length == 0) {
// Hide the suggestion box.
var s = boxName+"sug";
$("#"+s).hide();
} else {
var su = boxName+"sug";
var suauto = boxName+"auto";
$.post("band.php", {queryString: ""+bandString+"", inputName: ""+boxName+""}, function(data){
if(data.length >0) {
$("#"+su).show();
$("#"+suauto).html(data);
}
});
}
} // lookup
function bandfill(thisValue, boxName) {
var s = boxName+"sug";
$("#"+boxName).val(thisValue);
setTimeout("$('#'+s).hide();", 200);
}
and band.php
$db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$box = $_POST['inputName'];
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT band_name,band_id FROM upl_band WHERE band_name LIKE '$queryString%' LIMIT 10");
if($query) {
// While there are results loop through them - fetching an Object (i like PHP5 btw!).
while ($result = $query ->fetch_object()) {
// Format the results, im using <li> for the list, you can change it.
// The onClick function fills the textbox with the result.
echo '<li onClick="bandfill(\''.$result->band_name.'\',\''.$box.'\');">'.$result->band_name.'</li>';
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
My problem could be with the post call in the javascript, but I'm more leaning towards me improperly dealing with the variable variable names as an id tag.
Your string is broken, try this:
echo "<div><input type=text name='$set_b' size=25 id='$set_b' onkeyup=\"bandlookup(this.value,'$set_b');\" onblur='bandfill();'></div>";
here is the code
<php?
$id1 =1;
$id2 = "module 1 loaded";
echo "$var1=$id1","$var2=$id2";
?>
i know this is not correct way how can i pass these two varables to flash
<?php
echo http_build_query( array(
'var1' => 1
,'var2' => 'module 1 loaded'
));
Paul Dixon's code snip is what you need on the PHP side. Here's the flash part:
myVars = new LoadVars();
myVars.load("http://localhost/foo.php");
myVars.onLoad = function (success) {
if (success) {
for( var attr in this ) {
trace (" key " + attr + " = " + this[attr]);
}
} else {
trace ("LoadVars Error");
}
}
Note, you will want to replace the loop logic with whatever your application requires.
If you want to create a script which outputs data which can be loaded with LoadVariables or LoadVars you need something like this
//set up your values
$vars=array();
$vars['foo']='bar';
$vars['xyz']='123';
//output
header ("Content-Type: application/x-www-urlformencoded");
$sep="";
foreach($vars as $name=>$val)
{
echo $sep.$name."=".urlencode($val);
$sep="&";
}
If your version of PHP supports it, http_build_query makes this even easier:
$vars=array();
$vars['foo']='bar';
$vars['xyz']='123';
header ("Content-Type: application/x-www-urlformencoded");
echo http_build_query($vars);
Shouldn't it just be in the form of a query string:
echo $var1.'='.$id1.'&'.$var2.'='.$id2;
Make sure the keys and values are urlencoded.
Flash Code:
btn.onPress = function(){
testLoadVars = new LoadVars();
testLoadVars.onLoad = function(success){
if(success){
trace(testLoadVars.var1);
trace(testLoadVars.var2);
}
else
trace("error");
}
testLoadVars.sendAndLoad("http://localhost/filename.php?uniqueID=" + getTimer(),testLoadVars,"POST");
}
That's all.. Any Problem faced??
PHP Code:
<php?
$id1 =1;
$id2 = "module 1 loaded";
print "&var1=$id1";
print "&var2=$id2";
?>
I am sure this will work...