URL over-writing during every click event - javascript

I have tried history.pushState function to change my URL in the address bar on link click...
Everything went right.
But instead of showing different URL every time as per my desire, it started overwriting.
Here are my codes
$(document).ready(function() {
$('#followers').click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
data = 'page1';
url = 'followers/';
history.pushState(data, null, url);
document.title = 'Followers | <?php echo VISIT_FIRSTNAME;?> <?php echo VISIT_LASTNAME;?> (#<?php echo VISIT_USERNAME; ?>) | <?php echo SITE_NAME; ?>';
$('#data').load('/auth/load/load_followers', {
'username': '<?php echo VISIT_USERNAME; ?>',
'visit_id': '<?php echo VISIT_ID; ?>'
});
});
$('#following').click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
data = 'page1';
url = 'following/';
history.pushState(data, null, url);
document.title = 'Following | <?php echo VISIT_FIRSTNAME;?> <?php echo VISIT_LASTNAME;?> (#<?php echo VISIT_USERNAME; ?>) | <?php echo SITE_NAME; ?>';
$('#data').load('/auth/load/load_followings', {
'username': '<?php echo VISIT_USERNAME; ?>',
'visit_id': '<?php echo VISIT_ID; ?>'
});
});
$('#message').click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
data = 'page1';
url = 'message/';
history.pushState(data, null, url);
document.title = 'Message | <?php echo VISIT_FIRSTNAME;?> <?php echo VISIT_LASTNAME;?> (#<?php echo VISIT_USERNAME; ?>) | <?php echo SITE_NAME; ?>';
$('#data').load('/auth/load/load_message', {
'username': '<?php echo VISIT_USERNAME; ?>'
});
});
});

How history.pushState works is:
If you pass the url params as
history.pushState('page1', null, 'follower/')
history.pushState('page1', null, 'following/')
history.pushState('page1', null, 'messages/')
You will end up concatenating them like: 'follower/following/messages'.
I am assuming from you question, what you need is instead.
history.pushState('page1', null, 'follower')
history.pushState('page1', null, 'following')
history.pushState('page1', null, 'messages')
Remove the trailing /, It will overwrite instead of concatenate.

Related

stripe form not showing when billing name has an apostrophe

I have the following stripe payment form on my page:
stripe.createToken(card,{name: '<?php echo $order->customer['firstname'] . ' ' . $order->customer['lastname']; ?>', address_line1 : '<?php echo $order->customer['street_address']; ?>', address_city : '<?php echo $order->customer['city']; ?>', address_state : '<?php echo $order->customer['state']; ?>', address_country : '<?php echo $order->customer['country']['title']; ?>' }).then(function(result) {
if (result.error) {
// Inform the user if there was an error
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server
stripeTokenHandler(form, result.token);
}
});
});
I recenetly found out that a customer with the last name o'brian was not being shown the portion of the form that allows them to enter the credit card info. It took a while to find out why they were having that issue.
In any case, should I just be removing the apostrophe with a str_replace? That seems a bit strange to have to remove the apostrophe? Or is there something else I should be doing?
The apostrophe matches the single quote that starts the JavaScript string, and ends the string, causing unmatched quotes in the JavaScript.
Use json_encode() to safely translate a PHP value into the equivalent JavaScript literal, rather than echoing the raw value inside quotes.
stripe.createToken(card,{
name: <?php echo json_encode($order->customer['firstname'] . ' ' . $order->customer['lastname']); ?>,
address_line1 : <?php echo json_encode($order->customer['street_address']); ?>,
address_city : <?php echo json_encode($order->customer['city']); ?>,
address_state : <?php echo json_encode($order->customer['state']); ?>,
address_country : <?php echo json_encode($order->customer['country']['title']); ?>
}).then(function(result) {
Isn't it enough to use double quotes instead of apostrophes to enclose strings?
Something like:
stripe.createToken(card,{name: "<?php echo $order->customer["firstname"] . ' ' . $order->customer["lastname"]; ?>"

Redirecting to a php URL after showing JavaScript alert

I am trying to work on a module where there is an option to show the JavaScript alert and then it should redirect to a php $url. My script is attached below.
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');
url = '<?php echo $url; ?>';
window.location='url';
</script>";
It is showing the alert but it's not redirecting.
url = '<?php echo $url; ?>';
You can't nest <?php ... ?> blocks.
Just use the variable. You are in a double quoted PHP string literal, so it will be interpolated.
url = '$url';
window.location='url';
You are trying to redirect to the URL url instead of the value of the url variable.
Remove the quotes.
window.location = url;
Try this
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');var url = '" . $url; . "';window.location=url;</script>";
or you can also do it like
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');
window.location='" . $url; . "';</script>";
You are setting window.location to the value 'url'. Notice the quotes. You should use the declared variable url. Just remove the quotes, as shown below.
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');
var url = '<?php echo $url; ?>';
window.location= url;
</script>";
you should use location.href to redirect to php url e.g
alert("alert your text ");
location.href = <?php echo $url_name; ?> ;
check this
<script>
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed
Successfully.')";
url = '<?php echo $url; ?>';
window.location='url';
</script>";
If you doesn't need to confirm the redirection then using this script might help
<script>
alert('Your message');
setTimeout(locate,3000);
function locate()
{
window.location.replace('PHP URL');
}
</script>
If you need to confirm the redirection
if (confirm('Go to PHP URL'))
{
window.location.replace('PHP URL'); }
else
{
/* Do Something Else*/
}

Empty jQuery Autocomplete Array in Firefox and Chrome - Works in Safari

My php invoicing system uses jQuery autocomplete to lookup a customer's name from my database. The layout of the pages is like this:
invoice.php - contains the variable 'customers' and the php database select script
invoice.js - this contains the jQuery on focus command
In Safari everything works fine. I have used the console to see the variables logged - example (CUSTOMERS – ["Paul Smith"] (1))
But in Chrome and Firefox the console shows: "CUSTOMERS" Array [ ]
My code for invoice.php:
var arr_customers = new Array();
<?php $result = mysql_query("select * from customer where breaker='".$_SESSION['breaker_id']."'");?>
<?php $str = ""; $i = 0; while ($row = mysql_fetch_array($result)) { ?>
arr_customers[<?php echo $i;?>] = new Array();
arr_customers[<?php echo $i;?>][0] = "<?php echo $row['customer_name']; ?>";
arr_customers[<?php echo $i;?>][1] = "<?php echo $row['customer_code']; ?>";
arr_customers[<?php echo $i;?>][2] = "<?php echo $row['address']; ?>";
arr_customers[<?php echo $i;?>][3] = "<?php echo $row['uid']; ?>";
<?php if ($i == 0) {
$str = "'" . $row['customer_name'] . "'";
} else {
$str = $str . ",'" . $row['customer_name'] . "'";
}?>
<?php $i++;
} ?>
var customers =<?php echo ("[" . $str . "]") ?>;
and for the invoice.js:
jQuery(document).ready(function($) {
$("#customer_name").on('focus', function() {
console.log("CUSTOMERS", customers);
$( "#customer_name" ).autocomplete({
source: customers
});
});
});
I know I should be using prepared statements as well!

echoing javascript with php including mysql row variables

I'm trying to echo javascript code using php and trying to retrieve data from my database within this very echo-code... Does anybody know what I'm doing wrong? Is it because javascript is only client-side? (Technically, I'm trying to reach the database with php...) I would appreciate some help!
<?php
if($condition == true){
//connect to the database
//-select the database to use
//-query the database table
//-run the query against the mysql query function
//-create while loop and loop through result set
echo "<script>
items_set = [
{
src : '<?php echo ".$row['imageURL']." ?>',
url : '<?php echo ".$row['URL']." ?>',
category: '<?php echo ".$row['DetailCategory']." ?>',
title : '<?php echo ".$row['Name']." ?>',
description : '<?php echo ".$row['Description']." ?>',
price : '<?php echo ".$row['Price']." ?>',
location : '<?php echo ".$row['Postcode']." ?>',
thirdparty : '<?php echo ".$row['ThirdParty']." ?>',
thirdparty_mobile : '<?php echo ".$row['Thirdparty']." ?>'
}
];
jQuery('#list').portfolio_addon({
load_count : 1,
items : items_set
});
</script>";
}}
?>
Thanks in advance!
(In Dreamweaver the colors of the code look right, unlike here)
Make sure you separate what gets executed in your server (PHP) and what is passed to the client and executed in the browser:
<?php if(condition == true){ ?>
<script>
items_set = [
{src : "<?php echo $row['imageURL']; ?>",
url : "<?php echo $row['URL']; ?>",
category: "<?php echo $row['DetailCategory']; ?>",
title : "<?php echo $row['Name']; ?>",
description : "<?php echo $row['Description']; ?>",
price : "<?php echo $row['Price']; ?>",
location : "<?php echo $row['Postcode']; ?>",
thirdparty : "<?php echo $row['ThirdParty']; ?>",
thirdparty_mobile : "<?php echo $row['Thirdparty']; ?>"}
];
jQuery('#list').portfolio_addon({
load_count : 1,
items : items_set
});
</script>
<?php } ?>
Notice I modified your code to make strings variables, given that the $row variable is part of your PHP code, not your JavaScript.
in your php:
//specify header..
header("content-type:application/json");
//create variables for your values
$row['values'];
//create oo array
arrayResult =
array(
array("variable-name" => $variable,"imageURL" => $imageURL)
);
In your html..
//get data using JSON
<script type="text/javascript">
$j.getJSON( "cellJson.php", function( json ) {
$j.each(json, function(i, item) {
//example
var imageURL = item.imageURL;
//then in your script
items_set = [
{
src : ''+imageURL+'',
url : ''+URL+'',
category: ''+DetailCategory+'',
title : ''+Name+''
}
];
jQuery('#list').portfolio_addon({
load_count : 1,
items : items_set
});
});
</script>

AJAX- getting a specific array value in post

Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.

Categories