javascript function not taking arguments - javascript

This question is probably more complex than I realize.
When the page loads, it checks for a cookie (usercookie). If it exists, it calls a function in an external .js file. This function is situated in a jquery file and does three things. It hides come stuff, sets a variable (userloggedin) to true, and displays a welcome message to the users. However, its acting very strange. In order for the function to work, I have to define it with a "new" before it like its an object. If I don't do that, it won't work at all. But if I use it, it refuses to take any arguments. Take a look.
Keep in mind that this is situated in a $(document).ready(function() {}
userlogged = new function($name)
{
userloggedin = true;
$('.socialicons').hide();
$('#signup').hide();
$('#login').hide();
document.getElementById('cookieelement').innerHTML = "Welcome back, " + $name + "!";
}
Here is how I call the function from the main document.
<script type="text/javascript" id="cookiescript">
//checks for the usercookie and gets the value as well
var query = true;
if (query === true)
{
cookievalue =
"Seth";
userlogged(cookievalue);
}
</script>
Some of this code was returned from a php query to mysql, but I know that code works fine.
So my question is, how do I create this universal function in the js file that I can call anytime a user logs in somehow (eg. cookie detected, form entry)?

You have to declare a parameter at the declaration part like
function functionname(parameter)

you need to change the method signature to accept a parameter
userlogged = new function($name)
{
userloggedin = true;
$('.socialicons').hide();
$('#signup').hide();
$('#login').hide();
document.getElementById('cookieelement').innerHTML = "Welcome back, " + $name + "!";
}

Related

Understanding Ajax requests to update page content when SQL Query Response changes

I am writing a page update which works with PHP to read a SQL database the page echo's the contents in a div section 'track_data'. yet it doesn't do this update idk
I have JavaScript script which I dont really fully understand and hopeful someone could explain its principally the check response section I think is failing ? :
in my PHP page :
<script type="text/javascript">
function InitReload() {
new Ajax.PeriodicalUpdater('track_data', 'fetch_sql.php', {
method: 'get', frequency: 60, decay: 1});
}
</script>
Thanks for looking and hopefully someone undersstands this and can put a smile on my face for the second time today :)
Steps to fix
Thanks for the suggestions of syntax errors. I haven't really got very far with this here are the changes you suggested which I have changed but I still think there is something wrong with last function as it doesn't update div section.
Code in JS file
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv;
var gContentURL;
var gcheckInterval;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gcheckURL = checkURL;
setTimeout('check();',gCheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gContentUrl,{method:'get', onSuccess:'checkResponse'});
setTimeout('check();',gCheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
}
}
This is the bit I dont understand
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.response.json();/*t.responseText;*/}
});
}
}
Method and Issues
What is transport here and what is t? if it stores the contents of the body text from the second in gCurrentCheck and compares to transport version content then why doesn't it update if its different please which it is if the SQL has created a different page?
I did find this https://api.jquery.com/jquery.ajaxtransport/
First Answer not using Ajax
I was given a neat and JS version as an answer, which is not really what I was looking for. I was hopeful to get the one working with one with Ajax but I appreciate your efforts is very kind. I just really wanted to send a refresh to the div area so that the PHP rebuilt the page from the SQL.
I might have been missing the MIT javascript http://www.prototypejs.org/ lol but I dont think it was.
Just to help:
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. ... Make requests to the server without reloading the page.
Researching
I found this Update div with the result of an Ajax-call but it did not really explain as the OP was using PHP like me not HTML. The answer was given:
$.ajax({
url: 'http://dowmian.com/xs1/getcam.php',
type: 'GET',
data: {id: <?php echo $cam_id; ?>},
success: function(responseText){
$('#update-div').html(responseText);
},
error: function(responseText){
}
});
I dont think above it answered posters question or mine as ajax is a server based push how is this relevant? as if its PHP driven the needs a refresh at server to refresh the contents not to provide new html. It is this refresh I am not interested in to re-copy PHP code elsewhere in JS as its already in my PHP. Does that make more sense?
Update
I did find a bracket missing and a set of single quotes inserted by editor. Which I have updated above but there was no significant change.
Cheers Nicolas . I am still hopeful that someone knows about Ajax as it sits underneath these technologies. I have a server side PHP file that I was hoping to use AJAX to pull just the PHP from the section it was pointing to an gUpdateDiv . As its derived from the server and created on the fly from SQL. I dont see how your answer would help push this data back in to the from the server . The $(gUpdateDiv).innerHTML was supposed to be acted upon not the whole page . What I am unsure of is how a trigger from this can update timer just this $(gUpdateDiv).innerHTML . I am also not aware if a server based refresh would do this or if the transport id provided from the file would be able to deliver just that . I think I am missing something a vital part that I dont have or have grasped yet. The reason there is two timers is effectively it checks the same file at a different point in time as its created by PHP it might be different from the first if it is i.e. the SQL data has changed, I want this to update this $(gUpdateDiv).innerHTML with the data which it compared it to the second 'Get' in the second request. It sounds, simple in practice but have got stuck comparing two versions and insuring second version gets used .
Further update placing an alert in the Javascript file did not pop up like it does here https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert however the same alert in the initiating PHP worked fine and created the alert. called the same function from the main PHP nd the alert occurred so the JavaScript is running next visit F12 on the page to see if there is any warnings or errors. Ok after adding JQuery which I thought I had added this started working however It is not doing what i Expected it to do. As the contained both text and graphics created by PHP I expected this all to be updated The graphics are not the text is any ideas? .
Further to the image problems I placed an extra line to update the image however I used this too in PHP
<script type="text/javascript">
//initpage() ;
function updateArtworkDisplay() {
document.querySelector('#np_track_artwork').src = 'images/nowplaying_artwork_2.png?' + new Date().getTime();
}
</Script>
But it didnt work to update the image in php?
<div id='outer_img'><img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png' alt='Playing track artwork' width='200' height='200'></div>
in js change
/ looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
updateArtworkDisplay(); // fire up the redraw in php file.
}
}
Nearly there it does almost what it needs to apart from the redraw which is not happening
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv="";
var gContentURL="";
var gcheckInterval=0;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gCheckURL = checkURL;
setTimeout('check();',gcheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gCheckURL,{method:'get', onSuccess:'CheckResponse()'});
setTimeout('check();',gcheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
$time = new Date().getTime();
new Ajax.Request('outer_img', {method: 'get',onSuccess:function s() {
$('outer_img').innerHTML = "<img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png?t='"+$time+" alt='Playing track artwork' width='200' height='200'>"}
});
}
}
GIVEN UP WITH THIS PLEASE DELETE MY PERSONAL INFORMATION AND POSTSript-fetch-async-await/

PHP, Javascript, mysql, and selection lists

I'm working on a piece of some software that will grab information from a mysql database and throw it onto our form dynamically. I'm running into a couple problems, though. I'll give a quick rundown of some functionality.
When the form loads, we have a ton of selection lists. These are all populated through arrays with various keys/values in php. When I select an option from one list, we'll call it a "customers" list, on-click I need to check if that customer has a special flag (stored in the database), and update another selection list based on that data.
How I understand the core of my solution is I need to have a javascript trigger on-click, which I have. The function that is called references a php page that handles the database query through a class and it's function.
<script>
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer='+customer);
}
</script>
This function then talks to my php. The CustomerProvider class works 100%. I have tested that thoroughly on other pages. The problem arises when I try to actually get my selection list to change.
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != '')
{ ?> <script>var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';</script> <? }
else return;
}
?>
I'm coding in javascript literally for the first time ever and they kinda just threw me on this project. I know that my portion isn't being read as html or output as I intend. I know that every other part of the php and the first bit of javascript seems to be executing okay. Any help would be incredibly appreciated.
You seem to be on the right track but just for your own sanity here are a couple pointers. You shouldn't be returning Javascript from PHP for a situation like this. Instead you should be relying on Javascript promises to wait for a response containing just the data and continue the execution of your client code once you have your values returned. Take a look at this:
<script>
function setService() { // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.get('thePage.php?key=setService?customer=' + customer, function(data) {
console.log(data + ' was returned from your php script!');
if(data.hasContract=='1')
$('#ticket_service').val('Contracted Hours');
else
$('#ticket_service').val('No Contracted Hours');
});
}
</script>
And then your PHP script will just look like this:
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){
$hasContract = 1;
}
else
$hasContract = 0;
echo json_encode(array('hasContract' => $hasContract));
}
?>
Therefore returning only the data needed for the client app to continue... not application logic
Your code isn't doing anything with the output of the PHP script. If you want the output to be inserted somewhere in the DOM, you should use .load() rather than $.get.
$("#someelement").load('thePage.php?key=setService?customer='+customer);
This will put the output into <div id="someelement">. If the output contains <script>, the script will be executed.
If you know the result is just a script, you could use $.getScript() instead of $.get. Then the output should just be the Javascript, not enclosed in HTML tags like <script>.
The problem here is that you are not using the result from the server. Your JavaScript may indeed be correct, but the browser never sees or runs it. From the docs:
Request the test.php page, but ignore the return results.
$.get( "test.php" );
Try this code, which utilizes the $.getJSON() shortcut function. I've written two versions, which you can see commented in the code. One moves the logic for determining contract status into the JS. Either should work.
PHP
<?
if(isset($_GET['key']) && $_GET['key'] == 'setService')
{
$customer = $_GET['customer'];
$customer = intval($customer);
$s = CustomerProvider::getHasContract($customer);
// Default output
$output = array('hasContract' => false);
// Customer has contract
if ($s != '')
$output['hasContract'] = true;
echo json_encode($output)
// Alternative: PHP just returns getHasContract, JS determines action
// (this would replace $ouput, conditional, and echo)
// echo json_encode(array("hasContract" => $s));
}
?>
JavaScript
function setService()
{ // The customer's "id" grabbed from the aforementioned customer selection list
customer = $('#customer').val();
$.getJSON('thePage.php?key=setService?customer='+customer, function(result) {
// Alternative
// if (result.hasContract != "")
if (result.hasContract)
{
var element = document.getElementById('ticket_service');
element.value = 'Contracted Hours';
}
});
}
As others wrote, your code doesn't do a thing with the GET variables.
the element "ticket_service" doesn't exists on page and even if it was, the code has no impact on the page that sent the request, you should print/echo the result you want to display/return and then manipulate it with JS/Jquery.
since I'm against GET and pro POST which is safer method, here's an example with POST:
JS:
function postSomthing(customerID){
$.post(
'thePage.php',
{key:'setService',customer:customerID},
function(data){
if(data!='x'){
$('#ticket_service').val(data)
}
else{alert('no ticket');/*whatever you want to do*/}
});
}
PHP(thePage.php) :
if(isset($_POST['key']) && $_POST['key'] == 'setService'){
$customer = intval($_POST['customer']);
$s = CustomerProvider::getHasContract($customer);
if ($s != ''){echo 'x';/* false, or whatever you want*/}
else{echo 'Contracted Hours';}
}
notes:
you should create an element with the id "ticket_service" in the viewed page and not in the backstage one.

accessing object properties in javascript

I wrote this code and when I want to access object properties it keep saying undefined. can anyone point out my error.
function readXML()
{
var xml=new XMLHttpRequest();
xml.open('GET','index.json',false);
xml.send();
var xmlData=xml.responseText;
document.getElementById("demo").innerHTML =
xmlData.firstName + " " + xmlData.lastName;
}
the json file
{firstName:"John", lastName:"Doe", age:20}
I remembered reading about this because of trying to use it, you are missing a simple function called every state change for the request
Edit, corrected function
Realizing you have ,false) set for the async option, it has been deprecated and is no longer supported, so this function is mandatory.
xml.onreadystatechange = function()
{
if (xml.readyState == 4 && xml.status == 200)
{
var xmlData = JSON.parse(xml.responseText);
document.getElementById("demo").innerHTML = xmlData.firstName + " " + xmlData.lastName;
}
};
This code goes right above the xml.open() command.
This function is called on every change of the state of the request, you can also modify it to give an error if you do not receive a xml.status of 200, which means a successfully requested page.
This snippet was edited to fit your function, grabbed from an official website for documenting languages like PHP, JavaScript, JQueryJS, etc.
http://www.w3schools.com/json/json_http.asp
Edit no. 2
Discovered your json wasn't formatted properly, the values and keys must be encased by " or '. Here is what it should look like:
{"firstName":"John","lastName":"Smith"}
from that you can either use xmlData.firstName or xmlData["firstName"] they both do the same thing.
Next, the async parameter has been deprecated, and is completely asynchronous so you have to change your xml.open() to this:
xml.open('GET','index.json');
Finally for the onreadystatechange i modified it to fit your script, the edit is applied above in my previous one.
----- Want to see it live? -----
I have uploaded and corrected it to fit your function, it works and is fully function, with no errors processed, here is a link:
http://js.x10.bz/helpstack/35739016/main.html
Here is the link to the source code:
http://js.x10.bz/helpstack/35739016/main.txt
And finally, here is what the JSON file should look like:
http://js.x10.bz/helpstack/35739016/index.json

auto reload 'php' in javascript

I am developing my laravel app. I have this function in javascript-
function abc(){
var x = '<?php ($user && ($user->first_name == "" || $user->number == "")) ?>';
}
Now, when the page is loaded, the variable 'x' is loaded with either '1' or '0'. I want the php to be rendered everytime I call the function abc(). So, for instance, at time of page load 'x' is '1' but if the function is called after 20 secs of page load, I want the php to be rendered, so that the value of 'x' can change based on the changes happening on server in those 20 secs.
Btw, I am aware of ajax. I am asking if there is some simpler solution.
function abc(){
$.ajax({url:"phpfile.php",success:function(result){
$("div").html(result);
}});
}
setTimeout(function(){ abc(); },20000);
Try this using ajax
This isn't possible without AJAX because the JavaScript code is static once loaded on the client browser. The values do not change unless additional script executes to override those values asynchronously.
As you're using Laravel, take a look at setting up a route to return the value you're looking for. There are plenty of examples here: http://laravel.com/docs/routing . As your example is referring to users, take a look at this doc on RESTful controllers, as the example there is specifically a UserController. http://laravel.com/docs/controllers#restful-controllers
Something like this would let you grab the data you need on the PHP-side (I'm assuming you're checking if the user's initialized):
class UserController extends BaseController {
/* other controller logic above here.. */
public function getInitStatus($id)
{
$user = /* Whatever code you get the user with based on ID */
return Response::json($user && ($user->first_name == "" || $user->number == "");
}
}
Then setup a route like:
Route::controller('users', 'UserController');
Now that you're set on the server-side, there are plenty of ways to just call it in JS (e.g. http://api.jquery.com/jquery.getjson/ ).
function abc() {
$.getJSON( "/users/" + userID, function( x ) { /* do whatever you were going to do with x */ });
}
Ajax is the way to go. Please take a look into other answers.
This is answer is not a general good approach, but it answers what you exactly ask. Im just posting this cause i don't know what you have in mind so it may be usefull for you.
start by putting your js function in onload of body and change the name a bit
<body onload="original_abc()">
then change your js function name accordingly
function original_abc(){
var x = '<?php ($user && ($user->first_name == "" || $user->number == "")) ?>';
}
now use this with the name of your original function
function abc()
{
location.reload();
}
as a result, everytime you call abc() the page will reload, and the function original_abc will execute.
may be useful in some very specific cases, but in general, use ajax.

passing a value from one file to another javascript

I have a file called functions.js where I have the functiom sum which computes the score that a student takes at a test. I want that sum to be printed into a table in the file admin.php so that the administrator sees all the scores that each student has.
So how can I pass the sum variable to another file? I tried calling the function using the onlick action but that didn't work
I guess you probably want something like this
document.getElementById('saveScoreButton').onclick = {
var r = new XMLHttpRequest,
message = document.getElementById('message'),
score = sum();
message.innerHTML = 'Saving your score; please wait a second';
r.open('get', 'savescore.php?score=' + score, true);
r.send(null);
r.onreadystatechange = function () {
if (r.readyState == 4 && r.status == 200) {
message.innerHTML = 'Saved your score';
}
}
}
This passes the score to a PHP programme savescore.php when you click a button with id saveScoreButton. The PHP programme then has to retrieve it using $_GET["score"].
Note that this would be easy for the user to trick if they understand javascript and see what is happening. They could just type 'savescore.php?score=100' in the browser's address bar. If you want a secure solution the javascript should only pass the user's answers to the PHP programme, which would then mark the test and sum the results.
It is also possible to use the POST method instead of GET to pass a value:
...
r.open('post', 'savescore.php?score=' + score, true);
r.send('score=' + score);
...
Then pick it up in the PHP programme using $_POST["score"].
As mentioned in comments, if you want to compare/tabulate scores, then savescore.php will need to store the values in a database or file so that they can be retrieved by admin.php.
Javascript is ran client-sided, PHP is ran server-sided. Therefor, you have to code something in your javascript which alters the HTML page returned by the PHP script, displaying the result.
Once all of your files are loaded on the client, there isn't a concept of separate js files. The client (browser + javascript) and server (php) are 2 separate entities. When your data is one place the other has no clue it exists. Either research ajax as a method of communicating between the 2 locations or use a form and submit the page to the server.
Good overview of how the server and browser communicate: How does the communication between a browser and a web server take place?
Basics of Form submission: http://www.htmlgoodies.com/tutorials/forms/article.php/3479121/So-You-Want-A-Form-Huh.htm
Basics of Ajax: http://webdesign.about.com/od/ajax/a/aa101705.htm
Ajax with PHP: http://www.switchonthecode.com/tutorials/simple-ajax-php-and-javascript

Categories

Resources