How to attach javascript to a font awesome icon - javascript

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.

Related

Using AJAX to post data into API

I have a script that uses AJAX to comunicate with PHP based API.
First part loads trade history:
$(document).ready(function () {
var orders = $('#History ul');
var user = "<?php echo $user; ?>";
$.ajax({
type: "GET",
url: "api.php",
data: {
user: user
},
success: function (response) {
console.log(response);
var res = JSON.parse(response);
$.each(res, function (index, value) {
console.log(value);
if(value['PL']>=0){
orders.append("<li style=\"color:green;\">" + value['User'] + "</li>");
}else{orders.append("<li style=\"color:red;\">" + value['User'] + "</li>");}
});
}
});
Second part posts a trade to database:
$("#submit").click(function(){
//event.preventDefault();
var oPrice = newOrder.elements["oPrice"].value;
var cPrice = newOrder.elements["cPrice"].value;
var oType = newOrder.elements["oType"].value;;
var oSymbol = newOrder.elements["oSymbol"].value;
var oAmount = newOrder.elements["oAmount"].value;
var json ={
'user': user,
'oPrice': oPrice,
'cPrice': cPrice,
'oType': oType,
'oSymbol': oSymbol,
'oAmount': oAmount};
alert(JSON.stringify(json)); //---check zda je naplněný
$.ajax({
type: "POST",
url: "api.php",
data: json,
success: function (response) {
alert(response);
}
});
});
The problem is, that when i press the button and send json, its missing the 'user' data and looks like this:
TraderBook.php?oPrice=1&cPrice=1&oType=LONG&oSymbol=1&oAmount=1
I have no idea why does ajax exclude it. The json variable has it filled out
I think your problem might be here
$(document).ready(function () {
var user = "<?php echo $user; ?>";
var is the JS scoping declaration. So you're limiting your user value to just the anonymous function being triggered by the page DOM load completing. What you should do is try scoping it outside the function
var user; //global scope
$(document).ready(function () {
user = "<?php echo $user; ?>";
This way, when your $("#submit").click(function() fires, there's a value to feed into your script.
I was wrongchecking the problem a mistook data from a form for the json. Problem was inside the API --> There was a tabulator in a SQL command..
Thanks to everyone for suggestions.

Jquery ajax issue in php and ajax code

Here in the following code in jquery i get the alert test1 but when i try to get alert test2 i dint got that... there is some issue in code please help me to resolve.
$(document).ready(function() {
$(".delete-item-details").click(function() {
alert('test1');
var id = $(this).attr('ids');
alert('test2');
var order_id = $("#order_id").val();
goto_url = "/order/DeleteOrderDetailItems/" + id;
dataString = 'id=' + id + '&order_id=' + order_id;
$.ajax({
type: "POST",
url: goto_url,
data: dataString,
cache: false,
success: function(html) {
$("#row-id-" + id).fadeOut();
$("#total_span").html(html);
}
});
});
});
Please change this three lines in code and you will definitely get alert !!
alert('test1');
var id=$(this).attr('id'); // here you have written ids
alert('test2');
The default attribute is 'id' not 'ids'
If still now clear let me know i will help you out.
TRY
var id = $(this).prop('ids');

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;
});

ajax and javascript drilldown script addition

I have a make/model/engine search form, the user selects the make which then populates the model, the user selects the model and it populates the engine. The problem I have encountered is that several of the manufacturers (make) use the exact same model. The script I have chooses the engine based on the model only. I would like to modify the script so it chooses the engine based on the make AND model, this would resolve my problem. I am somewhat familiar with javascript but I am no expert, I see the ajax requests in the aircraftMakeModel.php file but do not know how to add the make to the query. I have included the three files used below. Any help is appreciated in advance.
Thanks
Tom
aircraftMakeModel.php
<script type="text/javascript">
$(document).ready(function()
{
$('#aircraftMake').change(function()
{
var make=$(this).val();
var dataString = 'make='+ make;
$.ajax
({
type: "POST",
url: "include/getAirFrame.php",
data: dataString,
cache: false,
success: function(html)
{
$('#aircraftModel').html(html);
}
});
});
});
$(document).ready(function()
{
$('#aircraftModel').change(function()
{
var model=$(this).val();
var dataString = 'model='+ model;
$.ajax
({
type: "POST",
url: "include/getEngine.php",
data: dataString,
cache: false,
success: function(html)
{
$('#engineModel').html(html);
}
});
});
});
</script>
getAirFrame.php
<?php
include "../connection.php";
$q = $_POST['make'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`aircraftModel`) FROM `aircraftData` WHERE `aircraftMake` = '$q' ORDER BY aircraftModel ; ");
echo '<option value="0">Aircraft Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>
getEngine.php
<?php
include "../connection.php";
$q = $_POST['model'];
$q = addslashes($q);
$rs=mysqli_query($link,"SELECT DISTINCT(`engineModel`) FROM `aircraftData` WHERE `aircraftModel` = '$q' ORDER BY engineModel");
echo '<option value="0">Engine Model</option>';
while($data = mysqli_fetch_row($rs)){
$sa=$data[0];
echo '<option value="'.$sa.'">'.$sa.'</option>';
?>
<?php } ?>
If you want to send the make and model on the ajax call to get the engine something like this should work. Make the call to get the model as you do, then also add the make to the ajax request data to get the engine.
Note: not sure if this is a typo $('#marke')
$(document).ready(function(){
$('#marke').change(function() {
//make id
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "include/getph.php",
data: dataString,
cache: false,
success: function(html) {
$('#model').html(html);
}
});
});
});
$(document).ready(function() {
$('#model').change(function(){
//make id
var id = $('#marke option:selected').val();
//model id
var id1=$(this).val();
var dataString = 'id1='+ id1 + '&id=' + id;
$.ajax({
type: "POST",
url: "include/getph2.php",
data: dataString,
cache: false,
success: function(html) {
$('#engine').html(html);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I don't understand AJAX callbacks

I have a javascript function which executes on the change of a dropdown:
<script type="text/javascript">
$(function()
{
// Executes when the status dropdown changes value
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
})
</script>
I am trying to get the alert call to show the return value of the following php code (which is true):
<?php
.
.
.
return true;
?>
The alert doesn't pop up. Anyone know why ???
I tried your code with another URL and it's working well.
There are three cases:
scriptUrl is not calculated properly and doesn't point to your PHP script
your server is down
you are accessing an URL not served under the same domain as the one of your script (same-origin policy)
You can see detail of your error if you add an error handler to ajax parameters :
error : function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
Return only returns a value within the php script - to output it to ajax you need to actually output the result to the page, in this case something like echo "true"; or print("true");
Try this
$(document).ready(function(){
$('select[name="status_dropdown"]').change(function(event)
{
var $this = $(event.target);
var orderId = $this.closest('tr').children('td:eq(0)').text(); // index 0 refers to the "order_id column" in the table
var result = null;
var scriptUrl = "ajax_php/update_status.php?order_id=" + orderId + "&status_id=" + this.value;
$.ajax(
{
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data)
{
result = data;
alert(result);
}
});
});
});

Categories

Resources