PHP - Ajax Call Not Returning Dynamically Assigned Variable String
Where is my "Progr" return value?
This is not my first day using php but I don't code in the language that often. I don't understand why my dynamic variable is not returned in AJAX GET? Essentially, I need to give the client a simple UI so that they can copy files to a printer and I wanted to provide a little unfiltered feedback so they knew whether operation was a success. My feedback was just going to be output of exec() function though cleaned up slightly (perhaps replace line breaks with html break tags). PHP version is 5.2.17.17 and cannot be upgraded. Web Server Apache.
PHP dumbed down code:
exec("LoadZPL_PURL.bat", $output);
Similar TutorialsHello, I've been trying this for hours now, looking at different examples and trying to change them to work for me, but with no luck... This is what I am trying to do: I have a simple form with: - 1 input field, where I can enter a number - 1 Submit Button When I enter a number into the field and click submit, I want that number to be send to the php file that is in the ajax call, then the script will take that number and run a bunch of queries and then return a new number. I want that new number to be used to call the php script via ajax again, until no number is returned, or something else is returned like the word "done" or something like that, at which point is simply makes an alert or populated a div with a message... The point is, that depending on the number entered it could take up to an hour to complete ALL the queries, so I want the script that is called to only run a fixed amount of queries at a time and then return the number it is currently at (+1), so that it can continue with the next number when it is called again. I would like to use jquery, but could also be any other way, as long as I get this to work. I already have the php script completed that needs to be called by the ajax, it returns a single number when being called. Thank you, vb So i need to dynamically call a function in my object, depending on certain parameters. Currently, I'm doing this: Code: [Select] <?php $myObject = new Object_Class; $the_function_to_call = "do_something"; // this is not really a static variable; it changes each time the script loads. eval("\$myObject->". $the_function_to_call ."();"); // run $myObject->do_something(); ?> This works fine but I'd rather not use eval() if I can help it. Is there an easy way to do this that I'm just missing? Please help me in this guys....... I am using MVC model for my application . I am stuck with the ajax call. this is my controller application/controller/admin/index.php function getCity() { $city=$this->model->getCity(); foreach($this->city as $key => $value) { echo '<option>'.$value['name'].'</option>' ; } } this is my model application/model/admin_model.php public function getCity() { if($_POST['id']) { $cid=$_POST['id']; $sth = $this->db->prepare('SELECT id, name FROM unit WHERE cid= :cid'); $sth->execute(array(':cid' => $cid)); return $sth->fetchAll(); } } this is my view <form id="city" action="<../application/admin/regstr/" method="post"> Country <select name="country" class="country"> <option value="" selected="selected">--Select Taluka--</option> <option value="1">India</option> <option value="2">USA</option> <option value="3">China</option> </select> City <select name="city" class="city"> <option selected="selected">--Select City--</option> </select> <input type="submit" /> </form> and this is my javascript for Ajax $(document).ready(function() { $(".country").change(function() { var id=$(this).val(); var dataString = 'id='+ id; $.ajax ({ type: "POST", url: "admin/getCity", data: dataString, cache: false, success: function(html) { $(".city").html(html); } }); }); }); But I am not getting the output. I have tested it with firebug in response tab. Instead of getting only option values html code as output I am getting the whole HTML page content (i.e. content of view page admin/index.php. Please help me out. Hi guys, I am using this oAuth library https://github.com/elbunce/oauth2-php But more specifically these lines of code: protected function getToken($token, $isRefresh = true) { try { $tableName = $isRefresh ? self::TABLE_REFRESH : self::TABLE_TOKENS; $tokenName = $isRefresh ? 'refresh_token' : 'oauth_token'; $sql = "SELECT $tokenName, client_id, expires, scope, user_id FROM $tableName WHERE token = :token"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':token', $token, PDO::PARAM_STR); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); return $result !== FALSE ? $result : NULL; } catch (PDOException $e) { $this->handleException($e); } } However, this is retuning no value. If I modify the code to be: protected function getToken($token, $isRefresh = true) { return $token; } It returns the $token value, so the $token is definitely being passed to the function. The code should return an associative array: i.e., $token["expires"], $token["client_id"], $token["userd_id"], $token["scope"], etc Also $token should not === NULL. PS. I run a few checks on $tableName = $isRefresh ? self::TABLE_REFRESH : self::TABLE_TOKENS; $tokenName = $isRefresh ? 'refresh_token' : 'oauth_token'; And they are returning the correct values. Which from my thinking narrows it down to: $sql = "SELECT $tokenName, client_id, expires, scope, user_id FROM $tableName WHERE token = :token"; $stmt = $this->db->prepare($sql); $stmt->bindParam(':token', $token, PDO::PARAM_STR); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); return $result !== FALSE ? $result : NULL; Any and all help is greatly appreciated. Thanks in advance. Somebody please help me. The below given code is not working.
Hi
I have an AJAX call that populates a select menu based on the selection from a previous menu. All works on on desktop browser, Safari, Firefox IE etc, however when using iOS the second select menu isn't populating.
the AJAX request is as follows
<script> function getXMLHTTP() { //fuction to return the xml http object var xmlhttp=false; try{ xmlhttp=new XMLHttpRequest(); } catch(e) { try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){ try{ xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e1){ xmlhttp=false; } } } return xmlhttp; } function getTeam(strURL) { var req = getXMLHTTP(); if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('away-team').innerHTML=req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } req.open("GET", strURL, true); req.send(null); } } function getGP(strURL) { var req = getXMLHTTP(); if (req) { req.onreadystatechange = function() { if (req.readyState == 4) { // only if "OK" if (req.status == 200) { document.getElementById('gp').innerHTML=req.responseText; } else { alert("There was a problem while using XMLHTTP:\n" + req.statusText); } } } req.open("GET", strURL, true); req.send(null); } } </script>and the trigger for it... <select name="year" class="txtfield" onChange="getGP('find_gp_ajax.php?season='+this.value)">Any ideas why the call won't work on iOS? Hello guys is it possible to create a single php file to contain all the functions to be called via AJAX and get AJAX to call the specific function required rather than having to create individual pages for each AJAX request you need to make? Many Thanks My login script stores the user's login name as $_SESSION[ 'name'] on login. For some unapparent reason, i'm getting errors stating that $user and $priv are undefined variables, though I've attempted to define $user as being equal to $_SESSION['name'], using $user to look up the the user's privilege level (stored as the su column ) in the SQL table, and then where the result of the sql query is $priv which is then evaluated in an if statement. I can't seem to figure out why this might not be working. The code I'm using: <?php session_start(); function verify() { //verify that the user is logged in via the login page. Session_start has already been called. if (!isset($_SESSION['loggedin'])) { header('Location: /index.html'); exit; } //if user is logged in, we then lookup necessary privleges. $_SESSION['name'] was written with the login name upon login. Privleges // are written in db as a single-digit integer of of 0 for users, 1 for administrators, and 2 for special users. $user === $_SESSION['name']; //Connect to Databse $link = mysqli_connect("127.0.0.1", "database user", "password", "database"); if (!$link) { echo "Error: Unable to connect to MySQL." . PHP_EOL; echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } //SQL Statement to lookup privlege information. if ($result = mysqli_query($link, "SELECT su FROM accounts WHERE username = $user", MYSQLI_STORE_RESULT)) { //LOOP TO CYCLE THROUGH SQL RESULTS AND STORE Privlege information as vairable $priv. while ($row = $result->fetch_assoc()) { $priv === $row["su"]; } } // close SQL connection. mysqli_close($link); // Verify privleges and take action. Only a privlege of "1" is allowed to view this page. A privlege of "2" indicates special //accounts used in other scripts that have certain indermediate additional functions, but are not trusted administrators. if ($priv !== 1) { echo $_SESSION['name']; echo "you have privlege level of $priv"; echo "<br>"; echo 'Your account does not have the privleges necessary to view this page'; exit; } } verify(); ?>
Hey guys, I'm making an Ajax call to my database and retrieving a newsletters HTML code as the result. I then prepend it into a div area called code_content. I use some php str_replace to add some links also. When the content loads into the div, the user can then add further content to it via Ajax calls, appending articles and that. What I'm trying to figure out is how can I then retrieve all the newly edited contents of this code_content div soni can send it to my Ajax function to write to te db? Can anyone figure out why this works in IE and Firefox but not Safari? Any help would be great. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Concept Builders</title> <link href="_css/main.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="_css/megamenu.css" type="text/css" media="screen" /> <script src="_scripts/pagebuilder.js" type="text/javascript"></script> <script src="_scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script src="_scripts/jquery.nivo.slider.pack.js" type="text/javascript"></script> <script src="_scripts/jquery.easing.1.3.js" type="text/javascript"></script> <script src="js/megamenu.js" type="text/javascript"></script> <?php include 'dbconfig.php'; include 'dbopen.php'; $plan=$_GET["plan"]; $sql = "SELECT * FROM homes WHERE plan_id= '".$plan."'"; $result = mysql_query($sql); while ($row = mysql_fetch_array($result)) { $price=$row['price']; $sqft=$row['sqft']; $beds=$row['bedrooms']; $baths=$row['baths']; $amenities=$row['amenity_1'].", ".$row['amenity_2']; } setlocale(LC_MONETARY, 'en_US'); $price=money_format('%(#6.0n', $price); $plan_details= "<table> <tr> <td width='182' class='propDetailsHeadings'>Price:</td> <td width='75'>".$price."</td> </tr> <tr> <td class='propDetailsHeadings'>SQ Feet:</td> <td>".$sqft."</td> </tr> <tr> <td class='propDetailsHeadings'>Amenities:</td> <td></td> </tr> <tr> <td>".$amenities."</td> <td></td> </tr> </table>";?> <script language="javascript" type="text/javascript"> function loadPage() { var ajaxDisplay = document.getElementById("plan_details"); ajaxDisplay.innerHTML = <?PHP echo $plan_details;?>; } </script> </head> <body onload="loadPage()"> This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=334644.0 I'll try to explain this as easily as possible. I'm working on making a little link shortener site just for fun/practice as a beginner with php. I originally used the source code 'lilurl' as a base to start out, but now I'm adding stuff to it for actual practice. I need some help though. I have two files, my index and my external php file. The external file is called on at the beginning of the index with require_once. The user submits a url into the PHP_SELF form and a url is returned, and it works all great. Now I'm trying to add the option to make a custom url suffix. Code: [Select] <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <fieldset> <label for="longurl">Enter a URL:</label> <input type="text" name="longurl" id="longurl" /> <input type="text" name="suffix" id="suffix" /> <input type="submit" name="submit" id="submit" value="Shrink!" /> </fieldset> </form>[/code] The form looks like this. I added the 'suffix' textbox. So after the user submits the code, it goes back up to the top (phpself). A variable is set for the url the user has inputted as "$longurl", like this. Code: [Select] $longurl = trim(mysql_escape_string($_POST['longurl']));So I added this. Code: [Select] $suffix = ($_POST['suffix']);And to check if it worked, I went down the the bottom of the index and had it echo the suffix variable. When I entered in code into the suffix text box, it would be echoed at the bottom of the page, so the variable did receive the value. So here's where the external file comes in. It is called on by require_once at the very beginning of the index. It is full of functions. One of the functions generates a random string of numbers (that I coded) to be used as the url suffix (uses the $id variable). So my plan was to erase the $id = $rand1 . blah blah stuff and put $id = $suffix. $suffix being the variable from the index that the user inputted. Make sense? Well whenever I try it, it always acts the like the variable is empty, even when I echo it on the index it returns the value of the textbox. Does anyone know what I'm doing wrong? Could it be because since I call on $suffix in the external file, and it's only been declared in the index that it's treating it like a new/empty variable? [spoiler] Someone also explained it to me like this. -I call upon the external file. -I declare the variable is the value of the text box. (Which means it's currently empty because the form has not been submitted.) -Then, the form is submitted as PHP_SELF. -The external file is called upon again. -The variable is then assigned a value. It's hard to explain, but basically that the variable in the external file is not told about the new value of the variable because they are declared after the external file is called upon? :\ So I tried moving the $suffix = ($_POST['suffix']); before the external file is called upon, but the same thing happens. It's hard to explain the situation, but I've tried a lot of things and can't get it to work.[/spoiler] I have just started using functions, and have been following a few tutorials. I think im misunderstanding returns. lets say i have the variables called $math1 an $math2 and i want to make $total = $math1 + $math2; i then use return $total; I then thought i could echo $total and it would work outside of the function but its giving me an error of an underfines variable. Could anyone explain what im doing wrong please? thanks Hi, This is my first post in this forum and am a PHP beginner. I have written a script in php and need to use echo to see the values of variables etc. However I dont get the output on the screen while using echo . I am using Xampp server with Apache. The startup.html file code is
<!DOCTYPE HTML>
</head>
and the test.php code is <?php
$lat = $_REQUEST['latitude'];
echo 'latitude- '.$lat . ', longitude- ' . $lon; Please help regards
Sanjish Hello all, I'm a PHP newbie, so please pardon me if this question has already been asked somewhere in this forum. I have been reading the PHP documentation. On this page http://www.php.net/manual/en/language.references.pass.php, I came across this code: <?php ... snip ... function &bar() { $a = 5; return $a; } foo(bar()); ?> This is returning a reference to local variable $a. Coming from a C/C++ background, my intuition tells me this just shouldn't work, since the local variable $a should be deleted as soon as the function "bar" returns. The code seems to work, though. My guess is that PHP is basically ref-counting and garbage collecting local variables like $a, and so it will not be automatically cleaned up on call exit. Is this about right? Thanks! WN I have a page that functions like this:
The user begins by loading ajaxtest.php, then using a drop-down menu, selects a user, after which a DIV on ajaxtest.php is populated with the user's selction to getuser.php?q=John%Doe
Here's a visual representation of what is currently happening, along with the part I don't understand.
getuser.php consists largely of a a large HTML table which interacts through PHP with my SQL database. Several of the fields in this table are editable, and after the user changes one of these fields, he can press an "update" button, which calls an AJAX script in update.js and runs update.php, which contains all my SQL queries to update the database, without the user being redirected to this update.php page. All of this is processing perfectly - the user makes some sort of edit, hits "update", and the database gets updated without any redirection or refresh.
Here's what I can't figure out though. Once the user makes a change, and hits "update," the database updates, but the end user doesn't see those changes that he made. I can't just do a simple page refresh, because the action is taking place on getuser.php, but getuser.php is loaded inside of a #DIV on ajaxtest.php. If I use something like window.location.reload(), this just refreshes ajaxtest.php and puts the user back to the starting point of having to select a user. This is not what I want. I don't want to refresh ajaxtest.php, I want to "refresh" ajaxtest.php with getuser.php?q=John%Doe insidethe DIV on ajaxtest.php.
It seems like this is very common - several forums have this capability, where a user has a page loaded, adds a comment, and sees that comment immediately without a full page refresh. I just don't know how to do it, and I've tried at lengths to search the web for an answer with no luck.
Can someone walk me through how to do this?
This topic has been moved to Ajax Help. http://www.phpfreaks.com/forums/index.php?topic=357605.0 Hi, I am trying to make some adjustments to uploadify.php which comes with the latest version of uploadify (3.0 beta), so that it works with a session variable that stores the login username and adds it to the path for uploads. Here is uploadify.php as it currently looks: Code: [Select] <?php session_name("MyLogin"); session_start(); $targetFolder = '/songs/' . $_SESSION['name']; // Relative to the root if (!empty($_FILES)) { $tempFile = $_FILES['Filedata']['tmp_name']; $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder; $targetFile = rtrim($targetPath,'/') .'/'. $_FILES['Filedata']['name']; // Validate the file type $fileTypes = array('m4a','mp3','flac','ogg'); // File extensions $fileParts = pathinfo($_FILES['Filedata']['name']); if (in_array($fileParts['extension'],$fileTypes)) { move_uploaded_file($tempFile,$targetFile); echo '1'; } else { echo 'Invalid file type.'; } } echo $targetFolder; ?> I added Code: [Select] echo $targetFolder; at the bottom so that I could make sure that the string returned was correct, and it is, i.e. '/songs/nick'. For some reason though, uploads are not going to the correct folder, i.e. the username folder, but instead are going to the parent folder 'songs'. The folder for username exists, with correct permissions, and when I manually enter Code: [Select] $targetFolder = '/songs/nick';all works fine. Which strikes me as rather strange. I have limited experience of using php, but wonder how if the correct string is returned by the session variable, the upload works differently than with the manually entered string. Any help would be much appreciated. It's the last issue with a website that was due to go live 2 days ago! Thanks, Nick Hello all I have a php and jquery/ajax call I am using to create a file/send an email. I get all the contents from my textboxes but I want a message to display on the screen afterwards being success or fail. In my .ajax call My call is exiting right before the ‘success:’ part. Why is my call not succeeding? Any tips/help will be appreciated Thank you Html page just a form with a submit button $(document).ready(function () { var form = $("#formData"); $(form).on("submit", function (event) { event.preventDefault(); $.ajax({ type: "post", url: "file.php", data: $(this).serialize(), beforeSend: function () { $("#status").html('<span style="color:red;">Loading everything actually creating a .TXT file of contents...</span>') //--works }, success: function (data) { var responseMsgType = "alert-" + data.type; var responseMsgText = data.message; // message below var alertBox = '<div class="alert ' + responseMsgType + ' alert-dismissable"><button type="button" class="close" ' + 'data-dismiss="alert" aria-hidden="true">×</button>' + responseMsgText + '</div>'; if (responseMsgType && responseMsgText) { $(form).find(".successArea").html(alertBox); $(form)[0].reset(); } } }); return false; }); <?php $controls = array('txtName' => 'Name', 'txtEmail' => 'Email', 'txtSubject' => 'Subject', 'txtMessage' => 'Message'); try { if(count($_POST)==0) { throw new \Exception ('Contact Form Message is empty'); } $headers = array('Content-Type: text/plain; charset="UTF-8";', 'From: ' . $email, 'Reply-To: ' . $email, 'Return-Path: ' .$email); $emailMessage = "You have a new message from your contact form" . PHP_EOL; $emailMessage .= "-------------------------------------------------------" . PHP_EOL; foreach($_POST as $key => $value){ if(isset($controls[$key])) { $emailMessage .= "$controls[$key]: $value". PHP_EOL; } } $mailMsg = "email6.txt"; if(file_exists($filename) == false) { $fh = fopen($mailMsg, "w"); fwrite($fh, $headers); fwrite($fh, $emailMessage); fclose($fh); } else { $fhexists = fopen($filename, "a"); fwrite($fhexists, $content); fclose($fhexists); } $responseMessage = array("type" => "success", "message" => $successMessage); } catch (\Exception $ex) { $responseMessage = array("type" => "errorM", "message" => $errorMessage); } if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { $encodedJSON = json_encode($responseMessage); header("Content-Type: application/json"); echo $encodedJSON; } else { echo $responseMessage["message"]; }
Hello All, I have a PHP web application which will refresh itself(ajax calls connecting to the server and get the latest data) periodically. These also update the Database-based session handler class. i.e. There is NO UPDATE to the session data but the timestamp is constantly updated. Our problem is that garbage collection does not kick in as it looks at the difference between timestamp and session_gc.maxlifetime. So, if and the user is not interacting with the application. Now my question is how can I force the timeout even though refreshing happens but the user is not interacting with the application and there are "phantom" session updates made by these ajax calls. Please let me know. Thanks. |