concatenated string from php to js using ajax - javascript

What is wrong here:
function getoptions(){
echo "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions();
echo ($id . '***' . $options);
js
console.log(data);
Result:
<option value = 3>ABX</option>10***
I'm expecting 10***<option value = 3>ABX</option>
Any help?

If you need to use the same function to either echo or return the output you can pass a flag to the function. You can set a default value so the function performs as expected by other parts of your app.
// set default value of echo the output so it's non-breaking for other functions that require the output to be echoed
function getoptions($out = 'echo'){
if ($out == 'return') return "<option value = 3>ABX</option>";
echo "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions('return');
echo ($id . '***' . $options);

In function getoptions you are echoing, you need to return the value. Look at the corrected function below.
function getoptions(){
return "<option value = 3>ABX</option>";
}
...
$id = $db->lastInsertId(); // for example `10`
$options = getoptions();
echo ($id . '***' . $options);

Related

How to replace the variable from controller to into a (.php) file

I have an empty test.php file,in that file, I've inserted data below shown.
This code is form controller. This trace data coming from UI using ajax.
Here my $trace array data like this :
array(
[0] => $test1 = "1,2,3,4,5,6,7";
[1] => $test2 = "1,2,3,4,7";
[2] => $test3 = "1,4,6,7,9,0";
)
This is coming from UI
$trace = $this->input->post('trace');
$viewsDir = 'C:/xampp/htdocs/project/application/views/html_v3/';
$fp = fopen($this->viewsDir.'test.php', 'w');
fwrite($fp, "<?php \n\n");
$i = 0;
if($trace){
foreach ($trace as $value) {
fwrite($fp, $trace[$i]."\n");
$i++;
}
}
fwrite($fp, "\n?>");
fclose($fp);
After inserted my data into test.php file then the file look like this:
<?php
$test1 = "1,2,3,4,5";
$test2 = "5,2,0,6,5";
$test3 = "4,8,9,7,1";
?>
Here, if once again I want to insert data into test.php file, my $trace array data like this:
aray(
[0] => $test1 = "9,9,9,9,9";
[1] => $test2 = "1,1,1,1,1";
[2] => $test4 = "1,2,6,7,8";
)
Here my query is how can I replace this ($trace)array variables if matched with test.php. If not matched it should be added to the test.php file.
Here my expected output is:
<?
$test1 = "9,9,9,9,9";
$test2 = "1,1,1,1,1";
$test3 = "4,8,9,7,1";
$test4 = "1,2,6,7,8";
?>
I tried like this,but i don't know how to compare my array($trace) and content of test.php
$file = $this->viewsDir.'test.php';
$contents = file_get_contents($file);
echo $contents; //i will get content of test.php based on this i have to replace or add
Please help me,
Thanks.
I'm not even sure I should help you with that. There is possibly something very wrong with your design if you're passing php code via POST and save it to a source file.
Anyways...
I'd declare helper function that 'parses' entry string line as key $trace1 and value "1,2,3,4,5" and adds it to array $arr
function addToTrace(&$arr, $entry) {
$entry = trim($entry);
if(substr($entry, 0, 1) == "$") {
$elements = explode("=", $entry);
if(count($elements) !== 2) {
return false;
}
$elements = array_map('trim', $elements);
$arr[$elements[0]] = $elements[1];
return true;
}
return false;
}
After that it's only a matter of reading the file first, adding all entries to new array $currTrace
$currTrace = [];
$fp = fopen($this->viewsDir . 'test.php', 'r');
if($fp) {
while (!feof($fp)) {
$line = fgets($fp);
addToTrace($currTrace, $line);
}
fclose($fp);
}
than adding new trace from post (ovewriting matching keys):
if($trace){
foreach ($trace as $value) {
addToTrace($currTrace, $value);
}
}
and saving $currTrace to file:
$fp = fopen($this->viewsDir . 'test.php', 'w');
fwrite($fp, "<?php \n\n");
foreach($currTrace as $key => $value) {
fwrite($fp, $key . " = " . $value . "\n");
}
fclose($fp);

Get javascript variable value in php

I need to get javascript variable value in php file.
html example:
UPDATE:
$html = '
<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
Shout I use regex ? regex is very complex to me... any help ?
<?php
$html = '<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
$variables = ["adminSeq", "companyId"];
$counter = 0;
foreach($variables as $variable) {
preg_match_all('/"(.*?)"/', $html, $matches);
${"$variable"} = ($matches[1])[$counter];
$counter++;
}
echo $adminSeq; // Prints out: 3423423423423
echo $companyId; // Prints out: 2349093284234
?>
You can also use GET requests to do this. The link would look like http://localhost/?adminSeq=3423423423423&companyId=2349093284234 then get out these values in PHP with:
<?php
$adminSeq = $_GET["adminSeq"];
$companyId = $_GET["companyId"];
?>

Select list ignores first value when using the onchange function, PHP, JAVASCRIPT

I'm using a select list function below to make a select list that have 5 values inside of it. Values 2-5 works fine when I select them, and they print out their values on the page when I select them, but value 1 does not print out no matter what. I cannot figure out what I did wrong or how to fix it. Please take a look at my code:
index.php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>";
while ($tempCount < $count) {
$tempCount++;
echo "<option value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"index.php")
$value = $_POST['value'];
echo $value;
Add one first option to the < select >, and, check if $_POST['value'] exists. Next is your code with both changes pointed by commented arrows (//<=====) :
<?php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>" .
"<option>Select an option</option>"; // <===========================
while ($tempCount < $count) {
$tempCount++;
echo "<option value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"xyz.php");
if ( isSet( $_POST['value'] ) ) // <===========================
{ $value = $_POST['value'];
echo $value;
}
?>
The option "Select an option" will let the user to choose option 1.
If you don't want to see "Select an option", the other solution is to make the chosen option selected, for example, if the user chooses "3", when the page reloads the option "3" will be selected, and the user will be able to choose option "1" :
<?php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>";
while ($tempCount < $count) {
$tempCount++;
// MAKE THE CURRENT OPTION SELECTED IF IT WAS CHOSEN BEFORE. <==========
if ( isSet( $_POST['value'] ) && // IF 'value' EXISTS, AND
( $_POST['value'] == $tempCount ) ) // IF 'value' == CURRENT NUMBER
$selected = "selected";
else $selected = "";
echo "<option $selected value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"xyz.php");
if ( isSet( $_POST['value'] ) ) // <===========================
{ $value = $_POST['value'];
echo $value;
}
?>

Assigning PHP Variables To Javascript Variables Not Working

I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.

Pass Phantomjs console to php file

I have been trying to pass my phantomjs console output back to the php file that executed it, but I only get and empty array with this code. It also happens immediately, which makes me think its attempting to get the return before the phantomjs script has even run.
<?php
$user= 'dafjdh#kjsdf.com';
$pass='dumfmh';
$response = exec("/home/jef28/public_html/swipr/phantomjs /home/jef28/public_html/swipr/login.js $user $pass", $output);
echo $output;
?>
The last lines of my .js file are
console.log(document.querySelectorAll('html')[0].outerHTML);
return document.querySelectorAll('html')[0].outerHTML;
How can I pass the console output back to php?
I use this function and it works just fine .
function execute($script, $args = array(), $options = array(), $bin = 'F:/----/phantomjs-1.9.8-windows/phantomjs.exe', $debug = true) {
$option_str = '';
foreach ($options as $option => $value)
{
$option_str .= '--'.$option.'='.$value.' ';
}
// Escape
$cmd = escapeshellcmd("{$bin} {$option_str}{$script} " . implode(' ', $args));
if($debug) $cmd .= ' 2>&1';
// Execute
$result = shell_exec($cmd);
if($debug) return $result;
if($result === null) return false;
// Return
if(substr($result, 0, 1) !== '{') return $result; // not JSON
$json = json_decode($result, $as_array = true);
if($json === null) return false;
return $json;
}

Categories

Resources