JQuery click 1 does nothing - javascript

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});

Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

Related

Loop in ajax, ordering function executions

I want to use jquery for checking sites servers one by one and if the server is ok start grabbing pages.
But in the following code, the loop execute at the first and 2 message appears at the first lines:
start analyzing site 1
start analyzing site 2
start grabbing site 1
start grabbing site 2
...
How I can change this to:
start analyzing site 1
start grabbing site 1
...
start analyzing site 2
start grabbing site 1
...
I am new in Jquery, but I have read about promise and deferrals but could not write the correct code.
I tested this code by async:false. It solves the problem, But I don't want to use this approach (You know the reason).
new_links_arr() = array('site1', 'site2');
function check_server(response) {
var new_links_c = new_links_arr.length;
for (var n = 0; n < new_links_c; n++) {
var this_link = new_links_arr[n];
if (this_link.length > 5) {
$("#responds").append("<hr/> start analyzing site: " + this_link + "");
var myData = 'mod=chk_srv&url=' + encodeURIComponent(this_link) + '&mk_rds_dir=1';
$.ajax({
type: "GET",
url: my_url,
dataType: "json",
data: myData,
cache: false,
success: grab_site,
error: end_error
});
}
}
}
function grab_site(response) {
$("#responds").append(" " + response.the_msg + " ");
var status = response.status;
if (status == 1) {
$("#responds").append(" start grabbing site ");
var myData = 'mod=chk_home&url=' + encodeURIComponent(response.url);
$("#Loding_info").html("Get Homapage and Detecting software from " + response.url);
$.ajax({
type: "POST",
url: my_url,
dataType: "json",
data: myData,
success: parse_jdata,
error: end_error
})
} else {
$("#responds").append("stop");
end_ajax();
}
}
You should start the next test after you finish processing the previous one.
var new_links_arr = ['site1', 'site2'];
var new_links_index = 0;
function check_server() {
if (new_links_index >= new_links_arr.length) {
return;
}
var this_link = new_links_arr[new_links_index];
if (this_link.length > 5) {
$("#responds").append("<hr/> start analyzing site: " + this_link + "");
var myData = {
mod: 'chk_srv',
url: this_link,
mk_rds_dir: 1
};
$.ajax({
type: "GET",
url: my_url,
dataType: "json",
data: myData,
cache: false,
success: grab_site,
error: end_error
});
}
}
function grab_site(response) {
$("#responds").append(" " + response.the_msg + " ");
var status = response.status;
if (status == 1) {
$("#responds").append(" start grabbing site ");
var myData = {
mod: 'chk_home',
url: response.url
};
$("#Loding_info").html("Get Homepage and Detecting software from " + response.url);
$.ajax({
type: "POST",
url: my_url,
dataType: "json",
data: myData,
success: parse_jdata,
error: end_error
})
} else {
$("#responds").append("stop");
end_ajax();
}
}
function parse_jdata(response) {
// do your processing
// ...
new_links_index++;
check_server();
}
My code was long (more than 10 functions). So I cut some piece of it and made a new array (The real array is made by php from previous response and post by json). This is the reason of mistakes in the code.
The idea by Barmar (incrementing the array index in the final function) was helpful. I changed my code and it is working nice now. Thank you for your help.
I added the new function for sending sites one by one to the next functions:
function walk_in_links_arr(new_links_arr2)
{
if (new_links_index >= new_links_arr2.length)
{
//alert(' new_links_index11 = ' + new_links_index);
$("#responds").append("all sites checking done. ");
pass_response_final();
}
var this_link = new_links_arr2[new_links_index];
//alert(' new_links_index22 = ' + new_links_index);
//alert (this_link);
if(this_link.length>5)
{
$("#responds").append(" start checking " + this_link + " ");
var myData = 'mod=chk_srv&url='+ encodeURIComponent(this_link)+'&mk_rds_dir=1';
$.ajax({
type: "GET",
url: my_url,
dataType:"json",
data:myData,
cache: false,
success:grab_site,
error:end_error
});
}
else
{
new_links_index++;
walk_in_links_arr(new_links_arr);
}
}

Implement jQuery on dynamically created elements

I'm trying to integrate two jQuery scripts into one but because the elements of the first part are created dynamically using jQuery I can't get the second part of the project working.
The project:
1.Instagram pictures are parsed as JSON into li elements.
Here's a portion of the code:
<ul id="elasticstack" class="elasticstack">
</ul>
<script>
$("#elasticstack").append("<li><div class='peri-pic'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' /><span class='name'>"+ data.data[i].caption.from.username +"</span> <span class='likes'><span class='glyphicon glyphicon-heart'></span><p>"+data.data[i].likes.count +"</p></span></div></li>"
);
</script>
Source: LINK
2.This works fine but when I try to add the slider none of the functions work. Even if I wrap the callout function in a $( document ).ready(function() { });
Here's the call out code:
<script>
new ElastiStack( document.getElementById( 'elasticstack' ) );
</script>
Source: LINK
Here's the JS Fiddle with all my code: LINK
Where am I going wrong?
You're looking for this. After the initial loadImages(start_url) call, you should be able to call loadImages(next_url) to load and display more. new ElastiStack had to be called after the images had been appended.
var access_token = "18360510.5b9e1e6.de870cc4d5344ffeaae178542029e98b",
user_id = "18360510", //userid
start_url = "https://api.instagram.com/v1/users/"+user_id+"/media/recent/?access_token="+access_token,
next_url;
function loadImages(url){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url,
success: function(data){
displayImages(data);
next_url = data.pagination.next_url;
}
})
}
function displayImages(images){
for(var i = 0; i < 20; i++){
if(images.data[i]){
$("#elasticstack").append("<li><img class='instagram-image' src='" + images.data[i].images.low_resolution.url + "'></li>");
}
}
// Call it after the images have been appended
new ElastiStack(document.getElementById('elasticstack'));
}
$(document).ready(function(){
loadImages(start_url);
});
Try to initialize the ElastiStack after data (HTML elements) has been appended into the DOM in your ajax, for example:
for (var i = 0; i < count; i++) {
// ...
$("#elasticstack").append(...);
}
new ElastiStack(...);
It should work.
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url ,
success: function(data) {
next_url = data.pagination.next_url;
//count = data.data.length;
//three rows of four
count = 20;
//uncommment to see da codez
//console.log("count: " + count );
//console.log("next_url: " + next_url );
//console.log("data: " + JSON.stringify(data) );
for (var i = 0; i < count; i++) {
if (typeof data.data[i] !== 'undefined' ) {
//console.log("id: " + data.data[i].id);
$("#elasticstack").append("<li><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' /></li>"
);
}
}
new ElastiStack(document.getElementById('elasticstack'));
}
});
You have to move your new ElastiStack(document.getElementById('elasticstack')); inside the ajax success event. You don't have to change anything else in your. I also updated your JSFiddle.

ajax success event doesn't work after being called

After searching here on SO and google, didn't find an answer to my problem.
The animation doesn't seem to trigger, tried a simple alert, didn't work either.
The function works as it is supposed (almost) as it does what i need to, excluding the success part.
Why isn't the success event being called?
$(function() {
$(".seguinte").click(function() {
var fnome = $('.fnome').val();
var fmorada = $('.fmorada').val();
var flocalidade = $('.flocalidade').val();
var fcodigopostal = $('.fcodigopostal').val();
var ftelemovel = $('.ftelemovel').val();
var femail = $('.femail').val();
var fnif = $('.fnif').val();
var fempresa = $('.fempresa').val();
var dataString = 'fnome='+ fnome + '&fmorada=' + fmorada + '&flocalidade=' + flocalidade + '&fcodigopostal=' + fcodigopostal + '&ftelemovel=' + ftelemovel + '&femail=' + femail + '&fnif=' + fnif + '&fempresa=' + fempresa;
$.ajax({
type: "GET",
url: "/ajaxload/editclient.php",
data: dataString,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
return false;
});
});
you are trying to pass query string in data it should be json data.
Does your method edit client has all the parameters you are passing?
A simple way to test this is doing the following:
change this line to be like this
url: "/ajaxload/editclient.php" + "?" + dataString;
and remove this line
data: dataString
The correct way of doing it should be, create a javascript object and send it in the data like so:
var sendData ={
fnome: $('.fnome').val(),
fmorada: $('.fmorada').val(),
flocalidade: $('.flocalidade').val(),
fcodigopostal: $('.fcodigopostal').val(),
ftelemovel: $('.ftelemovel').val(),
femail: $('.femail').val(),
fnif: $('.fnif').val(),
fempresa: $('.fempresa').val()
}
$.ajax({
url: "/ajaxload/editclient.php",
dataType: 'json',
data: sendData,
success: function() {
$('.primeirosector').animate({ "left": "+=768px" }, "fast" );
}
});
Another thing shouldn't this be a post request?
Hope it helps

jqGrid: grid function executes only once

Sorry, this is a Javascript beginner question. My jqGrid function works fine the first time around, but when I call it a second time, nothing happens, no request is issued. Code fragment:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
The alert() shows me that doGrid() is really called successfully the second time. So it's really the $("projectList").jqGrid() function that doesn't execute, or fails silently .. Unless I made an obvious mistake in the way I call it?
I think the second time is no longer a need to regenerate the entire Grid. Then you only change the set parameters and grid computing to date. For this you need a trigger("reloadGrid") call.
$(document).ready(function() {
var runonce=false;
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
if (false==runonce) {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
runonce=true;
} else {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl
}).trigger("reloadGrid");
}

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Categories

Resources