php vars are updating but javascript function shows allways first value - javascript

I have a php class that set values and updates them. I use getters methods to access those varibles from a javascript function and show them in screen. My problem is when I launch that javascript code, my vars are shown allways with the first values they get. I've checked them and they are up to date when I call myCreateFunction(); but is like this function launches before the php vars are updated. I'm new in javascript and some help would be appreciated, thanks!
<?php
class TableRows {
public $offerId = 0;
public function setOfferId(){
$this->offerId ++;
}
public function getOfferId(){
$this->offerId;
}
}
$tb = new TableRows();
?>
<script>
function myCreateFunction(string) {
var offerId = '<tr><th>'+<?php echo json_encode($tb->getOfferId()); ?>+'</th></tr>';
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
cell1.innerHTML = offerId;
}
</script>
<script>
myCreateFunction();
</script>
<?php
$tb->setOfferId();
?>
<script>
myCreateFunction()
</script>

Yes, because myCreateFunction is being rendered by your browser on your second call. PHP (server-side) has nothing in common with JavaScript (client-side). Don't mix your code like that.
Instead, you can use setters, getters, and then pass the value to your JavaScript function as parameter.

You have some problem in understanding where you are in your code (in javascript or in php). $tb->setOfferId(); does not modify anything in your javascript. So the second call to myCreateFunction() will be exactly the same.

Related

Using the same counter for a javascript function and a php query

I am seeking to increment a variable (counter) each time a DIV is clicked.
The variable of the counter is used to select a question_id in another table so I need to reference it both in JAVASCRIPT and PHP .
Here is my code:
<script type="text/javascript">
var i= 1;
$(document).ready(function(){
$("#input01, #input02, #input03, #input04, #input05").click(function(){
var value01 = $(this).attr('value');
var value02 = i;
$.post('input_answers.php',{value:value01,id_question:value02});
var value02 = i+1;
});
});
</script>
Below is the query to insert the data ('input_answer.php')
mysqli_query($connect, "INSERT INTO `answers` VALUES ('".$_POST['id_question']."' , '".$_POST['value']."' ) ");
My problem is that I'd like to incremen a variable to display a new question each time one of the DIV is clicked.
Thank you for your help.
Correct way to pass mutliple values to server is:
$.post('input_answers.php',{value:value01, id_question:value02});
Your case:
$.post(
'input_answers.php', // URL
{value:value01}, // data passed to server
{id_question:value02} // third argument, which is NOT passed to server
);
Update: correct way to increase your counter is to wait until request is over and add 1 in a callback:
$.post(
'input_answers.php',
{value:value01, id_question:value02},
function () {
// as your i is a global variable you can increase it here
i += 1
}
);

Unable to access array of entities passed through twig in javascript

I am currently working on a symfony2.0 project. At the moment I am stuck at some point where I want to use some simple javascript within my twig file.
From my controller I pass an array of entities called Machine to the twig file like this:
...
return $this->render('PRwissHostsBundle:mini:editLocation.html.twig',
array(
'form' => $form->createView(), 'id' => $id, 'machines' => $machinesInLoc,
));
My form inside the twig file easily cann acces the machines array. What I now need is to access this array within javascript.
Currently I m doing this like follwing:
<script type="text/javascript">
...
var mach_array = {{machines|json_encode|raw}};
var machine = mach_array[0];
alert(machine.name);
....
</script>
Somehow if I alert the mach_array it says that it is an object. Same result when I alert the machine. What is not possible is to access the machines id or name or whatevers property of it.
I have searched a couple of other questions like this but unfortunatly they were not helpfull regarding an array of entities.
Any help is highly appreciated.
In general, you shouldn't let Twig handle the data formatting unless it's absolutely necessary, for example as a response from a AJAX call.
With that said, your issue lies with how you declare the mach_array.
var mach_array = {{machines|json_encode|raw}};
should be
var mach_array = '{{machines|json_encode|raw}}';
By not wrapping the call to twig, Javascript will make mach_array a Object, its the same as
var mach_array = {"foo" : "bar"}
which resolves to a Object.
So I just solved my problem with the help of Nihilnovi. The problemw as not an empty array like gregory supposed, I just did not realy figure out how to properly use javascript and twig entities. The working code now looks like following:
<script type="text/javascript">
function report(period){
var e = document.getElementById("form_machines");
var selectValue = e.options[e.selectedIndex].value;
var selectText = e.options[e.selectedIndex].text;
if (selectValue != ""){
var table = document.getElementById("uebersicht");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "<b>Name:</b>";
var mach_array = {{machinesAvailable|json_encode|raw}};
{% for machine in machinesAvailable %}
if ({{machine.name|json_encode|raw}} == selectText){
cell2.innerHTML = "<a href='{{ url('PRwissHostsBundle_det_machine', { 'id':machine.id }) }}'> {{machine.name}} </a>";
}
{% endfor %}
cell3.setAttribute('align', 'right');
cell3.innerHTML = "<input type='checkbox' id=machine.id >";
}
}
</script>
Hope this helps some who steps into the same issue!

Copy dynamic field value to another field

I am running a database app (sql backend). One particular form calls a value from another table using the follwing:
<td class=NewSalesOpCompany id="contactPostCode"><#externalfield SQL="Select POSTALCODE from wce_sales s join wce_linkto l on s.UNIQUEID = l.luniqueid left join wce_contact c on l.LEntityID = c.UNIQUEID where (s.UNIQUEID = '<#field field=uniqueid noedit static>')" ></td>
The above code populates the field with post-code data in text format which works fine. I then want to copy the data in that field to another field. I have tried the folwing but failed to get it to work.
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._POSTCODE;
if (oppPOSTCODE != parentPOSTALCODE)
{ oppPOSTCODE.value = parentPOSTALCODE.value;}
}
</script>
When executing the function I get "parentPOSTALCODE.value is undefined" error via firefox. I'm a bit of a newbie at this so any help would be appreciated.
Try this:
<script language=javascript>
function copyPostCode() {
var parentPOSTALCODE=document.getElementById('contactPostCode');
var oppPOSTCODE=document.forms[0]._postcode;
if (oppPOSTCODE != parentPOSTALCODE)
{
oppPOSTCODE.value = parentPOSTALCODE.innerText;
}
}
</script>
Here is the example FIDDLE

populate dropdown onload by passing php array to javascript function

im trying to pass a php array to javascript function onload that will display the js array in a drop down list but now im already doing it for sometime i guess i need to pop it again
first i pass it from one php file to another using this code
header("location: Rules.php?varFields=".serialize($varFields));
secondly i transfer to another variable as it had been passed to the said php file
<?php
$varArray = unserialize($_GET['varFields']);
?>
third part is im tyring to pass it into a jS functon that will then display it to a drop down list
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
and here is the external javascript code
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.stringify(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in varDisplay)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
for the first two part i already tested it and it is working but for the last parts i cant make it work
I think this part looks suspicious
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
maybe
<body id="body" onclick="cmbRuleField(<?php echo json_encode($varArray);?>)">
is more like it.
One more tip, you can see the output on the rendered page to determine what the written out code looks like. So if you see something like:
<body id="body" onclick="cmbRuleField('['a', 'b']')">
you know there is a problem. You want a native Javascript array to be passed like this
<body id="body" onclick="cmbRuleField(['a', 'b'])">
EDIT
After talking on chat it became clear the top portion of OP's code needed a tweak as well.
header("location: Rules.php?varFields=".http_build_query($varFields));
The problem has to do with quotes not being terminated here:
...
<body id="body" onclick="cmbRuleField(\'' + <?php echo json_encode($varArray);?> + '\');" >
...
The JSON created using json_encode will have a lot of double quotes. Try this:
<script>
var array = <?php echo json_encode($varArray);?>;
</script>
<body id="body" onclick="cmbRuleField(array);">
There is a much easier way. Encode the $varArray as direct HTML options before sending to the browser. For instance:
<select id="ruleField">
<?php for ($i = 0; $i < count($varArray); $i++) { ?>
<option value="<?php= $varArray[$i].val ?>"><?php= $varArray[$i].name ?></option>
<?php } ?>
</select>
Might be because you are calling JSON.stringify on something that is already a string?
Also what is myCars?
..
for (var i in myCars)
..
Possibly rename it to varArray.
or rename varDisplay to varArray.
and lastly try calling JSON.parse instead:
function cmbRuleField(varArray)//ruleField
{
var varDisplay = JSON.parse(varArray);
var sel = document.getElementById("ruleField") // find the drop down
for (var i in myCars)
{ // loop through all elements
var opt = document.createElement("option"); // Create the new element
opt.value = varDisplay [i]; // set the value
opt.text = varDisplay [i]; // set the text
sel.appendChild(opt); // add it to the select
}
}
If that didn't work post the html output here so peeps can create a fiddle :)

Javascript Variable in Ajax Updater

I am trying to send the javascript variable 'sortlist' to an Ajax function using the following code:
<div id = "output">Drag to sort</div>
<script type="text/javascript">
var session = <? echo $sesh; ?>;
var track = <? echo $trk; ?>;
var sortlist = "sortlist_" + session + "_" + track;
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
})
</script>
The variable appears to be passing successfully to Sortable.create (because I can sort the boxes on the webpage), but it does not appear to be passing into Sortable.serialize within Ajax.updater (because it no longer writes the sort order values to the database).
This code works when I use the literal value in Sortable.serialize, like
parameters:Sortable.serialize('sortlist_1_1'),
I have tried using sortlist as a variable with and without single and double quotes inside Sortable.serialize to no avail. What is the format required to successfully pass this variable information?
For reference,
My AJAX/javascript experience is about a 1 (scale 1-10); my PHP/MySQL experience is about a 7 (scale 1-10).
Try this:
Sortable.create(sortlist,{
onUpdate:function(sortlist){return function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
};}(sortlist);
})
Let's go one step further then:
function(sortlist){
Sortable.create(sortlist,{
onUpdate:function(){
new Ajax.Updater('output','program_sort.php',
{onComplete:function(request){},
parameters:Sortable.serialize(sortlist),
evalScripts:true,
asynchronous:true}
)
}
});
}(sortlist);

Categories