var feedback = function (res) {
if (res.success === true) {
var get_link = res.data.link.replace(/^http:\/\//i, 'https://');
document.querySelector('.status').classList.add('bg-success');
document.querySelector('.status').innerHTML =
'Image : ' + '<br><input class="image-url" value=\"' + get_link + '\"/>' + '<img class="img" alt="Imgur-Upload" src=\"' + get_link + '\"/>';
}
};
The second portion is:
new Imgur({
clientid: '3527680b6690575', //You can change this ClientID
callback: feedback
});
How to get_link to php variable in a index.php page?
The solution is like this:
function notifvanish() {
var data = 0;
var dataset = 'set=' + data;
$.ajax({
type: "POST",
url: "notifvanish.php",
data: dataset,
cache: false,
success: function (html) {
//alert("Success");
}
});
}
Related
I am trying to get share count of pininterest and below code is working well
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.getJSON(PIUrl, function (data) {
pi_like_count = data.count;
alert(pi_like_count +' pininterest');
});
but when I am trying to put below code issue is coming as
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.ajax({
method: 'GET',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest');
},
error: function (data) {
alert('error' + data.count + ' pininterest');
console.log(data);
},
async: false
});
Console.log error as
promise: function promise()
readyState: 4
responseText: "{\"error\":\"Invalid callback, use only letters, numbers, square brackets, underscores, and periods.\"}"
This issue is coming when I am using $.ajax, I had tried same to get facebook share count and is working well but pininterest is not working
more explaination
function GetScores(url) {
var FBUrl, TWUrl, LNUrl, GLUrl, PIUrl;
var url1 = "";
url1 = encodeURIComponent(url1 || url);
//Fetch counters from PInterest
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest');
} ,
complete: function (jqXHR, data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest complete');
},
error: function (req, status, error) {
alert('error');
},
async: false
});
//Fetch counters from Facebook
var fb_share_count = 0;
FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
url: FBUrl,
success: function (data) {
fb_share_count = data.share.share_count;
alert(fb_share_count+' facebook');
},
async: false
});
var totalshare = parseInt(fb_share_count) + parseInt(pi_like_count);
return totalshare;
}
Here Facebook count and total share count is get then after the pinterest count alert is showing i.e. when this function is calling second time then after pinterest is giving old count.
Try it:
function GetScores(url, onCountTotal) {
var FBUrl, TWUrl, LNUrl, GLUrl, PIUrl;
var url1 = "";
url1 = encodeURIComponent(url1 || url);
//Fetch counters from PInterest
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?';
$.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
var fb_share_count = 0;
FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
dataType: 'json',
url: FBUrl,
success: function (data) {
fb_share_count = data.share.share_count;
var totalshare = parseInt(fb_share_count) + parseInt(pi_like_count);
onCountTotal(totalshare);
//alert(fb_share_count + ' facebook');
},
error: function (data) {
onCountTotal(-1);
},
async: true
});
},
error: function (req, status, error) {
onCountTotal(-1);
},
async: true
});
}
//EXAMPLE HERE CALL FUNCTION WITH CALLBACK
GetScores("http://www.google.com", function (count) {
alert("Count = " + count);
});
Here's what you could try using a CallBack :
var result = 0;
function handleData(data) {
result+=data.count;
}
function GetScores(url) {
var url1 = encodeURIComponent(url1 || url);
getFb(url1).done(handleData);
getPi(url1).done(handleData);
return result;
}
function getPi(url1){
var PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?';
return $.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl
});
}
function getFb(url1){
var FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
return $.ajax({
type: 'GET',
url: FBUrl
});
}
You can adapt for every platform you need the shares from, just add another function in GetScores and handle properly the returned json
You could also do something like :
function getFb(url1, callback){
var FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
url: FBUrl,
success: callback
});
}
getFb(function(data){
result+=data.count;
});
Try to adapt your code depending on the result of your alerts
How do I combine script 1 and script 2 to achieve my objective of sending data as well as one script.
The idea is to have the fresh content anytime a post is sent. I am using this with Framework7. Both scripts already work well in their roles to post or retrieve data.
This is the script that is getting/fetching data from the back-end.
SCRIPT 1
<script type="text/javascript">
$(document).ready(function() {
var url = "http://localhost/integration/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var comment = field.comment;
var user = field.user;
var post_time = field.post_time;
$("#listview").append("<tr class='even gradeA' width = '30px'><td>"+comment+"</td><td>"+user+"-"+post_time+"</td></tr>");
});
});
});
</script>
SCRIPT 2
The role of script 2 is to post data to the server.
<script type="text/javascript">
$(document).ready(function() {
$("#insert").click(function() {
var comment = $("#comment").val();
var user = $("#user").val();
var ip = $("#ip").val();
var dataString = "comment=" + comment + "&user=" + user + "&ip=" + ip + "&insert=";
if ($.trim(comment).length > 0 & $.trim(user).length > 0 & $.trim(ip).length > 0) {
$.ajax({
type: "POST",
url: "http://localhost/integration/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('Connecting...');
},
success: function(data) {
if (data == "success") {
alert("Successfully submitted");
$("#insert").val('submit');
} else if (data == "error") {
alert("error");
}
}
});
}
return false;
});
});
</script>
Both scripts are working independently.
Try this below code:
Here is what I have done. I have converted it into a function which you can call once your insertion code has been completed and also can be called when the page is refreshed.
function getUpdatedData() {
var url = "http://localhost/integration/json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var comment = field.comment;
var user = field.user;
var post_time = field.post_time;
$("#listview").append("<tr class='even gradeA' width = '30px'><td>" + comment + "</td><td>" + user + "-" + post_time + "</td></tr>");
});
});
}
$(document).ready(function() {
getUpdatedData();
$("#insert").on('click', function() {
var comment = $("#comment").val();
var user = $("#user").val();
var ip = $("#ip").val();
var dataString = "comment=" + comment + "&user=" + user + "&ip=" + ip + "&insert=";
if ($.trim(comment).length > 0 & $.trim(user).length > 0 & $.trim(ip).length > 0) {
$.ajax({
type: "POST",
url: "http://localhost/integration/insert.php",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#insert").val('Connecting...');
},
success: function(data) {
if (data == "success") {
alert("Successfully submitted");
$("#insert").val('submit');
getUpdatedData();
} else if (data == "error") {
alert("error");
}
}
});
}
return false;
});
});
I am using jquery in my one of the form. where on click of submit button i call one function QuoteDetailValidation(). In which i validate fields. But after validate that fields i try to get all fields which have errorActive class. But unfortunately i can't get it.
See my code
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
return false;
});
function QuoteDetailValidation(descriptionData1) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Now What happens, When there is error QuoteDetailValidation() append errorActive class to fields.
By var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; i try to get length of the fields which have errorActive class. but in alert of selectors, it always gives 0. But when i alert something before getting all errorActive Class then alert selectors give me perfect count. i think there is delay because of alert before getting class errorActive. so that it give me count. How to use it. Any help please. Thanks in advance.
You can determine the exact delay required for selectors to be initailized properly. Whatever we add as delay will be assumption and can be short for some scen
One options using below in your ajax request
async: false
like below:-
$.ajax({
type: 'GET',
async: false,
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {}});
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true(it is default) then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet. Helpful question
But I still will advise you to move selectors part in success of ajax like below:-
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length;
alert(selectors);
//some logice here or move the above in some function and call it here
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
or use call back functions.
Update: try something like below It will keep async as true and keep the count logic outside $.ajax.
function QuoteDetailValidation(descriptionData1,submitFormOrAddError) {
for (var i = 0; i < descriptionData1.length; i++) {
var id = descriptionData[i].id;
var value = descriptionData[i].value;
var costid = costData[i].id;
var costValue = costData[i].value;
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
submitFormOrAddError(data);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
}
}
Call it like this:
$('#saveQuote').on('click', function(event) {
var descriptionData1 = $('input[name=\"QuoteDetail[description][]\"]');
QuoteDetailValidation(descriptionData1);
QuoteDetailValidation(descriptionData1,function(output){
// here you use the output
var selectors = document.querySelectorAll('#quote-quoteItems-form .errorActive').length; //This line is excuted only after call completes
alert(selectors);
//form submit here if error is zero.
});
alert("hii");//this line is executed without waiting for above call..
return false;
});
You need to do this on your success callback of the QuoteDetailValidation method, because the $.ajax runs async and after invoking the method it still hasn't completed.
$.ajax({
type: 'GET',
url: "<?php echo Yii::app()->createUrl('QuoteData/validatedata'); ?>",
data: 'descvalue=' + value + '&Descname=description&costValue=' + costValue + '&costName=cost&descId=' + id + '&costId=' + costid,
success: function(data) {
var obj = $.parseJSON(data);
var cost = obj.cost;
var desc = obj.desc;
if (desc != '' || cost != '') {
if (cost != '') {
$('#' + costid).addClass('errorActive');
$('#' + costid).prev().addClass('error');
$('#' + costid).next().remove();
$('#' + costid).after(cost);
$('#' + costid).parent().removeClass('success');
$('#' + costid).parent().addClass('error');
}
}
// Here you know that the elements will have the necessary classes.
var selectors = $('#quote-quoteItems-form .errorActive').length;
alert(selectors);
},
error: function(data) {
alert('Your data has not been submitted..Please try again');
}
});
After submit a reply without 1st post Its display a blank data space and after refresh page its show reply.
What is problem here please.
..............................................................................
This is my script
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputReplycom = $(".replycom");
var inputImg = $("#img");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var replyList = $("#replynext");
function updateReplybox() {
var tutid = inputTutid.attr("value");
$.ajax({
type: "POST",
url: "reply.php",
data: "action=update&tutid=" + tutid,
complete: function (data) {
replyList.append(data.responseText);
replyList.fadeIn(2000);
}
});
}
$(".repfrm").click(function () {
error.fadeOut();
if (checkForm()) {
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var img = inputImg.attr("value");
var replycom = inputReplycom.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");
$('.reply_here').hide();
$("#loader").fadeIn(400).html('<br><img src="loaders.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
//send the post to submit.php
$.ajax({
type: "POST",
url: "reply.php",
data: "action=insert&author=" + author + "&replycom=" + replycom + "&url=" + url + "&img=" + img + "&parent_id=" + parent_id + "&tutid=" + tutid,
complete: function (data) {
error.fadeOut();
$("#loader").hide();
replyList.append(data.responseText);
updateReplybox();
$("#repfrm").each(function () {
this.reset();
});
}
});
} else //alert("Please fill all fields!");
error_message();
});
Probably all this code should be inside a $(document).ready({ ... });
To debug: Open chrome inspector and put a brakepoint at this line: var tutid = inputTutid.attr("value"); and check for what is inside inputTutid variable.
Also you can try
inputTutid.val();
instead of
inputTutid.attr("value");
OK I am building something that makes an ajax request to one server where it determines the url it needs to then make a new ajax request to another place. Everything is progressing thanks to all the help at SO =) .. however I am stuck again. I am struggling with getting the variables to return to the different functions as I need. The second (jsonp) request returns a json function which looks like :
jsonResponse(
{"it.exists":"1"},"");
and my code...
var img = "null";
var z = "null";
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
$(data).find("ITEM").each(function()
{
query = $("SKU", this).text();
query = 'http://domain.com/' + query + '?req=exists,json';
img = $("SKU", this).text();
img = '<img src="http://domain.com/' + img + '">';
var date =$("LAST_SCAN" , this).text();
$.ajax({
url: query,
dataType: 'jsonp'
});
$("table").append('<tr>'+'<td>' + (date) + '</td>' + '<td>' + (z) + '</td>');
});
}
});
});
// function required to interpret jsonp
function jsonResponse(response){
var x = response["it.exists"];
// console.log(x);
if (x == 0) {
console.log("NO");
var z = "NO IMG";
}
if (x == 1) {
console.log(img);
//this only returns the first image path from the loop of the parseXml function over and over
var z = (img);
}
return z;
}
So I guess my problem is a two parter.. one how do I get the img variable to loop into that if statement and then once that works how can I return that z variable to be used in the first xml parser?
Try this synchronous approach:
var itemQueue = [];
$(document).ready(function ()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
itemQueue= $(data).find("ITEM").map(function ()
{
return {
sku: $("SKU", this).text(),
date: $("LAST_SCAN", this).text()
};
}).get();
getNextItem();
}
});
});
function getNextItem()
{
var item = itemQueue[0];
var query = "http://domain.com/" + item.sku + "?req=exists,json";
$.ajax({
url: query,
dataType: 'jsonp'
});
}
function jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
var x = response["it.exists"];
var z = x == "0" ? "NO IMG" : "<img src=\"http://domain.com/" + item.sku + "\">";
$("table").append("<tr><td>" + item.date + "</td><td>" + z + "</td>");
}
Store 'date' in a global variable, and move the logic to append HTML elements into the jsonResponse function. You cannot return control flow from jsonResponse because it's called asynchronously, but you can continue doing anything you'd like from that function.