JavaScript/PHP: Get referral key URL - javascript

I'm working on an ajax (native JavaScript) form. I'm having trouble getting the referral key and sending it to the PHP back-end.
The idea is that the ajax request sends the entire URL (with the form data) as string to the PHP engine. I can then break down the URL in the PHP and extract the key.
Here is what I have so far:
Page url:
http://example.com?ref=gr84r34ijg98g
JS:
// Send the form data with the URL
function getquerystring() {
var email = document.getElementById('email').value;
var URL = document.URL;
qstr = 'email=' + email + '& URL=' + URL;
return qstr;
}
Then, in my PHP, I can retrieve the form data and url:
$email = $_POST['email'];
$url = $_POST['URL'];
How can I then break-down the URL, so as I only have the code at end as string? I was thinking I could break-down the URL in JavaScript before sending it, although I thought it might be easier to do that part with PHP.
Something like a preg_match() that removes "http://example.com?ref=" would probably do. Although not really sure how to do that.

Yes, you can get the value of ref in Javascript
function getquerystring() {
var email = document.getElementById('email').value;
var URL = document.URL;
var URL_arr = URL.split('ref='); //<-- URL_arr[1] will give ref string
qstr = 'email=' + email + '&URL=' + URL;
return qstr;
}

function getquerystring() {
var email = document.getElementById('email').value;
var URL = document.URL;
qstr = '?email=' + email + '& URL=' + URL;
return qstr;
}
try this.
$email = $_GET['email'];
$url = $_GET['URL'];

There is an extra space before URL .. and you should encode it with encodeURIComponent. Update this line
qstr = 'email=' + encodeURIComponent(email) + '&URL=' + encodeURIComponent(URL);
And on php side
$url = url_decode($_POST['URL']);
$email = url_decode($_POST['email']);

Try this:
var query = window.location.search.substring(1).split('&');
var ref = '';
$.each(query, function(i, v) {
v = v.split('=');
if (v[0] === 'ref') {
ref = v[1];
return false;
}
});
console.log(ref);

Why don't you just do the following in PHP (place it in either a header (if you want it to work on all pages) or at the top of index.php after all your includes :
<?php
$ref = (isset($_GET['ref']) && strlen($_GET['ref']) > 0) ? trim($_GET['ref']) : null;
//Process what ever you wanted to process from the beginning if you had a referral code
if(!is_null($ref)) {
// do your action
}
?>
Using the above you don't really need any kind of javascript.

Related

Attempting to Post String to PHP dynamically

Using JavaScript only I want to POST a string to php file and redirect to it at the same time, however, my php file is not picking up the information.
JavaScript:
var data = "&id=" + obj.id;
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
form.value = data;
document.body.appendChild(form);
form.submit();
};
redirect("summary.php","POST");
And the PHP code is simply (NO ERROR HERE, JUST FOR CONVENIENCE):
$id = $_POST['id'];
EDIT:
The problem is that the PHP file is not picking up the name "id". There is no problem in the php file or how I structure my data.
You made a small typo. ALthough it is a huge problem. In PHP you create variables using the $ sign.
var data = "id=" + obj.id;//you don't necessarilly need the & as you are only passing one item(value)
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
//form.value = data;//this won't work. form does not have value attribute:
//create input element
var i = document.createElement("input");
i.type = "text";//set type.
i.name = "id";//set name of the input
i.id = "id";
i.value = obj.id;//set value of input
form.appendChild(i);//add this input to the form
document.body.appendChild(form);//add the form to the body
form.submit();//dynamically submit
};
redirect("summary.php","POST");
In your php script, access it like
<?php
error_reporting(E_ALL);//show all errors and notices
$id = $_POST['id'];//you forgot the $ sign
//for debugging, check the post array
print_r($_POST);
?>
EDIT:
Make sure the obj.id is not null
That's not how you pass the data. value is a property of a form's input element, not the form itself.
So remove the line form.value = data; and replace with
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'id';
input.value = obj.id;
form.appendChild(input);
Now you should be able to get $_POST['id'].

Append image in function jquery

Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.

Initiate Mail From Javascript

I have a button click event in jquery, Inside which I want to initiate my mailbox on it's click with a particular text as the mail's body that is stored in a variable.
Following is my code:
$('#myButton').click(function(){
$('#btnLaunchEmail').hide();
if (strExternalZippedLink.trim() != '') {
//Here I have to initiate the email
}
})
I tried a lot of things but didn't worked . Can anyone help.
Try Below code:
if (strExternalZippedLink.trim() != '') {
//Lunching the email
var aLink = document.createElement('a');
aLink.href = 'mailto:?body=' + strExternalZippedLink;
aLink.click();
}
strExternalZippedLink will be shown in the body
You need to use a mailto URL. Wiki article: http://en.wikipedia.org/wiki/Mailto
$('#myButton').click(function(){
$('#btnLaunchEmail').hide();
if (strExternalZippedLink.trim() != '') {
var to = "someone#example.com";
var subject = "This is my subject";
var myBody = "This is the message body";
window.location = "mailto:" + to +"?subject=" + subject + "&body=" + myBody;
}
})

how to change in below url redirect script

I have a url redirect script that works very well, but i want some change in it.
when i redirect outgoing link then at the end of redirected url i got something like '#lcinside'
example
http://dl.dropbox.com/u/36139836/unknown.html?urlc=http://imgur.com/
goes to
http://imgur.com/#lcinside
but i want to put #lcinside before url start.
example
#lcinsidehttp://imgur.com
i want to put adf url redirect link instead of #lcinside.
how can i put #lcinside before url .
below is script.
please help me.
<script>
function gup(sName)
{
sName = sName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var sRegEx = "[\\?&]" + sName + "=([^&#]*)";
var regEx = new RegExp(sRegEx);
var aResult = regEx.exec(window.location.href);
if(aResult == null)
{
return "";
}
else
{
return aResult[1];
}
}
if(gup("urlc") != "")
{
window.location = gup("urlc").replace("lcamp", "&") + "#lcinside";
}
</script>
If you are just trying to scrub the referrer, maybe you should use meta refresh
<meta http-equiv="refresh" content="1;url=http://imgur.com/#lcinside">

Sending URL as a parameter using javascript

I have to send a name and a link from client side to the server. I thought of using AJAX called by Javascript to do this.
This is what I mean. I wished to make an ajax request to a file called abc.php with parameters :-
1. http://thumbs2.ebaystatic.com/m/m7dFgOtLUUUSpktHRspjhXw/140.jpg
2. Apple iPod touch, 3rd generation, 32GB
To begin with, I encoded the URL and tried to send it. But the server says status Forbidden
Any solution to this ?
UPDATE ::
It end up calling to
http://abc.com/addToWishlist.php?rand=506075547542422&image=http://thumbs1.ebaystatic.com/m/mO64jQrMqam2jde9aKiXC9A/140.jpg&prod=Flat%20USB%20Data%20Sync%20Charging%20Charger%20Cable%20Apple%20iPhone%204G%204S%20iPod%20Touch%20Nano
Javascript Code ::
function addToWishlist(num) {
var myurl = "addToWishlist.php";
var myurl1 = myurl;
myRand = parseInt(Math.random()*999999999999999);
var rand = "?rand="+myRand ;
var modurl = myurl1+ rand + "&image=" + encodeURI(storeArray[num][1]) + "&prod=" + encodeURI(storeArray[num][0]);
httpq2.open("GET", modurl, true);
httpq2.onreadystatechange = useHttpResponseq2;
httpq2.send(null);
}
function useHttpResponseq2() {
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
}
Server Code
<?php
include('/home/ankit/public_html/connect_db.php');
$image = $_GET['image'];
$prod = $_GET['prod'];
$id = $_GET['id'];
echo $prod;
echo $image;
?>
As I mentioned, its pretty basics
More Updates :
On trying to send a POST request via AJAX to the server, it says :-
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
2 things.
Use encodeURIComponent() instead of encodeURI().
Here is a detailed discussion on this: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
If you are new to JavaScript, use some lib to help you do the AJAX work. Like mootools, jQuery, etc.
Using a POST request solved my issue :)
function addToWishlist(num) {
var url = "trial.php";
var parameters = "prod=" + encodeURIComponent(storeArray[num][0]) + "&image=" + encodeURIComponent(storeArray[num][1]);
httpq2.open("POST", url, true);
httpq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpq2.onreadystatechange = function(){
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
};
httpq2.send(parameters);
}

Categories