Post variables from javascript to php - javascript

I am trying to send my variables to a php file and I want to prompt before submitting to have the user input his name before submitting. The page won't redirect to the php page as listed below. Any ideas why it is not redirecting? Do I need to include a jquery or some other script source I do not know about
var name = prompt("Enter your name to submit score");
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;
also when testing this on the php page with get function it only seems to work if the name variable isn't first. If i have the name,time,moves i get errors.

For sure you have an error on querystring separator. Replace all ? except the first by &
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;

As the other guys have mentioned, you need to separate your URI params with an ampersand, not a question mark.
Further, it would be recommended to encode the value that you're receiving from your user, since you never know if they are going to break your code with values you did not expect.
This can be done with the encodeURIComponent method as such:
var name = window.prompt('Enter your name'),
url = 'test.php' +
'?time=' + sec +
'&name=' + encodeURIComponent(name) +
'&moves=' + number_moves;
location.href = url;
Read more about this function on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
*Fixed the time variable to sec from src

First of all, you're not actually posting them as using this code sends them via the GET method. But that's for precision.
Now your problem is most probably that you should write this :
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;
Note the & separator between the parameters, where you had a second wrong ?

You only need one question mark. After that the multiple variables should be seperated with the & symbol:
window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves;
Hope this helps!

You have to delimit the query string parameters using & instead of ?.
var name = prompt("Enter your name to submit score"); window.location.href = "test.php?time="+sec+"&name="+name+"&moves="+number_moves
IMHO, please consider using the AJAX POST for sending values to server as they are prone to security attacks.

now that you fixed the separators, all the variables passed through the url are considered GET variables so they will be in the $_GET global variable in your php.
To get the variables in the global $_POST variable you would need to use a form with the method set to post or an ajax request that posts them.
HTML
<form id="myform" method="post" action="test.php" method="POST">
<input type="text" name="name" id="nameInput">
<input type="text" name="moves" id="movesInput">
<input type="text" name="time" id="timeInput">
<input type="submit" value="Submit">
</form>
You can still modify the values of the inputs through javascript but you will need to use DOM api methods. There quite a few DOM methods so look through the various references online like the mozilla developers network site
document.getElementById("nameInput").value = "Some Name";
//Though i wouldnt suggest using prompts to get
//data you can still do it
document.getElementById("nameInput").value = prompt("Enter your name");
There are also ways of submitting the form from javascript if needed
document.getElementById("myform").submit();
As for why your page is not changing after changing the href, this is probably due to an error in your javascript which actually makes it so the javascript statement to change the href to not actually execute. You can check for errors by looking in the javascript console.
The console will be in a developer tools window, usually opened by hitting F12 on chrome and IE, firefox and other will have a different shortcut key. If your prompt is showing up, then the error has to be with your string concatenation below it, it will error out if the variables are undefined.
//Will error out because there is no variable someNameVar...
location.href = "test.php?name="+someNameVariableThatDoesntExist;
//in console would see something like
//ReferenceError: someNameVariableThatDoesntExist is not defined

You need to declare sec and number_moves as variables. That's the only problem I see when I tested it.

Related

How to correctly read encoded get varible

I have a search engine that does the following things:
Read an input value and encode it using js, then redirect.
//read and save into `query` var
window.location.href = "/search/" + encodeURIComponent(query);
So if user enters
What is the meaning of & sign ?
The ulrl can't end up like this;
expample.com/search/What%20is%the%meaning%20of%20&this%20sign?
And instead get:
expample.com/search/What%20is%the%meaning%20of%20&26this%20sign%3F
Now when I dump the $_GET['parameters'] i get
string() "search/What is the meaning of "
I expect to get:
What is the meaning of & sign ?
I have tried:
$val = urldecode($_GET['parameters']);
But I have had no luck, Maybe I should change the way javascript encodes the url, what are your suggestions?
PHP decodes URL paramaters automatically into the $_GET superglobal as long as you're using the standard query string syntax. If you use your own syntax, you have to roll your own code (you already have custom code in the input form).
The raw URL can be fetched from $_SERVER['REQUEST_URI'] and parsed with the text manipulation tool of your choice. It's worth noting that this isn't an uncommon set up (many PHP frameworks do things this way).
You've mentioned that you're calling the following to obtain the value of the user's query:
$val = urldecode($_GET['parameters']);
This implies that a URL calling your PHP page would have a shape similar to the following:
http://foo.bar/?parameters=<the query here>
The important thing to include in the URL is ?; when a URL is parsed, the ? signals that whatever comes afterward is a URL-encoded query.
Thus, in your javascript:
window.location.href = "/search/?parameters=" + encodeURIComponent(query);
Then your existing code should work.
Just do
on client-side
window.location.href = "/search/" + query;
and on server-side
$val = urldecode($_GET['parameters']);

Javascript truncating string during concatenation

I have problems with string truncation in my app built with laravel and JS(jquery). At first I thought it was a back end problem (and I asked this question:Laravel Truncating Strings). After careful debugging I noticed there's something wrong in my JS code.
I am trying to pass some string from CKEditor via a JQuery post(AJAX) request to the backend, However in some cases the string is truncated especially with embeds that contains special characters!
Here is the snippet where problems occurs
var content = CKEDITOR.instances.editor.getData();
alert("Content :" + content + "<br> Length :" + content.length);
var data = 'post_id=' + post_id + '&content=' + content + '&_token=' + $('#token').val();
alert("Data :" + data);
alert("Content Again :" + content);
What's happening?
I get string from CKEditor
Alert the content and the length for debugging and all looks good
I concatenate content to the data variable which is later sent in an ajax
request
alert data shows truncated string in certain cases
I check content again its all good but for some reason data was
truncated.
Example ???
I paste this facebook embed in the editor
<iframe src="https://www.facebook.com/plugins/comment_embed.php?href=https%3A%2F%2Fwww.facebook.com%2Ftonyelumelu%2Fposts%2F10154690113371949%3Fcomment_id%3D10154690136096949&include_parent=false" width="560" height="161" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>
Alerting the content shows the correct result without truncating. But alerting the data variable gives
Data :post_id='+post_id+'&content=<p><iframe src="https://www.facebook.com/plugins/comment_embed.php?href=https%3A%2F
clearly the string is being cut around %2F sometimes %3A (another embed I tried)
How data variable looks with normal string (<p> This is some string </p> )
Data :post_id='+post_id+'&content=<p>This is some string</p>
&_token='+$('#token').val()
Please, what am I doing wrong? and generally how can I avoid such truncation in JS I have seen strings truncated several times in different situations that really hard to explain. Thanks in advance
If content has especial characters, let's say it's something like You & I forever, then your data variable would look like this:
post_id=1&content=You & I forever&_token=bla
See the problem? Content is ending right after You, because the ampersand isn't encoded. So you should do something like this:
var data = 'post_id=' + post_id + '&content=' + encodeURIComponent(content) + '&_token=' + $('#token').val();
With that, your data variable would look like this:
post_id=1&content=You%20%26%20I%20forever&_token=bla
And it would all work smoothly
Update
#Piyin's answer above is a better and cleaner way to do it! However I leave my long and boring method it may save for another purpose.
Older Solution (not cool :) )
Because I needed to fix this problem as quick as possible (in production lol) I used this work around! Until we get a better answer if you are in trouble you can use this :)
1) Create a hidden form
<form id="content-form">
<input type="hidden" name="post_id" id="content-post-id">
<input type="hidden" name="content" id="content">
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
2) Use JQuery (or whatever) to pass the data to this form
var post_id = $('#post-id').val(); //get post id
$('#content-post-id').val(post_id); //put in form
var content = CKEDITOR.instances.editor.getData(); //get content
$('#content').val(content); //put in form
3) Serialize the form with JQuery .serialize() (Instead of "manually" doing it)
var data = $('#content-form').serialize();
If you are not using JQuery this may not be cool except you have a substitute for serialize in whatever you are using!
This may not be a good solution but it works! Am sure looking in depth (code) what the serialize() function does can help me(or maybe you) understand how to correctly serialize data in complex situations like the one I had.

Passing variables to Javascript from "pretty" URL

My problem is, I would like to create "pretty" URLs for visitors that look like this:
http://domain.com/Name
I have users that often send friends to my service, and I have been created customized pages for each one with the person's First Name in the headline. E.g., "John, here's an easy way to fix this widget"
I then save the page as an index.html file in a custom folder so the link structure for the custom page is domain/Name with Name being their First Name.
This is getting tedious and I would love to use Javascript to automate the process. However, the only documentation I can find on passing variables to Javascript involves "ugly" domains such as domain/jspass2.html?FirstName=John&LastName=Smith
Is there a way to beautify these domains and still pass the variables to a javascript code that inputs their name into the html code? I don't want to "cloak" an ugly domain (using a href, for example)
Thanks for the help!
Well, you could make it "prettier" by making the querystring cleaner.
example:
http://www.domain.com/?John,Smith
The javascript in your index file can read that.
var getQueryString = function() {
queryString = window.location.search;
queryStringCleaned = queryString.substring(queryString.indexOf('?') + 1 );
return queryStringCleaned;
};
if "http://domain.com/Name" is your domain, variable firstName will have the value "Name".
var firstName = window.location.pathname.match(/([\w-]+)\/?.*/)[1];
You could just take the whole URL in JS, and parse it "by hand". Use this regex (for example) to find the parameters passed.
In addition to Paul, I wrote you something that extracts the first name field from the url you provided. If the format is consistent, and you can obtain the url in javascript, you can use this. You may possibly have to create the page first, then redirect the user because javascript is a client side language and the page will already be rendered.
var url = "domain/jspass2.html?FirstName=John&LastName=Smith";
url = url.slice(url.indexOf("FirstName=") + 10, url.length);
url = url.slice(0, url.indexOf("&"));

quick Jquery .load chat not working

I have the following jquery:
var msg = $("#newmessage").val();
var user = $("#userchat").val();
var filename = "/inc/chat.php?msg="+msg+"&user="+user;
alert(filename);
$("#chatData").load(filename);
when 'msg' does not have a space in it, the #chatData loads fine and posts the variable.
When it does have a space in it, I just get a blank div. With no information in it whatsoever.
if I load up the php file that inserts the data into the DB, and manually type the same GET data, it works fine.
Whats going on?
Try using
encodeURIComponent(msg)
Also consider:
$("#chatData").load('/inc/chat.php',
{ 'msg' : $("#newmessage").val(), 'user' : $("#userchat").val() }
);
URI encoding is done, if needed, by jQuery.
You don't have to worry about URI encoding as the POST method is used since data is provided as an object (source).
In this case POST may be better than GET anyways.
If you were using $_GET in your php file you will need to use either $_REQUEST or $_POST.
you have to encode your message before sending using encodeURIComponent() and decode on server-site using urldecode().
doing this will escape/encode special characters that aren't allowed in an url or that will break your query-string otherwise (like a & in your message that would otherwise start a new argument).
You can use either escape, encodeURI or encodeURIComponent, but escape is the only method supported by every browser, although most modern browsers support the latter.
Reference
Take a look at this document, which does a good job of explaining all three.
The space could be causing an issue - try javascript's encodeURIComponent():
var msg = encodeURIComponent($("#newmessage").val());
var user = encodeURIComponent($("#userchat").val());

saving value from form doesn't work

So, storing a Java String into a form hidden input value. I call said value via javascript and attempt to store it into a var. Strangely, I can display the value via alert but javascript crashes when I try to save it into a var.
The first line is from the initializing jsp file. It does some stuff that gets the string. The string is a list of ints that I plan on splitting in javascript for some stuff.
"<form id = \"listArrForm\"> <input id = \"listArr\" value = "+ output +" type = \"hidden\"></form>"
var listArr = document.getElementById("listArr").value; //Does work
alert(document.getElementById("listArr").value); //Does work
So yea, I'm guessing it has to do with the the type of value being retrieved?
Well, both should work as you can see in this jsfiddle: http://jsfiddle.net/2eWja/
What are you storing in the value that makes the script not work? Are you sure you're not putting quotes in?
what browser are you using? There could be problem for some
Btw using getElementById is known to be wrong. ;)

Categories