Use PHP variable as Javascript function parameters - javascript

I'm using Laravel and I have two php variable in my blade view like this:
$dropDown = $formDataValue['name']
$emptyDropDown = $formDataValue['name'];
And I create a Javascript function with two parameters in same blade view:
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + dropDown).empty();
$("#" + dropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + dropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
Then I call this:
<?php echo "<script> autoFill(".$dropDown.", ".$emptyDropDown."); </script>"; ?>
Problem is they can pass the parameters to function! I check element in browser and I see when I call this function, it's have parameters. But in the script tag, there nothing!
How I can fix this?
Thank you very much!

Seems like you forgot about quotes, when you are passing strings into function.
<script>
$(document).ready(function () {
autoFill('{{ $dropDown }}', '{{ $emptyDropDown }}');
});
</script>
You can do it this way, but you shouldn't, because Laravel Blade do it for you itself.
<?php echo "<script> autoFill('".$dropDown."', '".$emptyDropDown."'); </script>"; ?>

You can assign the php value in js variable in blade file like below:
<script>
var dropDown = '{{$formDataValue['name']}}';
var emptyDropDown = '{{$formDataValue['name']}}';
</script>
and then use js file and move the autoFill() function in js file and call that js file in blade using .
and call autoFill(dropDown, emptyDropDown); in js file on document.ready Like:
$(document).ready(function() {
autoFill(dropDown, emptyDropDown);
});

if you are using laravel try this
<script type="text/javascript">
autoFill("{{$dropDown}}","{{$emptyDropDown}}");
function autoFill(dropDown,emptyDropDown) {
console.log("hi");
}
Hope its helpfull
not using core php
<script type="text/javascript">
autoFill("<?=$dropDown?>","<?=$emptyDropDown?>");
function autoFill(dropDown,emptyDropDown) {
console.log(dropDown);
console.log(emptyDropDown);
}

You did not render the values as strings, so javascript interprets them as variables, which are not defined.
so instead of autofill(city,ward)
you want autofill('city','ward')
1000 ways to rome, this would be one:
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>

Related

Cannot access JavaScript var from PHP

I am having problems echoing a PHP variable that i am getting from a form from JavaScript. In JavaScript the variables can be logged without problems, but when trying to echo from PHP, I get "err".
I am using JQuery with this.
JavaScript file:
$(document).ready(function(){
$("#soegform").submit (function (event){
var formData = {
soegtitel: $("#soegtitel").val(),
soegforfatter: $("#soegforfatter").val()
}
console.log(formData)
if($.trim(formData) != '') {
$.post('name.php', {formData: formData}, function(data){
console.log(data);
$('#visliste').text(data);
});
}
event.preventDefault();
});
});
I get the correct output from the console.log(formData), so accessing the HTML form shouldn't be the problem.
PHP file:
$data = json_decode(file_get_contents("php://input"));
$titel = (!empty($data->soegtitel)) ?$data->soegtitel:"err";
$forfatter = (!empty($data->soegforfatter)) ?$data->soegforfatter:"err";
echo $titel;
My output from echo $titel; is err, so something went wrong. Please help, as I have been trying to solve this to no avail, for several hours.
Thanks

Run PHP from within TPL

I am trying to modify a module TPL file and face some difficulties.
I have a dropdown list and want to run an SQL query when the user selects an item from the list.
So far I have tried to run a PHP file through Ajax in order to run the query but without any success.
I have seen various examples but can't understand how it should be done.
Nevertheless here is what I have done so far.
This is the code I use on the TPL file:
<select id="statusSelect" onChange="updateStatus({$order.id_order|escape:'html':'UTF-8'})">
<option value="1"> test1 </option>
<option value="2"> test2 </option>
<option value="3"> test3 </option>
</select>
This is the JS function I use to call the PHP file, through Ajax:
<script type="text/javascript">
function updateStatus(order_id_sent)
{
//TEST
//alert(document.getElementsByTagName("option")[selectedIndex].value + " " + order_id_sent);
$.ajax({
url: 'setStatus.php',
type: 'get',
data: 'ajax=true',
success: function()
{
alert("It worked");
}
});
}
</script>
And here is my setStatus.php file which I want to call:
<?php
include_once('../../../../../config/config.inc.php');
include_once('../../../../../init.php');
public function doStuff()
{
echo "alert('test');";
return 1;
}
if ($_GET['ajax'])
{
echo function doStuff();
}
?>
use
$( document ).ready(function() {
$("#statusSelect").change(function(){
statusUpdate($(this).val());
});
}
in your code the name of the function is statusUpdate and in the select you call updateStatus
i wish this can help you
Finally I've got a solution for the problem, by using the following script to run the PHP file.
It seems that I had to import the JQuery from google-apis and use {literal} before and after my script.
Here is the updated javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
{literal}
<script type="text/javascript">
function setStatus(order_id_sent)
{
var selectedIndex = document.getElementById("statusSelect").selectedIndex;
// test
// alert(document.getElementsByTagName("option")[selectedIndex].value + " " + order_id_sent);
var data = document.getElementsByTagName("option")[selectedIndex].value + "-" + order_id_sent;
$.ajax({
data: data,
type: "post",
url: "setStatus.php>",
success: function(data){
alert("data sent" + data);
}
});
}
</script>
{/literal}
And here is my PHP file, which is not complete yet but the point was to run the query and now it works properly.
<?php
include_once('../../../../../config/config.inc.php');
include_once('../../../../../init.php');
include_once('../../../../../classes/Db.php');
if(isset($_REQUEST))
{
error_reporting(E_ALL && ~E_NOTICE);
$words = explode('-', $_POST['data']);
//add code to update db
}
?>

how will i pass a javascript variable to codeigniter controller function

i cant pass the variable to my controller function.please help
<input type="button" id="mydate" name="mydate" value="<?php echo $dat;?>" class="monthYearPicker" />
script:
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: $(this).val()
},
success: function (msg) {
console.log(msg);
}
});
});
how will i take this javascript variable var textBoxVal = $(this).val() in my controller function.
controller:
public function selectallbudget(){
$mydate= $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
With the help of ajax you can do it.
FIRST:
--------------------------------
<!--write this code in you header-->
<input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$.ajax({
url: base_url + "controller_name/function_name", // define here controller then function name
method: 'POST',
data: { date: dateValue }, // pass here your date variable into controller
success:function(result) {
alert(result); // alert your date variable value here
}
});
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
--------------------------------
SECOND: if you want to load any html code then you use this method otherwise above first method
--------------------------------
<!--write this code in you header-->
<input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$( "#mydate" ).load(
base_url + "controller_name/function_name", // define here controller then function name
{ date: dateValue }, // pass here your date variable into controller
function(){
// write code on success of load function
}
);
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
Your code is almost okay. There is only one change in your controller code:
Controller:
public function selectallbudget(){
//$mydate= $_POST['val']; This is not PHP this is codeigniter
$mydate = $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
Please make use of ajax. This problem has already been discussed here. Please refer it.
Pass Javascript Variables tp PHP Controller in Code Igniter
What you're doing wrong here is $(this).val() to pass on the input's value.
The this object's scope keeps on changing, and is quite different when you try to access in
data: {
val: $(this).val()
}
It's rather trying to access the current object at hand.
Solution's pretty simple though (since you're already initialising textBoxVal to the input's value.
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: textBoxVal
},
success: function (msg) {
console.log(msg);
}
});
});

Manage json data outside ajaxform

I am using the well known ajaxForm Jquery Form Plugin (http://jquery.malsup.com/form/). I 'll present to you my code:
HTML code:
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
}
</script>
PHP code:
...
$result=$db->query($query);
if ($result->num_rows>=1)
{
$counter=0;
while ($row = $result->fetch_assoc()) {
$counter++;
$data1=$row["req_created"];
$data2=$row["subject"];
$temp[$counter] = array(
'elem1' => $data1,
'elem2' => $data2,
);
}
echo json_encode($temp);
}
As you may see from the above code, $temp is passed to var data inside function processJson. I'd like to know if array $temp is accessible outside processJson? For example, I want to choose $temp[3]["elem2"] upon a button click, however is it possible to get this data without searching again the database? If yes, how?
Thank you very much
You can have the data in variable, this will be like temporary storage.
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
var tem_data;
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
tem_data = data;
}
// Use tem_data anywhere;
</script>
But only last requested data will be the tem_data.
If you want all data then do it in array with array push method

How to call php function from JavaScript function? [duplicate]

This question already has answers here:
Javascript and PHP functions
(7 answers)
Closed 9 years ago.
In my index.php file, I have a php function "InsertTheRecord" which gets a parameter and insert it into the database. It return 1 if that parameter is inserted successfully otherwise 0.
I have following JavaScript function "InsertRecord" in same index.php from where I want to call php InsertTheRecord function. How can I call php function from JavaScript function?
My JavaScript function:
function InsertRecord() {
var myParameter = 40;
var result = ////call InsertTheRecord(myParameter) //I don't know how to do this?
if result == 1 { //do something}
else { //show error message}
}
php server side scripting language and javascript is client side scripting language
you can do this by ajax call(Jquery)
<div id="yourdiv"></div>
var data ="hello world";
var data2="hello all";
function run(){
$.ajax({ url: 'myscript.php',
data: {'q': data,'z':data2},
type: 'post',
success: function(output) {
alert(output);
document.getElementById("yourdiv").innerHTML += output; //add output to div
}
});
}
myscript.php
<?php
myfun();
function myfun(){
$myvar2 = $_POST['z'];
$myvar = $_POST['q']."how are you?";
echo $myvar."\n";
echo $myvar2;
}
?>
this alert "hello world how are you?"
Try
var result = <?php echo InsertTheRecord(myParameter); ?>
updated after OP's comment
$.ajax
function InsertRecord() {
$.ajax({
type: "POST",
url: "your_php_page.php",
data: "arg1=id&arg2=name",
success: function (data) {
var myParameter = 40;
var result = data;
if result == 1 {} else {}
}
});
}
PHP is serverside,
JS is clientside,
So the PHP works first, after that the JS works dynamically in the browser.
You cannot call the PHP function in runtime. But you can use AJAX which can do that. Check this out: http://www.w3schools.com/ajax/ajax_aspphp.asp
What if you echod the myParameter to a hidden input field and then grabbed it with javascript:
HTML/PHP file:
<input type="hidden" id="myParameter" value="<?php echo InsertTheRecord(myParameter); ?>"/>
In Javascript:
function InsertRecord() {
var myParameter = 40;
var result = document.getElementById("myParameter").value();
if result == 1 { //do something}
else { //show error message}
}
It is not possible
Javascript is client side scripting language where PHP is server side scripting language
But, you can try AJAX methods to get similar results where you can pass variables same as function
as function myfunction(var1, var2 ,....){return var1*var2}
using ajax, you can run a php script externally on button click
$.ajax({key:var},function(result){alert(result)});
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
http://www.tutorialspoint.com/ajax/

Categories