I'm having a problem when I click my generate cards button multiple times(it generates a new set of cards randomly on every click) and then I click on any of my buttons that sort it will run multiple ajax calls instead of just the latest generated array. It will pass in every array of cards that has been generated not just the most recent one, sort of like it's keeping a queue.
console log will output, "sending color sort", "sending color sort", "sending color sort", etc. *For as many times as i've clicked my generate_cards* button
How can I have it so the sort function only runs once.
<input type="button" value="Generate Cards" id="generate_cards"> </input>
<input type="button" class="sorter" value="Color Sort" id="color_sort"> </input>
<input type="button" class="sorter" value="Shape Sort" id="shape_sort"> </input>
Generate Cards:
$('#generate_cards').click(function() {
$.ajax({
url: ''+set,
async: false,
type: 'POST',
dataType: 'html',
success: function(data) {
var obj = JSON.parse(data);
//sent array to sorting function :
sorting(obj);
var tmpl = $("#formInfo_tmpl").html();
var html = Mustache.to_html(tmpl, obj);
pool_window.html(html);
initilizejs();
},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
card sort function
function sorting(cards) {
$('.sorter').on("click", function() {
var cards_window = $("#sealed_pool");
var sort_type = $(this).attr('id');
//just give me the first word:
sort_type = sort_type.replace(/(\w+).*/,"$1");
console.log('sending'+sort_type);
$.ajax({
url: '',
async: false,
type: 'POST',
data: ({'cards':cards, 'sort_type':sort_type}),
dataType: 'html',
success: function(data) {
var obj = JSON.parse(data);
if(sort_type =='color_sort')
{
var tmpl = $("#color_sort_tmpl").html();
}
if(sort_type =='shape_sort')
{
var tmpl = $("#formInfo_tmpl").html();
}
var html = Mustache.to_html(tmpl, obj);
cards_window.html(html);
initilizejs();
},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
});
}
remove the previous click-listener before you add a new:
$('.sorter')
.off("click")
.on("click", function() {
//code
});
You need to use setInterval within the document ready function, like this:
$(document).ready(function() {setInterval(doAjax, 5000);});
Related
I am trying display data from database based on parent in tree view using AJAX PHP.
I have followed below example .
https://www.w3schools.com/howto/howto_js_treeview.asp
It is working .but after expanding it is not closing .
Here is my script
$(document).ready(function() {
//$(".parent").click(function(){
$(document).on("click", ".box" , function() {
var comp = $(this).text();
const myArray = comp.split("(");
var compnumber=myArray[0];
var model=decodeURIComponent(compnumber);
//alert(part);
if(compnumber){
$.ajax({
url:"ajax_getBomLineDetailsInfo.php",
type : "POST",
data: {
// func:'getdowntimeline',
compnumber: compnumber
},
dataType : "json",
success:function(response)
{
//alert('success');
if(response){
var len = response.length;
// $(".sub").empty();
$('.' + model).empty();
// $(".sub").prepend("");
for( var i = 0; i'"+PartNumber+"'");
var part=decodeURIComponent(PartNumber);
// var test='123';
$('.' + model).append(""+PartNumber+"");
}
//$(".sub").append("");
//$(".GSX130181").show();
//$('.' + model).addClass('active');
//$(this).toggleClass('box check-box');
//$(this).toggle();
// childclick();
//$(".child").show();
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error');
}
});
}
else{
}
});
});
I am getting box class text values on click and getting child values for that text using ajax and appending as li .I need to execute the javascript code in the https://www.w3schools.com/howto/howto_js_treeview.asp in above script .but it is not working .
How to fix the issue ?
I have a form that contains fields of an associative array:
<label for="my_array[][system]">System</label>
<input id="my_array[][system]" type="text" value="" name="my_array[0][system]">
<label for="my_array[][name]">Name</label>
<input id="my_array[][name]" type="text" value="" name="my_array[0][name]">
I'm trying to get this form posted to PHP using Ajax. I've attempted this:
$.ajax({
type: "POST",
dataType: "json",
url: ajaxurl,
data: {
action: "update_postmeta",
post_id: post_id,
nonce: nonce,
my_array: $('input:text[name="my_array*"]')
.each(function() { values[this.name] = $(this).val() })
},
success: function (response) {
alert(response);
},
error: function ( jqXHR, textStatus, errorThrown) {
alert("Error: " + textStatus + '\r\n\r\n' + errorThrown);
}
})
The problem is on this line of code:
my_array: $('input:text[name="my_array*"]')
.each(function() { values[this.name] = $(this).val() })
.each() is not a function... I'm not sure how to get my_array populated with the form's data in the same structure it would be using a regular form submission (without Ajax).
How do I post a form's data when it is created with an associative array?
Change your my_array function() to auto-invoke the function and return an array of key: value objects:
{
...,
my_array: (function() {
var my_array = [];
$('input:text[name="my_array*"]')
.each(function() {
my_obj = {};
my_obj[this.name] = $(this).val();
my_array.push(my_obj);
});
return my_array;
})()
}
Also, you may need to use the attributeStartsWith selector syntax:
jQuery( "[attribute^='value']" )
For completeness, here is an example with using an object instead of an array to directly control the key: value pairs for my_array. Also, I'm using the startsWith syntax.
{
...,
my_array: (function() {
var my_array = {};
$('input:text[name^="my_array"]')
.each(function() {
// Directly sets the key/value data in the POST.
// You could modify the key names if desired.
my_array[this.name] = $(this).val();
});
return my_array;
})()
}
I'm trying to do something like user click on button, it sends request to json, and i want it shows the response of json, but i have some errors that i can't figure it out how to solve it.
HTML:
<a class="backLink" id="target_button" onclick="insertText('target_', 'AA', 'NN')"><div class="fa fa-external-link"></div>Show</a>
JS + ajax:
<script type="text/javascript">
function insertText(elemID, text, text2) {
$.ajax({
url: "https://myserver.com/jsons.php?request=getTargets&tar="text"&bar="text2"",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
if (console && console.log) {
console.log(data);
var getValue = $("#" + elemID).val() == "" ? data : "";
$("#" + elemID).val(getValue);
}
});
}
</script>
I'm not sure if im doing it in the better way.
It is something simple. User click on button, call the function with that parameters, make a request to json , receive answer and display it on the elemID.
Thanks
EDIT:
changes i made
<script>
console.log('called');
function insertText(elemID, product, country) {
"use strict";
console.log('called2');
$.ajax({
url: 'https://myserver.com/jsons.php?request=Targ&country=" + country + "&product=" + product +".",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
if (console && console.log) {
console.log(data);
}
});
console.log('called3');
}
console.log('called4');
</script>
result on console:
called
called4
it looks like i can't enter on function
Write console.log('called'); in your insertText() function right before the line contains $.ajax({
So you can see the function is called on click or not.
If the Console tab of the Developer Tools throws JavaScript errors, this could brake further JavaScript execution too.
Replace your double quotes with single quote.
URL should be
url: 'https://myserver.com/jsons.php?request=getTargets&tar='+ text +'&bar='+ text2
How I did it:
<script type="text/javascript">
function insertText(elemID, p, c) {
var server = window.location.hostname;
$.ajax({
url: "https://" + server + "/jsons.php?request=Target&c=" + c + "&p=" + p +"",
beforeSend: function (xhr) {
xhr.overrideMimeType("text/plain; charset=x-user-defined");
}
})
.done(function (data) {
console.log(data)
var tmp = data.replace('"',"");
var tmp2 = tmp.trim();
var getValue = $("#" + elemID).val() == "" ? tmp2 : "";
$("#" + elemID).val(getValue);
});
}
</script>
HTML:
<a id="t_button" onclick="insertText('t_d', '<?php $c ?>', '<?php $p ?>');" > show</a>
Hope it helps someone another !
I'm trying to upload files through Ajax call and jQuery. Each input[type="file"] is handled dynamically as you will see on the code below and are created on the change event for the Select2 element.
var tipoRecaudo = $('#tipoRecaudo'),
tipo_recaudo = tipoRecaudo.val(),
selectedIdsTipoRecaudo = [];
tipoRecaudo.select2({
ajax: {
dataType: 'json',
url: function () {
return Routing.generate('obtenerRecaudosTramite');
},
data: function (tipo_recaudo) {
return {
filtro: tipo_recaudo
}
},
results: function (data) {
var myResults = [];
$.each(data.entities, function (index, item) {
if (selectedIdsTipoRecaudo.indexOf(item.id.toString()) === -1) {
myResults.push({
'id': item.id,
'text': item.nombre
});
}
});
return {
results: myResults
};
}
},
formatAjaxError: function () {
return Translator.trans('mensajes.msgNoConexionServidor', {}, 'AppBundle');
}
}).change(function () {
var id = $(this).val(),
selectedData = tipoRecaudo.select2("data"),
htmlTpl = '<table class="table"><caption>'+ selectedData.text + '</caption><tbody><tr><td>';
htmlTpl += '<input type="hidden" name="tipoRecaudos[]" id="tipoRecaudo ' + id + '" value="' + selectedData.id + '" /><div class="row"><div class="col-xs-6"><div class="form-group"><input type="file" id="recaudosNombreArchivo' + id + '" name="recaudos[nombre_archivo][]" multiple="multiple" class="form-control" /></div></div></div></div>';
htmlTpl += '</td></tr></tbody></table>';
selectedIdsTipoRecaudo.push(id);
$('#recaudoContainer').append(htmlTpl);
});
$('#recaudoContainer').on('change', 'input[type=file]', function (event) {
$("input:file").filestyle({
buttonText: "Seleccionar archivo",
iconName: "fa fa-upload",
buttonName: "btn-primary"
});
});
$('#btnGuardarPasoSieteAgregarProducto').on("click", function (event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// Create a formdata object and add the files
var formData = $('#formRecaudosTramites').serialize();
$.each($('#formRecaudosTramites')[0].files, function (key, value) {
formData = formData + '&recaudos[]=' + value;
});
$.ajax({
url: Routing.generate('rpniSubirRecaudos'),
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
contentType: 'multipart/form-data',
processData: false, // Don't process the files
//contentType: false // Set content type to false as jQuery will tell the server its a query string request
}).done(function (data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
console.log('SUCCESS: ' + data.success);
} else {
// do something with error
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// do something with fail callback
// STOP LOADING SPINNER
});
});
What is happening is: no filenames exists on query string, no files are upload or send through the Ajax call, instead it's sending a [object Object], what I'm doing wrong? Can any give me some working code for this stuff?
EDIT:
After reads the post referenced by user I change my code as the one before and now the error turns on:
TypeError: a is undefined
...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e...
What is wrong there?
Note: Yes, I know there are tons of plugins for handle this like jQuery File Upload from Blueimp, Dropzone and some others but I leave them out since I start using jQuery File Uploader from inside OneupUploaderBundle on my Symfony2 project and spent 4 days without success so I move to the other side: made things by myself so I can learn something else and improve my knowledge
i think this will help you,
var fd = new FormData();
//name is the key on the page of php to access the file
fd.append('name', $('#aob_file')[0].files[0]);
pass this fd object to your data field in ajax,
Problem
After a successful AJAX call, I want to update an element on page. However, it is not being updated.
Code [Javascript]
$(function()
{
$(".upvote").click(function()
{
var id = $(this).parent().find("input").val();
$.ajax(
{
type: "GET",
url: "process.php",
data: "id=" + id +"&f=u",
success: function(results)
{
$(this).parent().parent().find("span.ups").empty().append("Upvotes: " + results);
console.log(results);
}
});
return false;
});
});
Code [HTML]
This code is being generated by PHP.
<div class="post">
<h2>$title</h2>
<p>$body</p>
<span class="ups">Upvotes: $upvotes</span>
<span class="downs">Downvotes: $downvotes</span>
<span class="total">Total votes: $t_votes</span>
<div id="links">
<input type="hidden" id="id" name="id" value="$id">
<button>Upvote!</button>
<button>Downvote!</button>
</div>
</div>
Returned by PHP
The updated number of upvotes.
this is not what you think it is. Its value is determined by how the function it appears in is called (and will change when inside a different function).
I've no idea what it will be in a jQuery success callback, but it won't be an HTML element.
If you want it to be the clicked upon element, then you need to store it while this is that element.
$(".upvote").click(function() {
var clicked_element = this;
Then you can use that variable later on:
$(clicked_element).parent().etc
You cannot use this keyword like that.
var that = null;
$(function()
{
$(".upvote").click(function()
{
var id = $(this).parent().find("input").val();
that = $(this);
$.ajax(
{
type: "GET",
url: "process.php",
data: "id=" + id +"&f=u",
success: function(results)
{
that.parent().parent().find("span.ups").empty().append("Upvotes: " + results);
console.log(results);
}
});
return false;
});
});
I didn't test this, but it should work.
Cheers.
$(this) inside the success callback is not the element you might think it is. It would probably be better to cache the parent object instead and traverse from there:
var $post = $('.post');
//... $.ajax etc
success: function() {
$post.find('.ups').etc //...