Javascript Variable in Ajax Updater - javascript

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

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

Refresh part of my php page with setInterval()

I have a value on my PHP page and I want to refresh it per second with setInterval().
So I actually know how to refresh values with html etc. But now I want to do the same with php values. Here is my code:
<script>
setInterval(function()
{
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
},1000);
</script>
Ofc this isn't working since JS and php arent really great together.
and in my table I just simply have:
<table>
<tr>
<td>Activity:</td>
<td><p id='MachineActivity'></p><?php echo $TimeMachineActive; ?></td>
</tr>
</table>
So the problem now is, it's only refreshing when I press f5. But now I want the autorefresh. I know setInterval() worked for html. Is it possible to get this done for php code?
This should work for you:
JS Code:
<script>
setInterval(function()
{
$.ajax({
url: 'value-generation.php',
type: 'get',
success: function(response){
$("#MachineActivity").html(response)
},
});
},1000);
</script>
value-generation.php code:
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
echo $TimeMachineActive;
?>
This is how you convert php value to javascript value
<script>
setInterval(function(){
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
var n_val = "<?php echo $TimeMachineActive; ?>";
console.log(n_val);
},1000);
</script>
Change console and give it to your desire.
But does this make the loading time more ? Every second you are calling a remote page and checking ?
When you refresh, PHP returns the whole page again, and it cannot refresh parts of the page. So if you want just part of the page refreshed, you'll need to use iframes.
<body>
<h1>This is my main PHP page</h1>
<iframe src="[url-to-another-php-page-with-only-the-timer]"></iframe>
</body>
And then you'll have to do a separate php page with just the timer value, and serve the html with a meta tag - this meta tag will do the refresh. Meta tag is detailed in this ticket: PHP - auto refreshing page
You need to define setInterval function.
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Now call your set interval function and it should work fine.
As you know, a PHP file will make the server generate a page when you call its URI.
The way you are using your script won't make the server "regenerate" the page and update the values.
Assuming this, you can:
Externalize the php code which is in your setInterval function (ex: update_time_machine.php)
Recall the externalized PHP resource(using IFrame or a request)
Update your page through Jquery/JAVASCRIPT using the PHP script output.
Edit: Mihali's answer sounds the cleanest one.
I'm sure this will work for you
<script>
setTimeout(function(){
location.reload();
},1000); // 1000 milliseconds means 1 seconds.
</script>

How to use explode function to delimit and display different values

I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.
I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:
The book, El libro
The man, El hombre
The woman, La mujer
etc.
I would like to break these two values into an array and display them in separate places on my web page.
I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
The script that displays the result:
<script type="text/javascript" src="rantex.php?type=1"></script>
Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?
Thank you, and please excuse my noobness.
The following seems unnecessary, since file() will have already removed new line characters:
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
To break your line, you may instead use:
list($english, $spanish) = explode(', ', trim($txt));
It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?
Heres a quick implementation.
// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)
$sentences = explode("\n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) {
return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) {
return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
Now you can let the client handle the rest, with some basic JavaScript.
// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence
[edit]
You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.
// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
var sentences = <?= json_encode($pairs); ?>;
var random = sentences[Math.floor(Math.random() * sentences.length)];
var elspa = document.getElementById('spanish');
var eleng = document.getElementById('english');
elspa.innerText = random.sentence.split(',')[1];
eleng.innerText = random.sentence.split(',')[0];
</script>
Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to #stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.
The .PHP file is like so:
<?php
$f_contents = file('quotes.txt');
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>
On the .HTML page in the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
(function ($) {
$(function()
{
function load_random_data() {
$.get('random_line.php', function(data) {
var data = $.parseJSON(data);
$('#random_english').text(data.eng);
$('#random_spanish').text(data.esp);
});
}
load_random_data();
$('#get_random').click(function(e){
e.preventDefault();
load_random_data();
});
});
})(jQuery);
</script>
This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:
<td id="random_spanish"></td>
<td id="random_english"></td>
Plus as a bonus the coder threw in a nifty button to refresh the json classes:
<input type="button" value="Get random" id="get_random" />
So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.
Thanks again everyone!

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

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,

Categories