jquery ReferenceError: is not defined variable as array index - javascript

I'm getting this error ReferenceError: postCssID is not defined
My script is working if I add js code inside my php file but not working if I use separated js file
in php is working
<script type="text/javascript">
var offsets = offsets || new Array();
offsets["<?=$pst_cssid?>"] = 5;
$("#cmt-a-ii<?=$pst_cssid?>").click(function(){
$.ajax({
url: "<?=Url::to(['/comment/view-more'])?>",
type: 'POST',
data: ({st: '<?=$pst_id?>', cssid: '<?=$pst_cssid?>', offset: offsets["<?=$pst_cssid?>"]}),
success: function(result){
$("#cmt-d-ii<?=$pst_cssid?>").append(result);
}
});
offsets["<?=$pst_cssid?>"] += 5;
});
</script>
But if I use separated js file is not working , the error is in this : offsets[postCssID]; in my php file I only declare variables
<script type="text/javascript">
var postCssID = "<?=$pst_cssid?>";
var postID = "<?=$pst_id?>";
var urlLink = "<?=Url::to(['/comment/view-more'])?>";
</script>
I add path to my js file : <script src="/sxct/js/ly-extra-script.js"></script>
var offsets = offsets || new Array();
offsets[postCssID] = 5;
$("#cmt-a-ii"+postCssID).click(function(){
$.ajax({
url: urllink,
type: 'POST',
data: ({st: postID, cssid: postCssID, offset: offsets[postCssID]}),
success: function(result){
$("#cmt-d-ii"+postCssID).append(result);
}
});
offsets[postCssID] += 5;
});

Related

How to attach javascript to a font awesome icon

I have a fontawesome icon in my HTML as a button and i'd like to use javascript and trigger it AJAX style
<i id="heart" class="jam jam-heart-f"></i> Like
Here is the attempt at javascript to trigger it - but I dont get any errors to follow up on. I try to post the like attempt to a PHP page like.php to add the link to a database.
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
}
});
I dont think #heart seems to be triggered in JS by the id="heart" with the font awesome icon. Any ideas how I can rig this together
You forgot to add closing parenthesis and semicolon for your $('body').on... statement
Try this:
$(document).ready(function()
{
$('body').on("click",'#heart',function()
{
var videoId = "<?php echo $video_id; ?>";
var A=$(this).attr("id");
var B=A.split("like");
var messageID=B[1];
var C=parseInt($("#likeCount"+messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {videoId: videoId},
cache: false,
success: function(result){
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Your code triggers the post-request correctly, but you are not closing your functions and scopes correctly.
I tried it out here:
http://jsfiddle.net/4cohrz5p/
And code to keep stackoverflow happy:
$(document).ready(function() {
$('body').on("click", '#heart', function() {
var videoId = "<?php echo $video_id; ?>";
var A = $(this).attr("id");
var B = A.split("like");
var messageID = B[1];
var C = parseInt($("#likeCount" + messageID).html());
$.ajax({
method: 'POST',
url: 'like.php',
data: {
videoId: videoId
},
cache: false,
success: function(result) {
likeInfo = JSON.parse(result);
$("#likeCount1").html("Likes:" + likeInfo.likeCount);
//document.getElementById("likeCount1").value = likeInfo.likeCount;
//$("#likeCount1").html(likeCount);
}
});
});
});
Besides, the javascript console shows Uncaught SyntaxError: missing ) after argument list for your code. And you open the network-tab when you click the heart to see outgoing requests and can inspect them to see that they send the correct data (and the response too!).
Any decent js editor would have shown this error before even running the code. Try VS Code. Free and lightweight and pretty great overall.

pass data from ajax success data to ejs templates

I just started to use ejs. Now, I want to pass data gotten from ajax result to two different div in ejs.
I can pass to a single div but for multiple divs, what change do I need in my code?
$.ajax({
type: "POST",
url: serviceurl + 'Get',
dataType: 'json',
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "imagesrc": imagesrc }),
success: function (data) {
var property = JSON.parse(data.GetResult);
$('.insideContent>').remove() ;
$('.insideContent').addClass("insidecontentcss") ;
var str = $("#insidecontenttooldata").html();
var data = { tooldata: property };
var content = new EJS({ text: str }).render(data);
$(".insideContent").html(content);
var str1 = $("#well").html();
var data1 = { tooldata: property };
var content1 = new EJS({ text: str1 }).render(data);
$(".well").html(content);
}
and in ejs page i use two script like
<script id="insidecontenttooldata" type="text/x-ejs-template">
//// loop////
</script>
<script id="well" type="text/x-ejs-template">
///loop///
</script>
I guess you have error while targeting second template. Modify code as follows:
var str1 = $("#well").html(); //id of template is 'well' and not the 'welldata'
var data1 = { tooldata: property };
var content1 = new EJS({ text: str1 }).render(data1);
$(".well").html(content1);
Note: as suggested by #kristjan reinhold modified the code to use relative variables.

Unable to change image onChange function on ajax success return

Hi I'm new to this javavascript/ajax. I am trying to create a dropdown that dynamically changes the images by the different options as shown in this Fiddle here but the change function does not seem to be working.
I made sure that I am able to get the data from pictureList but the image source did not change successfully as the fiddle.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[this.value]]});
}
});
return false;
});
However, when I do test it outside the ajax post, it is able to run.
Instance of this is change in ajax success function scope.
In this line $('.content img').attr({"src":[pictureList[this.value]]}); this
is not the instance of selectVariant element.
The usual practice for this is declare a variable that and use that variable in other scope. try the below code.
$('#selectVariant').change(function () {
var sku = $('#selectVariant :selected').val();
var sessionId="<?php echo $sessionId; ?>";
var dataString='sku='+ sku +'&sessionId='+sessionId;
var that = this;
$.ajax({
type:"post",
url: "<?php echo $base_url; ?>ajax-helper/search_variant.php",
data:dataString,
cache:false,
dataType: "JSON",
success: function(data){
var pictureList = {};
//example of my data list
//var pictureList = {'Apple SKU2': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/apples_in_season.png",
//'Pear1': "http://tos-staging-web-server-s3.s3.amazonaws.com/9/catalogue/pears.png"
//};
$.each(data.productVariantImages,function(i, productVariantImages){
pictureList[data.sku] = this.imagePath;
});
console.log(pictureList);
$('.content img').attr({"src":[pictureList[that.value]]});
}
});
return false;
});

Passing arrays js variable to php

Currently I have stored variables in a Javascript array. The goal here is to turn them into PHP variables so that I can use these variables and insert them into my database.
The problem with this code is that the AJAX part doesn't work. Please get me in the right direction as I am extremely new to AJAX. I did try to read about them but still do not understand much. Doing it without refreshing the page is not necessary. Methods other than AJAX are welcomed.
Here is my current code:
<button onclick="Bookings()">Book</button>
<script>
function Bookings() {
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: "studioSelected=" + studioSelect,
success: function(data) {
alert("success!");
}
});
}
}
</script>
<?php
//bookingconfirmed.php
if (isset($_POST['studioSelect'])) {
$uid = $_POST['studioSelect'];
//steps to insert into database.
First, you should move ajax call outside of foreach
var usefulData = [];
var t2Cells = document.getElementsByClassName("t2");
for (var i = 0; i < t2Cells.length; i++) {
var t2CellsIndex [i] = t2Cells[i].cellIndex
var t2CellsRow [i] = t2Cells[i].parentNode.rowIndex
//alert('Coordinates are: '+t2Cells [i].cellIndex+'x'+t2Cells [i].parentNode.rowIndex);
var tbl = document.getElementById("tblMain");
//alert (tbl.rows[0].cells[t2CellsIndex].innerHTML);
var studioSelected = tbl.rows[0].cells[t2CellsIndex].innerHTML
// add data to array
usefulData.push(studioSelected);
var Timeselected = tbl.rows[t2CellsRow].cells[0].innerHTML
}
$.ajax({
type: "POST",
url: 'bookingconfirm.php',
data: {'usefuldata': usefulData},
success: function(data) {
alert("success!");
}
});
Then in your php file:
if (isset($_POST['usefuldata'])) {
var_dump($_POST['usefuldata']);
}

Fetch mulitple values using Jquery post getting undefined value

Below is my jquery ajax method
<script type="text/javascript">
$(document).ready(function () {
$('#c_select').change(function(){
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type:'post',
url:'getvalues.php',
dataType: JSON,
success:function(resp){
alert(resp.first);
}
error:function(resp){
alert(resp.first);
}
});
});
});
</script>
Below given file is where i get the values (PHP File)
<?php
$output = array('first'=>'Steven',
'last'=>'Spielberg',
'address'=>'1234 Unlisted Drive');
echo json_encode($output,JSON_FORCE_OBJECT);
?>
success part is not getting executed i am getting undefined error
Try following code, it should work
$(document).ready(function() {
$('#c_select').change(function() {
var one = 10;
var two = 20;
var three = 30;
var four = 40;
$.ajax({
type: 'post',
url: 'getvalues.php',
dataType: 'json',
success: function(resp) {
alert(resp.first);
},
error: function(resp) {
}
});
});
});

Categories

Resources