I have a variable stored username and I wish to pass this through a link to the next page. So I have:
Go!
When you land on register-form.php there is an onload event for the script:
<body onload="inputUsername()">
function inputUsername(){
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
}
However I get an undefined variable error for username.
It seems to me that the URL is not passing the variable correctly. Should I be seeing my actual variable in the address line? Should I be seeing username=myusernameisthis ?
In essence, all I'm after is passing the variable username from page 1 to page 2. That's all.
Parameters passed in a url query string don't get magically loaded into the javascript global scope.
As #Archios says you can parse the query string with javascript with something like:
var username = getUrlVars()["username"];
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
but personally I prefer:
function inputUsername(){
var username= "<?php echo isset($_GET[username])?$_GET[username]:''; ?>";
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
}
what would be even easier, is if you changed:
<input id="inputUsername" type="text" name="username">
to
<input id="inputUsername" type="text" name="username" value="<?php echo $_GET[username]">
and remove the onload event.
the href on the previous page should look something like:
Go!
assuming $username holds the current username
where your script says
username = wordOne + wordTwo + wordThree;
add the line
$('.userNameButton a').attr('href','register-form.php?username='+username);
I think You are trying to get query string variable to javascript not to php. Try something like:
Get query string parameter to js
You are getting an undefined variable error because you have not set the js variable 'username' anywhere. Setting this in the URL is NOT the same as defining a variable.
If you are setting the URL correctly you shouls see something like 'register-form.php?username=Francesca'
You can do this with a mix of PHP and javascript.
In your register-form.php:
register-form.php:
if(isset($_GET["username"])) {
$username = $_GET["username"];
} else {
$username = "not set";
}
in your js (this is better than calling <body onload="inputUsername()">):
window.onload=function(){
var username = <?php echo $username ?>
console.log("I'm running" + username);
document.getElementById('inputUsername').value = username;
};
Better yet would be to not use js at all and do this all in PHP:
<?php
if(isset($_GET["username"])) {
$username = $_GET["username"];
} else {
$username = "not set";
}
?>
<input name="username" id="username" type="text" value="<?php echo $username ?>">
Here ya go. I commented the code so it makes more sense hopefully. Basically, we get the url from the address bar and parse out the pieces one by one to get what we want.
window.ParseQueryString = function () {
//Get the current location in the address bar
var url = window.location.href,
parameterSet = [],
//Get everything to the right of the '?'
parameterString = url.split('?')[1];
//Do we have anything to work with?
if (parameterString) {
//Lets get all individual parameter in the parameter string
var parameterParts = parameterString.split('&');
for (var i = 0, e; e = parameterParts[i++];) {
//Get the parameter key and the value
var parameter = e.split('=');
//Push it into the array
parameterSet.push({
'key': parameter[0],
'value': parameter[1]
});
}
}
//Give me my prettyfied query string array plz!
return parameterSet;
}
console.log(ParseQueryString());
Using this code with a window location of http://www.home.com?s=search&f=images will yield:
[{ key: 's', value: 'search'}, {key: 'f', value: 'images'}]
With this, in your onload callback, you can call the ParseQueryString and look through it to find the username value and populate it to textbox.
Edit
I am added a function that instead of returning an array of key/value pairs, it will return an object with the query string keys as the fields on the object.
window.ParseQueryString = function () {
//Get the current location in the address bar
var url = window.location.href,
parameterSet = {},
//Get everything to the right of the '?'
parameterString = url.split('?')[1];
//Do we have anything to work with?
if (parameterString) {
//Lets get all individual parameter in the parameter string
var parameterParts = parameterString.split('&');
for (var i = 0, e; e = parameterParts[i++];) {
//Get the parameter key and the value
var parameter = e.split('=');
//Add a new field to the object
parameterSet[parameter[0]] = parameter[1];
}
}
//Give me my prettyfied query string array plz!
return parameterSet;
}
Here is a fiddler demonstrating your specific use case. Please note that the fiddler is appending a query string to the url as fiddler wouldn't allow it otherwise. This occurs on line 3
Related
I was wondering why my variable from my php page isn't saving to my .txt. I have posted the code below. All the variables match.
Everytime the new page refreshes, the message disappears and I've checked my txt file, the variables are not saved in an array as it should be.
function updateData() {
$.getJSON("#host/information.txt",
function(data) {
var senator = data[0];
var cmicrophone = data[1];
var microphone = data[2];
var words = data[3];
$("#java").text(senator + cmicrophone + microphone + words);}
);
}
<?php
session_start();
if(isset($_POST["senator"]) && isset($_POST["cmicrophone"]) && isset($_POST["microphone"]) && isset($_POST["words"])) { // If the page receives POST data, it needs to be stored
$senator = $_POST["senator"];
$cmicrophone = $_POST["cmicrophone"];
$microphone = $_POST["microphone"];
$words = $_POST["words"];
$data = json_encode(Array($senator, $cmicrophone, $microphone, $words)); // Put values into an array and encode it for storage
file_put_contents('information.txt', $data); // Put the JSON-encoded array into a text file. This function replaces the contents of the text file, which is exactly what is needed in this application. To append instead of replacing the contents, you need a FILE_APPEND flag.
} else { // If there's no POST data, the values are retrieved from the storage
$data = json_decode(file_get_contents('information.txt')); // Retrieve the contents of the text file and decode them back into an array
$senator = $data[0];
$cmicrophone = $data[1];
$microphone = $data[2];
$words = $data[3];
}
echo "". $senator. "" .$cmicrophone. "" .$microphone. "";
$wordformat = wordwrap($words, 32, "\n", false);
echo "".$words. "";
?>
If the code is correct, would it just be the
$.getJSON()
location isn't correct? The variables are all correct.
I try to make this query from JavaScript
var subject = document.getElementById("inputUri").value;
var property = "?p";
var object = "?o";
var query = "\
PREFIX dbpedia2: <http://dbpedia.org/property/>\
PREFIX foaf: <http://xmlns.com/foaf/0.1/>\
PREFIX : <http://dbpedia.org/resource/>\
SELECT * \
WHERE {\
"+ subject + property + object +".\
}LIMIT 10";
And I receive the variable ?s from an input form, but when I write another variable name, it doesn't work.
The code for the result is the following:
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function( _data ) {
var results = _data.results.bindings;
var subject = document.getElementById("inputUri").value;
for ( var i in results ) {
var subjectResult = results[i].s.value;
var objectResult = results[i].o.value;
var propertyResult = results[i].p.value;
}
}
});
In
var subjectResult = results[i].s.value;
Is the error, but I don't know to receive the value from my input text to the subjectResult assignation.
I defined the variable which receives any variable name from the input text, by this way:
var str = subject;
var res = str.replace("?", "");
Then in the for loop:
var subjectResult = results[i][res].value;
There is no variable called ?s in your query, so it makes sense you can't retrieve its value.
Depending on the structure of your code, you should be able to use the subject variable directly:
var subjectResult = subject;
var objectResult = results[i].o.value;
var propertyResult = results[i].p.value;
Another option is to create the variable in your query, using BIND:
"SELECT *\
WHERE {\
BIND(" + subject + " AS ?s)\
?s ?p ?o .\
} LIMIT 10"
Not sure what SPARQL server are you using, but when I tried this on Virtuoso, it failed with a confusing error, even though I believe it's valid SPARQL.
Also note that building queries like this from user input leaves you open to injection attacks.
Hi I am trying to get my php variables to echo in my js code. I know technically php doesnt work in js/jquery but I've searched for workarounds and they dont seem to be working as expected. This is what I have --
<script type="text/javascript">
var stR = "<?php echo $htitle ?>";
var seq = "<?php echo $sequence ?>";
var coM = "<?php echo $comment ?>";
mrp_data_callbacks.push( function(index, data, stR) {
data["htitle-" + seq] = stR;
return data;
});
mrp_data_callbacks.push( function(index, data) {
data["comment-seq"] = coM;
return data;
});
</script>
And this is what is printed --
var stR = "testing comments";
var seq = "0";
var coM = "testing";
mrp_data_callbacks.push( function(index, data, stR) {data["htitle-" + seq] = stR;
return data;});
mrp_data_callbacks.push( function(index, data) {data["comment-seq"] = coM;
return data;});
So the php echos correctly when defining the variables but when using them in my functions, nothing works. I tried different combination of things and still nothing.
Basically in my functions I need "coM, seq, and stR" to echo the values.
What am I doing wrong?
EDIT:
This is my goal and what I mean by I need the values to echo. ---
modify to add your custom meta field values.
jQuery(document).ready(function() {
mrp_data_callbacks.push( function(index, data) {
data["hello"] = "world";
return data;
});
});
"Hello" -- My meta key
"World" -- The Value
data["hello"] = "world";
Where it says world, I am trying to have to output of the var(s) I created.
var stR = "testing comments";
data["htitle-" + seq] = testing comments;
The code uses the values you provided, but there is no code that actually calls the callback functions you have defined.
I have taken your code and added some tests around it, so to show that the values are indeed available to the two functions:
// Initialise the array of functions.
// Probably this is done by a library you loaded,
// of which you have provided no information:
mrp_data_callbacks = [];
// --- Original code BEGIN ---
var stR = "testing comments";
var seq = "0";
var coM = "testing";
mrp_data_callbacks.push( function(index, data, stR) {data["htitle-" + seq] = stR;
return data;});
mrp_data_callbacks.push( function(index, data) {data["comment-seq"] = coM;
return data;});
// --- Original code END ---
// Define data
var data = {};
// Call the above functions for testing the result:
mrp_data_callbacks.forEach( function(fun, index) {
fun(index, data, stR);
});
// check if everything worked, and data has received
// the expected properties. We use JSON.stringify to
// have a complete view of the data object:
alert(JSON.stringify(data));
The alert at the end outputs this:
{"htitle-0":"testing comments","comment-seq":"testing"}
So, this proves the values provided by PHP are readily available in the functions, through the variables stR, seq, coM. But you need to actually call these functions to see anything happening in your data object.
NB: console does not refer to what you see in "view source" in your browser, but to the tool in which you can query information about the displayed web document.
Edit
If you want the PHP values to be directly injected in the relevant Javascript functions, then you don't need the Javascript variables (stR, seq, coM), and you can do as follows in PHP:
<script type="text/javascript">
mrp_data_callbacks.push( function(index, data) {
data["<?php echo "htitle-" . $sequence ?>"] = "<?php echo $htitle ?>";
return data;
});
mrp_data_callbacks.push( function(index, data) {
data["comment-seq"] = "<?php echo $comment ?>";
return data;
});
</script>
This will come to the browser as this:
<script type="text/javascript">
mrp_data_callbacks.push( function(index, data) {
data["htitle-0"] = "testing comments";
return data;
});
mrp_data_callbacks.push( function(index, data) {
data["comment-seq"] = "testing";
return data;
});
</script>
I'm picking errors from php file using ajax and i face few troubles. Like in php file i take errors into $email_error and $password_error so i want to return error reports to ajax and assign $email_error to id = "email_errors" and $password_error to id = "password_errors". Maybe someone could explain how i specify what variables i want to return and what id should it take .I will leave some commented code below. Thanks!
php
<?php
if (isset($_POST['email']) && isset($_POST['password1']) && isset($_POST['password2'])) {
$email = trim ($_POST['email']);
$password1 = trim ($_POST['password1']);
$password2 = trim ($_POST['password2']);
}
$email_error = 'No errors<br>';
$password_error = 'No errors<br>';
if (empty($email))
$email_error = ('Pleas fill in email field<br>');
if ($email == 'example')
$email_error =('There already is user with this email<br>');
if (empty($password1))
$password_error = ('Please fill in password fields<br>');
if (empty($password2))
$password_error = ('Please fill in password fields<br>');
$email_error; //this variable must be returned to ajax and assigned to id "email_errors"
$password_error; //this variable must be returned to ajax and assigned to id "password_errors"
?>
javascript
$(document).ready(function () {
$('#push_button').click(function() {
$.post('php.php',
{
email : $('#email').val(), // i take these variables to php
password1 : $('#password1').val(),
password1 : $('#password2').val()
} ,
function ( data ) { //what do i return here?
$('#email_errors').val(data); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data); //how to assign $password_error to #password_errors
}
)
})
})
to return value simply echo the variable with json_encode()
e.g.
$return_array = new array();
$return_array['email_error'] = $email_error;
$return_array['password_errors'] = $password_errors;
echo json_encode($return_array);
in the javascript function (data){}:
function ( data ) { //what do i return here?
$('#email_errors').val(data['email_error']); //how to assign $emaill_error to #email_errors
$('#password_errors').val(data['password_errors']); //how to assign $password_error to #password_errors
}
If you want to return several variables to ajax, you would have to return some json
PHP :
// .. your php code
$ret = array("email_error" => $email_error, "password_error" => $password_error);
echo json_encode($ret);
Be careful, json_encode needs PHP >= 5.2
JS :
$.ajax({
url: "php.php",
type: "POST",
dataType: "json", // The type of data that you're expecting back from the server
data: {
email: $("#email").val(),
password1: $("#password1").val(),
password2: $("#password2").val() // careful, you had "password1" as variable name 2 times
},
success: function(obj) {
// obj is your php array, transformed into a js object
// you may want to use .html() instead of .val() since your errors are strings with html tags - depends if #email_errors / #password_errors are inputs or divs
$("#email_errors").html(obj.email_error);
$("#password_errors").html(obj.password_error);
}
});
In PHP, the following will return nothing:
$email_error;
$password_error;
Your not echo'ing the values or anything. If you want to pass two different values, I'd return a JSON object like so (in PHP):
echo json_encode(array(
'email_error' => $email_error,
'password_error' => $password_error
));
And then in JavaScript, your data should now be a JavaScript object, as jQuery should parse the JSON object and understand it as an object. So you'll be able to do like this in JavaScript:
$('#email_errors').val(data.email_error);
$('#password_errors').val(data.password_error);
If you don't want to use an array, you could create a new object and then pass that object to json_encode.
$obj = new stdClass;
$obj->email_error = $email_error;
$obj->password_error = $password_error;
echo json_encode($obj);
So I need to pass long string variable from JavaScript to PHP, but the URL shows me that its too long. I use this method:
function Fillup(id){
var answer = $('.nicEdit-main').html();
$.get('submit.php?id='+id+'&answer='+answer,
function(data){
$('.answer-div').html(data);
});
};
And grab them at the PHP file:
$id = $_GET['id'];
$answer = $_GET['answer'];
But there are times that answer variable are long html codes. For example I created textarea with text editor options, witch you can see is .nicEdit-main and if there is picture added, then my variable is too long to be passed trough URL. Can someone please suggest me a better method?
You can try this:
function Fillup(id){
var answer = $('.nicEdit-main').html();
$.post('submit.php',
{
id: id,
answer: answer
},
function(data) {
$('.answer-div').html(data);
}
});
};
And in PHP side :
$id = $_POST['id'];
$answer = $_POST['answer'];