Use variable from Ajax response - javascript

I have two files:
example.html:
<div class="my-div"></div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "example1.html",
type: "get",
success: function(response) {
$(".my-div").html(response);
}
});
$(document).on("click", "button", function() {
console.log(alpha); // Should print "data",
});
});
</script>
example1.html:
<button></button>
<script type="text/javascript">
$(document).ready(function() {
var myDropzone = new Dropzone("", {
success: function(file, response) {
const alpha = "data";
}
});
});
</script>
In example.html, I need console.log(alpha) to output "data". I make an Ajax request to example1.html, and update the contents of my div with the returned html. The constant alpha isn't useable until new Dropzone() succeeds. How can I make this code work?

One option is to make your alpha variable global.
You declared your alpha variable inside success function so you can only use that variable inside it.
<button></button>
<script type="text/javascript">
const alpha; /* Init it here */
$(document).ready(function() {
var myDropzone = new Dropzone("", {
success: function(file, response) {
alpha = "data"; /* Assign the value here */
}
});
});
</script>
Now you can access it as
$(document).on("click", "button", function() {
console.log(alpha); // Should print "data",
});

Related

get value of element of html in another js file

in my index page i sent a request ajax and response is a number.and i set the response to the value of input with hidden type
<input type="hidden" id="Status">
<script src="js/indexPhone.js"></script>
<script>
$(document).ready(function() {
$("#SendPhone").click(function(e) {
var phoneField = $("#PhoneField").val();
var phoneFieldString = "989" + phoneField.substring(0);
$.ajax({
type:'post',
url:'getSMS.php',
data:{'phoneFieldString':phoneFieldString},
success:(function (response) {
$("#Status").val(response);
})
})
});
});
</script>
and my problem is i want to get this value in another javascript page that i included in my index but it alerts empty. this my indexPhone.js:
$("#SendPhone").click(function() {
alert($("#Status").val());
});
Ajax request is asynchronous, so the second click runs before value is set.
Use events:
// index.html
$("#SendPhone").click(function (e) {
// ...
$.ajax({
// ...
success: (function (response) {
$("#Status").val(response);
$("#Status").trigger("gotSMS");
})
});
});
// indexPhone.js
$("#Status").on("gotSMS", function () {
alert($(this).val());
});

Display one item of my choice rather than the whole list items in ajax upon success

I've got an AJAX code, that does POST reqeusts and displays results upon success. The displayed results are in JSON format and from a different website. The result displays all of the list items, but now I want to display only one item of my choice at the same time, instead of displaying all the items. I've been trying to use the each() and slice() functions, but I think I'm not using them correctly or I don't have any idea of how to deal with the problem. Please help, I'm new to AJAX and JQuery.
This is the code I have:
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
/**The code below will display all the items under a div="product_dispay"*/
jQuery('#product_display').append(jsonData.product_display);
//I want a code that will display one item of my choice at this section.
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
You can access the contents of the #product_display element with jQuery. The API returns HTML data so you can render it in the page, then using jQuery find the data within the HTML and do whatever you want with it.
I have added this code into your original code.
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
This is the final code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {user: user};
jQuery.ajax({
async: false,
url: "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type: "post",
dataType: "jsonp",
jsonp: "jsoncallback",
success: function (jsonData) {
console.log(jsonData);
if (jsonData.product_display !== '') {
jQuery('#product_display').append(jsonData.product_display);
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
} else {
alert(jsonData.error);
}
},
error: function () {
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeIn('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "block");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeOut('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "none");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function () {
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
</body>
</html>
I hope it helps.
This is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {
user: user
};
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
jQuery('#product_display').append(jsonData.product_display);
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeIn('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","block");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeOut('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","none");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
The result displayed upon success is in html format.
jsonData.product_display[i]
has not worked.

Re-Run a Ajax script?

If I have a script like below that's ran to load a table with data injected into it from an external PHP file on to the page.
<script>
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
success : function(text)
{
response = text;
}
});
alert(response);
});
</script>
I have another script down below where a user can add records to the database.
<script id="sosurce" language="javascript" type="text/javascript">
$("#newitemadd").click(function(){
$('#New').modal('show');
$("#insertResults").click(function(){
var getname = $('#getname').val();
var getquant = $('#getquant').val();
var getprice = $('#getprice').val();
var getdesc = $('#getdesc').val();
$.ajax({
url: 'api2.php',
data: "name="+getname+"&quantity="+getquant+"&price="+getprice+"&description="+getdesc,
success: function(data)
{ $('#New').modal('hide');
$("#success").html(data);
$('#success').slideDown().delay(3000).slideUp().reload
},
error: function() {
$("#failure").alert('show');
}
});
});
});
</script>
It works fully as intended but, how can I get the first script to Re-Run so the table that's inserted onto the page is refreshed to show the new results that were just added?
you can do like this .
<script>
var renderTable = function() {
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
success : function(text)
{
response = text;
}
});
alert(response);
}
// Call function onload
jQuery(function($){
renderTable();
$(".refreshBtn").click(function(){
renderTable();
})
});
</script>
Move first code into an function like
<script>
$(document).ready(LoadData);
function LoadData() {
var response = '';
$.ajax({
type: "GET",
url: "Records.php",
success : function(text) {
response = text;
}
});
alert(response);
};
</script>
And call this function from other function, example does it on success
<script id="sosurce" language="javascript" type="text/javascript">
$("#newitemadd").click(function() {
$('#New').modal('show');
$("#insertResults").click(function() {
var getname = $('#getname').val(),
getquant = $('#getquant').val(),
getprice = $('#getprice').val(),
getdesc = $('#getdesc').val();
$.ajax({
url: 'api2.php',
data:
"name="+getname+"&quantity="+getquant+"&price="+getprice+"&description="+getdesc,
success: function(data) {
$('#New').modal('hide');
$("#success").html(data);
$('#success').slideDown().delay(3000).slideUp().reload
// Call load data again to refresh the table
LoadData();
},
error: function() {
$("#failure").alert('show');
}
});
});
});
</script>

IE8 Object Expected JQuery .ready function

I have the following function that is called in the head tag.
Page::IncludeJavascriptFile('js/packages.js');
Page::AddHeadElement('
<script type="text/javascript">
$(document).ready(function() {
pollClientTable('.TriplecastConfig::get('transfer_polling_period')*1000 .', true);
});
</script>
');
pollClientTable is defined in packages.js which is before the function call.
pollClientTable function:
var pollClientTableTimer = null;
var pollClientTableTimerPoll = null;
function pollClientTable(poll, async) {
clearTimeout(pollClientTableTimer);
$.ajax({
url: "ajax_requests/getClientPackages.php",
async: async,
timeout: poll,
success: function(data) {
$('#packagesForm').empty();
$('#packagesForm').append(data);
}
});
pollClientTableTimerPoll = poll;
pollClientTableTimer = setTimeout(function(){pollClientTable(poll, true);}, poll);
}
The functions work in any other browser bar IE8. Any ideas why?

Function Doesn't Work When Called Within Object

I have the following code:
// auto_suggest.js
function AutoSuggest(textboxElem, resultElem, url) {
this.textboxElem = textboxElem;
this.resultElem = resultElem;
this.url = url;
this.registerEvent();
}
AutoSuggest.prototype = {
registerEvent: function() {
this.textboxElem.onkeyup = this.getSuggestions;
},
getSuggestions: function() {
// This doesn't work either: this.loadResponse("some data");
$.get(this.url, { text: this.textboxElem.value }, this.loadResponse);
},
loadResponse: function(data) {
// Not called
this.resultElem.innerHTML = data;
}
};
// suggest.html
<script src="jquery-1.6.1.js" type="text/javascript"></script>
<script src="auto_suggest.js" type="text/javascript"></script>
<script>
$(function() {
var suggest = new AutoSuggest(document.getElementById("suggest"),
document.getElementById("result"),
"result.txt");
// This DOES work: suggest.loadResponse("123");
});
</script>
<input type="text" id="suggest" /><br>
<div id="result"></div>
The function loadResponse refuses to be called from within the object, but from the outside it is fine. What could be the problem?
The AJAX callback (AutoSuggest.loadResponse) is, by default, passed the jqXHR object as its context (this value). You need to override this by passing the context option to $.ajax. Replace your $.get function with this:
$.ajax({
url: this.url,
type: 'GET',
data: { text: this.textboxElem.value },
success: this.loadResponse,
context: this
});
This makes jQuery set this to the correct value.
The code
this.textboxElem.onkeyup = this.getSuggestions;
should be
var t = this;
this.textboxElem.onkeyup = function() {
t.getSuggestions();
}

Categories