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

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
}
);

Related

How can I grab a div in PHP that's in a loop within a javascript function

Below is the code.
under the function there is a resultContainer.innerHTML that populates a list of QR codes scanned. How can $_POST the values in PHP so that I can send it in an email format? I tried adding a name within the div (<div **name="qrOutput"**>[${countResults}] - ${qrCodeMessage}</div>) but PHP does not pick it up. Only returns an empty string.
I also tried giving the <div id="qr-reader-results"></div> element a name but because the output is within another div inside this div I also got an empty result.
Thanks a lot for any help.
<!-- start -->
<div id="qr-reader" style="width:500px"></div>
<div id="qr-reader-results"></div>
<div id="root"></div>
<script>
function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete" ||
document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
docReady(function() {
var resultContainer = document.getElementById('qr-reader-results');
var lastResult, countResults = 0;
function onScanSuccess(qrCodeMessage) {
if (qrCodeMessage !== lastResult) {
++countResults;
lastResult = qrCodeMessage;
resultContainer.innerHTML += ***`<div">[${countResults}] - ${qrCodeMessage}</div>`;***
}
}
var html5QrcodeScanner = new Html5QrcodeScanner(
"qr-reader", {
fps: 10,
qrbox: 250
});
html5QrcodeScanner.render(onScanSuccess);
});
</script>
<p id="QRout"></p>
You can store your results in an other variable when you add it to the DOM.
Declare a variable to store your results
var myResults = [];
When you add the result to the DOM add also the results in array variable
// ...
resultContainer.innerHTML += `<div>[${countResults}] - ${qrCodeMessage}</div>`;
myResults.push({count: countResults, message: qrCodeMessage})
Then you can use myResult var on a POST request
myCustomPostFunction('/yourUrl/', myResult);
The "myCustomPostFunction" will depend on the way you want to send the data
Check this codepen: https://codepen.io/zecka/pen/VwKNpze
Post request like a form submit
If you want to send the data to the current page like a form post, you can find an example here: https://stackoverflow.com/a/133997/2838586
Post request to a rest api
Fetch: POST json data

Store value from multiple select element value into array in MongoDB using mongoose schema

hi everyone thanks in advance,
I have an HTML form with a div element which has a select tag and two buttons for + and -. The user can click on the + button to duplicate select tag(up to 5 times). I need to store the value from select tag to store in MongoDB using mongoose. I am not sure how I can get this value in JS and store in the variable to pass into MongoDB.
pug file
div(id='divDay1')
button.btnDay1(type='button' onclick='appendRow(this)') +
button.btnDay1(type='button' onclick='removeRow(this)') -
label(for='Day1') Day1:
div
Select#Day1.form-control1(type='select' name='Day1' required='true' )
for task in tasks
option(value=task._id) #{task.TaskName}
// JS code
var x=1;
//Add select list
function appendRow(elem)
{
//get parent node
var parent = elem.parentNode;
//console.log(parent);
//get last child element
var l=parent.lastChild;
//console.log(l);
//var d = document.getElementById(parent.id);
var s = document.getElementById( l.firstChild.id ).cloneNode(true);
s.id = "Select"+x;
//var s1=document.getElementsByClassName("form-control1")
//console.log(d);
//console.log(s);
//Add only 4 child elements
if(l.childElementCount<4){l.appendChild(s);};
//increment x
x++;
};
// remove select list
function removeRow(elem)
{
//alert("JS file Load");
var parent = elem.parentNode;
//get last child element
var l=parent.lastChild;
// remove last child element, Remove upto 1 element
if(l.childElementCount>1){l.removeChild(l.lastChild);};
};
Use this code snippet to get form data in an array
function getSelectValArr() {
var selectValArr = [];
$(':input', $('#div1')).not('button').each(function() { selectValArr.push($(this).val());});
return selectValArr;
}
Make sure jQuery has been included in your html.
Then use this array to send data to server.
var setting = {url: 'your_api_url', data: {"someKey":
getSelectValArr() }, method: 'POST', success: function(response) {},error: function(error) {}};
$.ajax(setting);

Passing a jquery variable

i'm having trouble with the following jquery code
$this->registerJs(
'jQuery(document).ready(function($){
$(".member").on("change",function(){
var id = $(this).attr("id");
// alert(id);
var n = $(this).val();
// alert(n);
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation','id'=>'+id'])
.'&name="+id)
});
});'
);
i want the ajax link to be like this http://192.168.1.4/~user/church/backend/web/death/stl_set_relation?id=20&name=1
but with my code i'm not able to pass value of id correctly.
what my code creates is the following url
http://192.168.1.4/~user/church/backend/web/death/stl_set_relation?id=%2Bid&name=20
i also tried like this
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation','id'=>'"+id"'])
.'&name="+id)
but it didn't give me the desired result
how can i pass the value of id correctly?
try like this may be it will work..
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation','id'=>'"+id+"'])
.'&name="+n);
You can do this in another way that is by using yii\helpers\Url class.
For example :
$this->registerJs(
'jQuery(document).ready(function($){
$(".member").on("change",function(){
var id = $(this).attr("id");
// alert(id);
var n = $(this).val();
// alert(n);
$.post( "'.Url::toRoute('death/stl_set_relation').'", { id: id, name: id });
});
});'
);
I solved the problem using following code
$.post("'.\Yii::$app->getUrlManager()->createUrl(['death/stl_set_relation'])
.'?id="+id+"&relation="+n)
Try this line
$.post("<?php echo \Yii::$app->getUrlManager()->createUrl([\'death/stl_set_relation\']) ?>?id="+id+"&name="+id).
Whatever you are writing in single quotes here will be printed as it is in the JS. You are printing + sign as it is here. Also you are using id inside PHP scope which should not be the case.

How to pass javascript array variable through jquery $.window url to codeigniter controller?

I have a list of students with a corresponding check box each. The check box value contains students id that I need to pass to my controller function. I have a javascript code that detects the check box checked values and stored it to a javascript array variable. The javascript array variable will then be passed to the $.window url with a url address heading to my codeigniter controller function. This works fine when you choose the first student, it will show the student id via var_dump method, however, if the second or third and so on student is chosen, it says the uri you submitted has disallowed character. The same response when you checked all check boxes. The javascript array variable seems to passed only a single value to my codeigniter controller function taking just the first value of the student list. How I would be able to pass also the 2nd, 3rd and so on checked values or even to pass javascript array variable to codeigniter controller function through javascipt url with $.window. Images and codes are shown below. Thanks a lot.
Image choosing just the first student list
Controller output image after clicking send email button
Image choosing the second student
Controller output image after clicking send email button
Image choosing all student list
Controller output image after clicking send email button
Javascript:
<script type="text/javascript">
$("#send_email").click(function(){
var cboxes = document.getElementsByName('student_id[]');
var checked_val= [];
var unchecked_val=[];
var len = cboxes.length;
for (var i=0; i<len; i++) {
(cboxes[i].checked) ? checked_val[i]=cboxes[i].value:unchecked_val[i]=cboxes[i].value;
}
$.window({
title: "Coursebooking",
url: "<?php echo base_url() ?>student_controller/pop_val/"+checked_val,
});
});
</script>
Controller:
function pop_val(){
$stud_id = $this->uri->segment(3);
var_dump($stud_id);
}
try this,
var array_val = $('input[name="student_id[]"]:checked').map(function(){
return this.value;
}).get();
$.window({
title: "Coursebooking",
url: "<?php echo base_url() ?>ajax_student_controller/pop_val/" + array_val,
........
localhost/coursebooking/ajax_student_controller/pop_val/338,339 This kind of url causes the uri disallowed character error. A comma between the numbers 338 and 339. To solve this is just to add comma character in config.php file in $config['permitted_uri_chars'] = 'a-z 0-9~%.:_+-'; and then use explode function in your controller function to separate the comma separated values. Here are the output:
Image of a var_dump output after checking 3 check boxes and adding comma character in the config.php file $config['permitted_uri_chars'] = 'a-z 0-9~%.:_+-,';
Image of a var_dump output to separate comma separated values into array indexed values using explode function.
Controller Code:
function pop_val(){
$stud_id = $this->uri->segment(3);
$split_val = explode(',',$stud_id);
var_dump($split_val);
}
My revised javascript code. However, this changes only applies in getting the second value of the student list being checked, the same as getting the right value of the 3rd student list being checked. But checking all check boxes together returns a uri error saying "The URI you submitted has disallowed characters".
<script type="text/javascript">
$("#send_email").click(function(){
var cboxes = document.getElementsByName('student_id[]');
var checked_val= [];
var unchecked_val=[];
var array_val=new Array();
var len = cboxes.length;
for (var i=0; i<len; i++) {
if(cboxes[i].checked){
checked_val[i]=cboxes[i].value;
array_val.push(checked_val[i]);
}
}
$.window({
title: "Coursebooking",
url: "<?php echo base_url() ?>ajax_student_controller/pop_val/" + array_val,
});
});
</script>
Image choosing the second student on the list
Controller output returns the right value
Image choosing the 3rd student on the list
Controller output returns the right value
Image choosing the all student on the list
Still Controller output returns the uri error
url: "<?php echo base_url() ?>student_controller/pop_val/"+checked_val,
Try:
url: "/student_controller/pop_val/" + checked_val,

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