so I'd like to assign a url parameter value to jquery but it won't take it ..
var product_id = '<?php echo $_GET["pID"]; ?>';
my function is below , document ready is included... just posted the relevant stuff
function sendOrderToServer() {
var order = $(".sortable_table").sortable("serialize");
var array_order = order.split("&");
var product_id = '<?php echo $_GET["pID"]; ?>';
alert(product_id);
for (var i=0;i<array_order.length;i++){
var id = array_order[i].split("=");
id = id[1];
var text_field_video = $("#products_video_sm_dynamic_"+ id).val();
var text_field_video_caption = $("#products_video_sm_dynamic_"+ id +"_caption").val();
var text_field_image = $("#products_image_sm_dynamic_"+ id).val();
var text_field_image_caption = $("#products_image_sm_dynamic_"+ id +"_caption").val();
var text_field_video_xl = $("#products_video_xl_dynamic_"+ id).val();
var text_field_video_xl_caption = $("#products_video_xl_dynamic_"+ id +"_caption").val();
var text_field_image_xl = $("#products_image_xl_dynamic_"+ id).val();
if(text_field_video != undefined){
var element = "products_video_sm_dynamic_" + id;
var position = i + 1;
}
if(text_field_image != undefined){
var element = "products_image_sm_dynamic_" + id ;
var position = i + 1;
}
if(text_field_video_xl != undefined){
var element2 = "products_video_xl_dynamic_" + id ;
var position = i + 1;
}
if(text_field_image_xl != undefined){
var element2 = "products_image_xl_dynamic_" + id ;
var position = i + 1;
}
//alert(element);
//alert("position is" + position);
$.ajax({
type:'POST',
url :'includes/insert_database.php',
data:{ position : position, element1:element , element2:element2},
success: function(result){
alert(result);
}
});
}
}
http://example.com/yourpage.php?pID=%27%3B+alert%28%27OMG+I+just+totally+hacked+your+site%21%27%29%3B+%27
Try this instead:
var product_id = <?php echo json_encode($_GET['pID']); ?>
Related
I have a function which makes an AJAX call and depending on the answer, sets the colour of an input. The function core itself works fine. However, when it comes to changing the colour of the input, it is not working.
function Nueva_Red() {
var e1 = document.getElementById("rrss_tipo");
var e2 = document.getElementById("rrss_usuario");
var e3 = document.getElementById("redes");
var e4 = document.getElementById("alta_nueva_red");
var id_red = e1.options[e1.selectedIndex].value;
var red = e1.options[e1.selectedIndex].text;
var usuario = e2.value;
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
if ((id_red > 0) && (usuario != "")) {
var datastr = 'seccion=rrss_check&dato=' + id_red + "|" + usuario;
$.ajax({
type: 'GET',
url: 'validacion.php',
data: datastr,
success: function(html) {
if (html == 1) {
document.getElementById("nuevas_rrss").style.visibility = "visible";
document.getElementById("nuevas_rrss").style.display = "inline-block";
var opcion = document.createElement("option");
opcion.value = id_red + "-" + usuario;
opcion.innerHTML = red + " -> " + usuario;
e3.appendChild(opcion);
e1.value = 0;
e2.value = "";
e2.title = "";
e2.style.backgroundColor = "none";
e2.style.borderColor = "black";
} else {
e2.title = html;
e2.style.backgroundColor = error_error;
e2.style.borderColor = error_error;
}
},
error: function(html) {
e2.style.borderColor = error_app;
e2.style.backgroundColor = error_app;
}
});
}
}
Thank you!
How can i run the below code only after the code 1 has load all its content from the external page ?
jQuery Script tried
//filters
$(window).bind("load", function() {
$(".filters li").on("click", function () {
id = ($(this).data("id")+'').split(',');
filter = $(this).data("filter");
$("#hotel-list .box").hide();
id[0] == "all" && $("#hotel-list .box").show() || id.forEach(function(v){
$('#hotel-list .box[data-'+filter+'*="'+v.trim()+'"]').show();
});
return false;
});
<!-- Count Star Rating -->
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars + two_stars;
$('.totals').text(totals);
<!-- Count Board -->
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb + board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function( url ){
var img = document.getElementsByTagName('img');
var i=0, l=img.length;
for(;i<l;i++){
var t = img[i];
if(t.naturalWidth === 0){
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
And the jQuery AJAX code is:
var datastring = location.search; // now you can update this var and use
$("#hotel-list").load("Rezults2.php"+ datastring + " #hotel-list> *");
So i need that the 1st codes to be executed only after the 2nd code has done its job ( from 3 to 9 secs )
ANy ideea on this ?
function runThisAfter() {
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
//etc...
}
$("#hotel-list").load("Rezults2.php", function(){ runThisAfter(); });
This will run "runThisAfter()" when load is complete.
Solution is:
$(document).ajaxComplete(function( event, xhr, settings ) {
// Your complete function here
});
Or in my Case full code:
$(document).ajaxComplete(function(event, xhr, settings) {
//Count STARS
var two_stars = $("article[data-stars*='2']").length;
var three_stars = $("article[data-stars*='3']").length;
var four_stars = $("article[data-stars*='4']").length;
var five_stars = $("article[data-stars*='5']").length;
$('.total-three').text(three_stars);
$('.total-four').text(four_stars);
$('.total-five').text(five_stars);
var totals = three_stars + four_stars + five_stars +
two_stars;
$('.totals').text(totals);
//COUNT BOARD
var board_no = $("article[data-board*='No']").length
var board_ro = $("article[data-board*='Room']").length
var board_bb = $("article[data-board*='Breakfast']").length;
var board_fb = $("article[data-board*='Full Board']").length
var board_hb = $("article[data-board*='Half']").length
var board_ai = $("article[data-board*='All']").length
var board_sc = $("article[data-board*='Self']").length
$('.total-ro').text(board_ro);
$('.total-bb').text(board_bb);
$('.total-fb').text(board_fb);
$('.total-hb').text(board_hb);
$('.total-ai').text(board_ai);
$('.total-sc').text(board_sc);
var total = board_ro + board_bb + board_fb + board_hb +
board_ai + board_sc + board_no;
$('.total').text(total);
//Fix broken images
fixBrokenImages = function(url) {
var img = document.getElementsByTagName('img');
var i = 0,
l = img.length;
for (; i < l; i++) {
var t = img[i];
if (t.naturalWidth === 0) {
//this image is broken
t.src = url;
}
}
}
window.onload = function() {
fixBrokenImages('images/noimg.png');
}
});
});
Hi Guys i encounter Problem on my program which says that i have no method 'toFixed' what is the meaning or what to do to fix this?
Here is MY javascript
<script type="text/javascript">
$(document).ready(function(){
$("#datepicker").kendoDateTimePicker({
format: "yyyy-MM-dd HH:mm:ss"
});
$("#supplier_list").kendoComboBox();
$(".code_select").kendoComboBox();
//automatic computation in rows
$('[id^=qty],[id^=price],#tin_number').on('change',function() {
var index = this.id.match(/\d+/)[0];
var qty = parseInt($('#qty'+index).val());
var price = parseFloat($('#price'+index).val());
var disc = $("#discount").val();
var total = 0;
$('#total'+index).val((qty * price ? qty * price : 0).toFixed(2));
var total = 0;
$('[id^=total]').each(function(index){
total+=parseFloat($(this).val()?$(this).val():0);
});
var totalAll = $('#sum_of_total').val(total.toFixed(2));
var vatable = 0;
var vatable_amt = 0;
var totalVat = 0;
var computeDisc = 0;
if($("#tin_number").val().length != 0){
vatable = total / 1.12;
vatable_amt = vatable * 0.12;
totalVat = vatable + vatable_amt;
}else{
totalVat = total;
}
$('#vatable').val(vatable.toFixed(2));
$("#vatable_amount").val(vatable_amt.toFixed(2));
var gtotal = $("#gtotal").val(totalVat.toFixed(2));
$("#total_amt_due").val(gtotal.toFixed(2));
// Here is the line of error uncaught TypeError : Object[object object] has no method'toFixed'
});
$("#discount").on('change',function(){
var totalSales = $("#gtotal").val();
var discountedAmt = $("#discount").val();
var computeTotalDisc = totalSales - discountedAmt;
$("#total_amt_due").val(computeTotalDisc.toFixed(2));
});
//AUTO ASSIGN TO SUPPLIER INFO
$('#supplier_list').bind('change', function(){
var var_add_category ='<?php echo site_url("purchaseorder_controller/supplier_details"); ?>';
$.ajax({
type:'POST',
url: var_add_category,
data:{ id: $(this).val() },
dataType:'json',
success:function(d){
var bankname = d['bankname'];
var bankbranch = d['bankbranch'];
$("[name=spaddress]").val(d['spaddr']);
$("[name=tin]").val(d['sptinno']);
$("[name=contactperson]").val(d['pricontactname']);
$("[name=contactnumber]").val(d['sptelno']);
$("[name=bank]").val(bankname + ' - ' + bankbranch);
$("[name=account_name]").val(d['bankacctname']);
$("[name=account_no]").val(d['bankacctno']);
}
});
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate != ''){
$("#qty"+index).removeAttr('readonly');
$("#price"+index).removeAttr('readonly');
}
});
$("[id^=code]").on('change',function(){
var index = this.id.match(/\d+/)[0];
var validate = $('#code'+index).val();
if(validate == ''){
$("#qty"+index).prop('readonly', true);
$("#price"+index).prop('readonly', true);
}
What to do pls help me guys thank you for the help in advance
gtotal is a jQuery object, not a number ?
var gtotal = $("#gtotal").val(totalVat.toFixed(2)); // returns jQuery object
$("#total_amt_due").val(gtotal.toFixed(2)); // that has no toFixed()
try:
var gtotal = totalVat.toFixed(2);
$("#gtotal, #total_amt_due").val(gtotal);
Try this:
var gtotal = +$("#gtotal").val(totalVat.toFixed(2)).val();
Then gtotal is number.
Also, you can't calculate a number that has already been .toFixed()
so you can do:
$('#vatable').val(vatable.toFixed(2));
$("#vatable_amount").val(vatable_amt.toFixed(2));
var gTotal = totalVat;
$("#gtotal").val(totalVat.toFixed(2));
$("#total_amt_due").val(gtotal.toFixed(2));
but you can't do:
var gTotal = totalVat.toFixed(2); //pretend this equaled 1000.00
var total_amt_due = gTotal + 1.toFixed(2);// this would give you 1000.001.00
or
var total_amt_due = total_amt_due.toFixed(2);//this would give you the object no method toFixed error
I need to create data for a JSON request with the inputs taken from an html form. The data format that I want to generate is like below.
{
"applicationName":"Tesing",
"cpuCount":"12",
"hostdescName":"localhost",
"maxMemory":"0",
"maxWallTime":"0",
"minMemory":"0",
"nodeCount":"1",
"processorsPerNode":"12",
"serviceDesc":{
"inputParams":[
{
"dataType":"input",
"description":"my input",
"name":"myinput",
"type":"String"
},
{
"dataType":"input",
"description":"my input",
"name":"myinput",
"type":"String"
}
],
"outputParams":[
{
"dataType":"output",
"description":"my output",
"name":"myoutput",
"type":"String"
},
{
"dataType":"output",
"description":"my output",
"name":"myoutput",
"type":"String"
}
]
}
}
My code looks like below;
var jasonRequest = {};
jasonRequest["applicationName"] = appName;
jasonRequest["cpuCount"] = cpuCount;
jasonRequest["hostdescName"] = hostName;
jasonRequest["maxMemory"] = maxMemory;
jasonRequest["maxWallTime"] = ""; //TODO
jasonRequest["minMemory"] = ""; //TODO
jasonRequest["nodeCount"] = nodeCount;
jasonRequest["processorsPerNode"] = ""; //TODO
var inArray = new Array();
for(var j=0; j<inputCount; j++) {
var input = {};
input["dataType"] = "input";
input["description"] = "empty";
input["name"] = $("#inputName" + j+1).val();
input["type"] = $("#inputType" + j+1).val();
inArray[j] = input;
}
var outArray = new Array();
for(var j=0; j<outputCount; j++) {
var output = {};
output["dataType"] = "output";
output["description"] = "empty";
output["name"] = $("#outputName" + j+1).val();
output["type"] = $("#outputType" + j+1).val();
outArray[j] = output;
}
var serviceDesc = {};
serviceDesc["inputParams"] = inArray;
serviceDesc["outputParams"] = outArray;
jasonRequest["serviceDesc"] = serviceDesc;
alert("printing inArray");
alert(inArray.toSource().toString());
alert(JSON.stringify(jasonRequest));
The data created by this code is like below. I could use strings and create the message by concatenating it but I don't think that is a nice way of doing this. As you can see the inputParams and outputParams are not properly populated. Can you suggest how can I properly generate this message.
{
"applicationName":"Tesing",
"cpuCount":"12",
"hostdescName":"localhost",
"maxMemory":"0",
"maxWallTime":"0",
"minMemory":"0",
"nodeCount":"1",
"processorsPerNode":"12",
"serviceDesc":{"inputParams":"","outputParams":[]}}
[EDIT]
My code looks like below.
$(document).ready(function(){
var inputCount = 0;
var outputCount = 0;
$("p1").live("click", function(){
inputCount++;
$(this).after("<br/>");
$(this).after("Input Name *:" +
"<input type="text" id="inputName" + inputCount + "" name="inputName" + inputCount + "" value="echo_input" size="50"><br/>");
$(this).after("Input Type *:" +
"<input type="text" id="inputType" + inputCount + "" name="inputType" + inputCount + "" value="String" size="50"><br/>");
});
$("p2").live("click", function(){
$(this).after("Output Name *:" +
"<input type="text" id="outputName" + outputCount + "" name="outputName" + outputCount + "" value="echo_output" size="50"><br/>");
$(this).after();
$(this).after("Output Type *:" +
"<input type="text" id="outputType" + outputCount + "" name="outputType" + outputCount + "" value="String" size="50"><br/>");
});
$('[name="btn2"]').click(function(){
var appName = $("#appName1").val();
var exeuctableLocation = $("#exeuctableLocation1").val();
var scratchWorkingDirectory = $("#scratchWorkingDirectory1").val();
var hostName = $("#hostName1").val();
var projAccNumber = $("#projAccNumber1").val();
var queueName = $("#queueName1").val();
var cpuCount = $("#cpuCount1").val();
var nodeCount = $("#nodeCount1").val();
var maxMemory = $("#maxMemory1").val();
var serviceName = $("#serviceName1").val();
var inputName1 = $("#inputName1").val();
var inputType1 = $("#inputType1").val();
var outputName = $("#outputName1").val();
var outputType = $("#outputType1").val();
var jsonRequest = {};
jsonRequest["applicationName"] = appName;
jsonRequest["cpuCount"] = cpuCount;
jsonRequest["hostdescName"] = hostName;
jsonRequest["maxMemory"] = maxMemory;
jsonRequest["maxWallTime"] = ""; //TODO
jsonRequest["minMemory"] = ""; //TODO
jsonRequest["nodeCount"] = nodeCount;
jsonRequest["processorsPerNode"] = ""; //TODO
var inArray = [];
for(var j=0; j<inputCount; j++) {
var input = {};
input["dataType"] = "input";
input["description"] = "empty";
input["name"] = $("#inputName" + j+1).val();
input["type"] = $("#inputType" + j+1).val();
inArray[j] = input;
}
var outArray = new Array();
for(var j=0; j<outputCount; j++) {
var output = {};
output["dataType"] = "output";
output["description"] = "empty";
output["name"] = $("#outputName" + j+1).val();
output["type"] = $("#outputType" + j+1).val();
outArray[j] = output;
}
var serviceDesc = {};
serviceDesc["inputParams"] = inArray;
serviceDesc["outputParams"] = outArray;
jsonRequest["serviceDesc"] = serviceDesc;
alert("printing inArray");
alert(inArray.toSource().toString());
alert(JSON.stringify(jsonRequest));
$.ajax({
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
url: "http://localhost:7080/airavata-registry-rest-services/registry/api/applicationdescriptor/build/save/test",
data: jasonRequest
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
});
</script>
What's inputCount and outputCount? Seems like they are zero or NaN or something, so you get empty arrays. Yet, your code will still print "inputParams":[] instead of "inputParams":"".
To get a nice output (not that it would be needed for your app, only for debugging), you can use the third parameter of JSON.stringify.
So I am trying to loop through some elements and change some text based on the result of an ajax call. the problem is I cannot get the data out of the ajax callback and I am not sure how exactly to chain the events to do so. I am getting a stock quote value it would be nice if I could just return that object up into the previous scope, the loop of matches, and then do all the manipulation there.
$(function(){
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var tweet_html = $(this).html();
tweet_html = tweet_html.replace(symbol_pat,function(){
var symbol = arguments[2];
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format':format,
'q':query,
'env':env
},
success: function(data){
var quote = data.query.results.quote;
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
tweet_html = arguments[0].replace(html_str);
$(this).html(tweet_html);
}
});
});
});
});
$.ajax() runs asynchronously, so you can't really "wait" for the success in the previous scope. You can use jQuery promise and Deferred to do this though. Check out http://www.erichynds.com/jquery/using-deferreds-in-jquery/ and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
EDIT:
showing an alternate solution that doesn't require promise or deferred:
$(function(){
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var that = this;
var symbol = arguments[2];
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format':format,
'q':query,
'env':env
},
success: function(data){
var quote = data.query.results.quote;
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
var tweet_html = $(that).html();
var tweet_html = arguments[0].replace(html_str);
tweet_html = tweet_html.replace(symbol_pat,html_str);
$(that).html(tweet_html);
}
});
});
});
});
so long as your replace code is correct, I believe the following rework of your code should work (or at least get you darn close, as this is untested and depends on the rest of your code):
$(function(){
var YAHOO_API_URL = 'http://query.yahooapis.com/v1/public/yql'
var tweets = $('.tweet');
var symbol_pat = /(^|\s\$)([a-z]+\b)/gi;
$.each(tweets, function(){
var tweet_html = $(this).html();
tweet_html = tweet_html.replace(symbol_pat, function(){
var symbol = arguments[2];
var format = 'json'
var query = 'select * from yahoo.finance.quotes where symbol in ("'+symbol+'")';
var env = "store://datatables.org/alltableswithkeys";
var quoteHtml = getQuote(format, query, env, function(quote) {
var change = quote.Change;
var change_pct = quote.ChangeinPercent;
var quote_price = quote.LastTradePriceOnly;
var html_str = "";
if( change.indexOf("+") != -1 ){
html_str = '<span class="symWrap up">'+arguments[0]+'</span>';
}
else{
html_str = '<span class="symWrap down">'+arguments[0]+'</span>';
}
return arguments[0].replace(html_str);
});
return quoteHtml;
});
$(this).html(tweet_html);
});
var getQuote = function(format, query, env, successCallback) {
$.ajax({
'url':YAHOO_API_URL,
'async':false,
'method':'GET',
'data': {
'format': format,
'q': query,
'env': env
},
success: function(data){
var quote = data.query.results.quote;
if(successCallback !== undefined && typeof successCallback == 'function') {
successCallback(quote);
}
}
});
};
});