Ajax multiple value - javascript

Did anyone know how i can send all this stuff with ajax to a search.php? it is already working but only with a search bar. I want to add to the search bar these variables. Its only important for the sort variable(the div with the sort id) to send the data on the beginning.
i think it would work to save the var into divs and get the values with document.getElementById('').getAttribute('value') but i still need to find out how to add this line of code to this ajax and that the ajax constantly check for changes in this divs. i still want that the ajax file send a output before i even touched the searchbar and the divs
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"post",
data:{search:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
function gettagValue() {
var checks = document.getElementsByClassName('tag');
var strtag = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
str += checks[i].value + "#";
}
}
alert(strtag);
}
function getblacklistValue() {
var checks = document.getElementsByClassName('blacklist');
var strblacklist = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
strblacklist += checks[i].value + "#";
}
}
alert(strblacklist);
}
function getbrandValue() {
var checks = document.getElementsByClassName('brand');
var strbrand = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
strbrand += checks[i].value + "#";
}
}
alert(strbrand);
}
alert(document.getElementById('sort').getAttribute('value'));

Do you mean that you want to send the values you're currently alerting? For starters, return those values instead of just alerting them:
function gettagValue() {
// ...
return strtag;
}
// same for the getblacklistValue and getbrandValue functions
Then in your AJAX code, call those functions to get those values and include them in the data:
function load_data(query)
{
let tagValue = gettagValue();
let blacklistValue = getblacklistValue();
let brandValue = getbrandValue();
$.ajax({
url:"search.php",
method:"post",
data:{
search:query,
tagValue:tagValue,
blacklistValue:blacklistValue,
brandValue:brandValue
},
success:function(data)
{
$('#result').html(data);
}
});
}

Related

What is the proper way to write a JQuery function inside a Java Script Function

I have written a Java Script Function to run on click of a submit button in the form enterCPDetails. I want to do some check in this and then run the AJAX call. But its not Working
function sumbitNewCPTabDataChk() {
//If i comment the next line my code works
$("#enterCPDetails").on("submit", function (event) {
var newCPDetailsTab = document.getElementById('newCPDetailsTable');
var newCPNoInput=document.getElementById('newCPNo');
var newCPNoInputValue=newCPNoInput.value;
if(newCPNoInputValue===""){
alert("Please enter CP No.");
}
// LOOP THROUGH EACH ROW OF THE TABLE.
else{
for (row = 1; row <= newCPDetailsTab.rows.length - 1; row++) {
// loop through each ceel in row
for (c = 0; c < newCPDetailsTab.rows[row].cells.length; c++) {
//get the cell element in variable
var element = newCPDetailsTab.rows.item(row).cells[c];
//check if the child element of cell is text or not. If
text then check if it is not empty
if (element.childNodes[0].getAttribute('type') === 'text')
{
var valueinCell=element.childNodes[0].value ;
if (valueinCell === "" ) {
alert("Please fill complete data in the table.");
exit();
}
}
else{
alert("asdf");
var rowCnt= newCPDetailsTab.rows.length;
document.getElementById('cntTableRows').value=rowCnt;
event.preventDefault();
$.ajax({
url: "../web/addNewCPDetaills.php",
type: "POST",
data: "enterCPDetails".serialize(),
success: function (result) {
console.log(result);
}
});
}
}
}
}
});
}
If i comment the line
$("#enterCPDetails").on("submit", function (event) {
My function works. But with this line it does not. Why?
From what I see I assume you've attached an onclick event handler to the submit button which calls the function sumbitNewCPTabDataChk(). This isn't necessary because essentially that's what the submit event of Jquery does.
So get rid of the click handler, the function sumbitNewCPTabDataChk and just use Jquery's submit like:
$("#enterCPDetails").on("submit", function(event) {
var newCPDetailsTab = document.getElementById('newCPDetailsTable');
var newCPNoInput = document.getElementById('newCPNo');
var newCPNoInputValue = newCPNoInput.value;
if (newCPNoInputValue === "") {
alert("Please enter CP No.");
}
// LOOP THROUGH EACH ROW OF THE TABLE.
else {
for (row = 1; row <= newCPDetailsTab.rows.length - 1; row++) {
// loop through each ceel in row
for (c = 0; c < newCPDetailsTab.rows[row].cells.length; c++) {
//get the cell element in variable
var element = newCPDetailsTab.rows.item(row).cells[c];
//check if the child element of cell is text or not. If text then check if it is not empty
if (element.childNodes[0].getAttribute('type') === 'text') {
var valueinCell = element.childNodes[0].value;
if (valueinCell === "") {
alert("Please fill complete data in the table.");
exit();
}
} else {
alert("asdf");
var rowCnt = newCPDetailsTab.rows.length;
document.getElementById('cntTableRows').value = rowCnt;
event.preventDefault();
$.ajax({
url: "../web/addNewCPDetaills.php",
type: "POST",
data: "enterCPDetails".serialize(),
success: function(result) {
console.log(result);
}
});
}
}
}
}
});

How to get last instance of an array built from for loop?

I'm using a for loop to search api results and build an array of objects so I can use that data and append it to the DOM. I'm doing this because Flickr's API's results aren't consistent to their values. For example, I'm looking for "aperture" and sometimes it's index number is [9], sometimes it's [11], and so on. I'm not sure if there's another way to achieve the results I'm looking for. I figured I could just loop through the results and search for the values I need.
Is there a way to grab only the last instance of the array? As it is now if I were to call exifArray[9].aperture it would show the result multiple times and also as undefined when the loop hasn't reached that part yet. I attempted to move the console.log(exifArray) to just outside of the for loop so it wouldn't repeat but it just returns the empty array that was declared at the top of the function.
Here's a screen shot of the console and also a code snippet:
Flickr.prototype.exifData = function(results) {
var apiKey = '';
var self = this;
var exifArray = [];
for (var i=0; i<results.photos.photo.length; i++) {
var currentId = results.photos.photo[i].id;
var exifData = $.ajax({
url: "https://api.flickr.com/services/rest/?method=flickr.photos.getExif&api_key=" + apiKey + "&photo_id=" + currentId + "&format=json",
dataType: "jsonp",
jsonp: 'jsoncallback',
type: "GET",
})
.done(function(exifResults) {
var options = {};
if (exifResults.stat === "ok") {
for (var x=0; x<exifResults.photo.exif.length; x++) {
var labelArray = exifResults.photo.exif[x].label;
if (labelArray === 'Model') {
options.cameraType = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Lens Model') {
options.lensModel = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Exposure') {
options.exposure = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Aperture') {
options.aperture = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'ISO Speed') {
options.iso = exifResults.photo.exif[x].raw._content;
} else {continue}
}
}
exifArray.push(options);
console.log(exifArray);
if (exifResults.stat === "ok") {
self.content.renderExifData(exifArray);
}
})
}
}
You can use pop()
var lastItem = arr.pop();

JavaScript ajax success break and continue not working

Hey guys so am testing this cracker am working on via localhost to see if i can do it really since am bored and want to do something so i thought about this but may i ask why break and continue arnt working its a for loop isnt it?, So it should work.
Edit:
Forgot to mention that the code doesnt even work when i added the break and continue.
Any help is great thanks.
function doTest() {
var html_next;
var user_l = document.getElementById("users");
var pass_l = document.getElementById("pass");
if (user_l.value == "") {
alert("The username field cant be empty!")
} else if (pass_l.value == "") {
alert("The password field cant be empty!")
}
var message = document.getElementById('status_1');
var user_l_s = user_l.value.split("\n");
var pass_l_s = pass_l.value.split("\n");
for (var i = 0; i < user_l_s.length; i++) {
num_users++;
for (var j = 0; j < pass_l_s.length; j++) {
$.ajax({
url: 'posttest.php',
type: 'GET',
data: {'users': user_l_s[i], 'pass': pass_l_s[j]},
dataType: 'text',
async: false,
success: (function (i, j) {
return function (response) {
html_next = response;
if (html_next.indexOf("Failed") > -1) {
continue;
} else if (html_next.indexOf("Cracked") > -1) {
break;
} else if (html_next.indexOf("DELETED") > -1) {
break;
}
}
})(i, j),
beforeSend: function () {
message.innerHTML = "Cracking Test...";
}
});
}
}
message.innerHTML = "Done...";
}
It is because you are sending an Async request to your server. Which means your server is handling multiple requests and it is not necessary that every request gets responded to in the same time.
What you are looking for is sequential code that can process your data all at once.
You should try async:false and then try
You have to use success callbacks, you just need to use other logic. Instead for loops, call to a function when the ajax success is complete. This function have to register the changes and, if necessary, stop or keep working.
Here is an example that I used with another SO user but the logic and the idea are the appropriate. Instead of using loops, we wait for each success callback to keep working.
var MyApp = {
Scripts: {
ToLoad: [
'/path/to/script1.js',
'/path/to/script2.js',
'/path/to/script3.js'
],
Loaded: 0
},
DoTheJob: function(){
if( this.Scripts.ToLoad.length == this.Scripts.Loaded ) {
// do some stuff
return;
}
$.getScript(this.Scripts.ToLoad[this.Scripts.Loaded], function(){
MyApp.Scripts.Loaded++;
MyApp.DoTheJob();
});
}
};
$(function(){
MyApp.DoTheJob();
});
Here is the jsFiddle
This should do it..
You can even try it out with async = true
I think so it should work with it too
function doTest() {
var html_next;
var user_l = document.getElementById("users");
var pass_l = document.getElementById("pass");
if (user_l.value == "") {
alert("The username field cant be empty!")
} else if (pass_l.value == "") {
alert("The password field cant be empty!")
}
var message = document.getElementById('status_1');
var user_l_s = user_l.value.split("\n");
var pass_l_s = pass_l.value.split("\n");
for (var i = 0; i < user_l_s.length; i++) {
num_users++;
function makeReq(pass_l_s, index) {
var index = index || 0;
$.ajax({
url: 'posttest.php',
type: 'GET',
data: {
'users': user_l_s[i],
'pass': pass_l_s[index]
},
dataType: 'text',
async: false,
success: (function(i, index) {
return function(response) {
html_next = response;
if (html_next.indexOf("Failed") > -1) {
index += 1
if (index < pass_l_s.length)
makeReq(pass_l_s, index)
// continue;
} else if (html_next.indexOf("Cracked") > -1) {
// break;
} else if (html_next.indexOf("DELETED") > -1) {
// break;
}
}
})(i, index),
beforeSend: function() {
message.innerHTML = "Cracking Test...";
}
});
}
makeReq(pass_l_s)
}
message.innerHTML = "Done...";
}

Delete div if no ajax info about id

i got this code
function get_players()
{
$.ajax({
type: "POST",
url: "get_players.php",
dataType: "html",
success: function(data) {
var str = data;
var chars = str.split("<br />");
for(var i = chars.length - 1; i >= 0 ;i-- ) {
chars[i] = chars[i].split('/');
var o = document.getElementById(chars[i][0]);
var aimt = i;
if (!o) {
if (aimt!=chars.length -1) {
$('#gracze').html('<div id="'+chars[aimt][0]+'" class="char"><div id="char_name" style="left:-'+(((chars[aimt][3].length*9)/2)-16)+'px;width:'+(chars[aimt][3].length*9)+'px;">'+chars[aimt][3]+'</div></div>'+$('#gracze').html());
$('#'+chars[aimt][0]).css("top", chars[aimt][2]*32-16+"px");
$('#'+chars[aimt][0]).css("left", chars[aimt][1]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]+1);
}
} else {
$('#'+chars[aimt][0]).animate({
"top": chars[aimt][2]*32-16+"px", "left": chars[aimt][1]*32+"px"
}, { duration: 300});
//$('#'+chars[aimt][0]).css("top", chars[aimt][1]*32-16+"px");
//$('#'+chars[aimt][0]).css("left", chars[aimt][2]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]);
}
}
}});
setTimeout("get_players();", 300);
}
which receives players from this
5/7/13/GodFather
6/7/10/dsfsf
7/8/13/fdsf
and i want to ask how to delete div if there's no info about user
As you don't know which div elements to remove, the only way is removing them all then adding those you get from the AJAX response.
To remove them all, use the class that you already have:
$(".char").remove();
Add this line to the success function, before iterating over the lines.
OK, you can save the ID values returned by the AJAX call in array then remove any that does not exist in the array. Revised function code:
success: function(data) {
var str = data;
var chars = str.split("<br />");
var arrDivIDs = new Array();
for(var i = chars.length - 1; i >= 0 ;i-- ) {
chars[i] = chars[i].split('/');
arrDivIDs[chars[i][0]] = true;
var o = document.getElementById(chars[i][0]);
var aimt = i;
if (!o) {
if (aimt!=chars.length -1) {
$('#gracze').html('<div id="'+chars[aimt][0]+'" class="char"><div id="char_name" style="left:-'+(((chars[aimt][3].length*9)/2)-16)+'px;width:'+(chars[aimt][3].length*9)+'px;">'+chars[aimt][3]+'</div></div>'+$('#gracze').html());
$('#'+chars[aimt][0]).css("top", chars[aimt][2]*32-16+"px");
$('#'+chars[aimt][0]).css("left", chars[aimt][1]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]+1);
}
} else {
$('#'+chars[aimt][0]).animate({
"top": chars[aimt][2]*32-16+"px", "left": chars[aimt][1]*32+"px"
}, { duration: 300});
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]);
}
}
$(".char").each(function(index) {
if (!arrDivIDs[$(this).attr("id")])
$(this).remove();
});
}
Use .remove() http://api.jquery.com/remove/
EDIT
Where you have the check to see whether there is any data coming back (assume var o) you can do this:
o.remove();
EDIT 2
You can use variables in jQuery to select the id:
$("#" + chars[i][0]).remove();

total up json data?

[UPDATE]
Thanks guys,final code:
var EUR_share_cost = 0;
var USD_share_cost = 0;
var GBP_share_cost = 0;
var EUR_total_cost = 0;
var USD_total_cost = 0;
var GBP_total_cost = 0;
$.ajax({
url: '/producer/json/index/period/month/empties/'+empties+'/fields/'+fields+'/start/'+start+'/end/'+end+'',
async: false,
success: function(returned_values) {
$.each(returned_values.aaData, function(index, item) {
if (item[2] == 'EUR') {
EUR_share_cost += parseFloat(item[5]);
EUR_total_cost += parseFloat(item[3]);
} else if (item[2] == 'USD') {
USD_share_cost += parseFloat(item[5]);
USD_total_cost += parseFloat(item[3]);
} else if (item[2] == 'GBP') {
GBP_share_cost += parseFloat(item[5]);
GBP_total_cost += parseFloat(item[3]);
}
});
}
});
$('#EUR_share_cost').html(EUR_share_cost);
$('#USD_share_cost').html(USD_share_cost);
$('#GBP_share_cost').html(GBP_share_cost);
}
});
When you're in $.each(), the callback has 2 parameters, the first is the index (that incrementing number you're seeing), the second is the actual item, you'd actually want something like this:
$.each(returned_values || {}, function(index, item) {
console.log(item);
});
I think overall you're looking for this:
var eur_total = 0;
$.each(returned_values && returned_values.aaData || {}, function(index, item) {
if(item[2] == "EUR") eur_total += parseFloat(item[3]);
});
$('#EUR-total').val(eur_total);​
This would total up the third column...not sure which column you're after (maybe 5th?), you can give it a try here.
The first part of $.each is the index, the second part is the data see the documentation for details.
Your code should instead look like this:
$.ajax({
url: '/area/json/index/period/month/',
async: false,
success: function(returned_values) {
console.log(returned_values);
$.each(returned_values || {}, function(index,item) {
console.log(item);
});
}
})

Categories

Resources