Open Jquery dialog from inside Ajax request? - javascript

I have a problem with my current javascript/ajax request. I'm trying to open a Jquery dialog from inside my .append my code follows:
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var NewEdit = row[0];
var PreviousEdit = row[1];
var FunctionName = row[2];
var FunctionID = row[2]
function ShowInfo()
{
dialog('Original: <br>'+PreviousEdit+'<br><br> New: <br>' +NewEdit);
}
$('#RecentEdits').append("<br>Page: "+FunctionName+" - <a href='#' OnClick='ShowInfo()'>Info</a>");
}
I have only pasted relivant code, if required I can post the entire function.
I know for a fact, my variables are correctly set due to them being printed out.
How can I open up a Dialog box showing more information from inside a Javascript function?
Solution:
As there is no correct replies. I have used OQJF's example and produced this:
<script>
function ShowInfo(a,b)
{
alert('Original: \n'+unescape(a)+'\n\n New: \n'+unescape(b));
};
</script>
<script>
//window.setInterval(function()
//{
$(function ()
{
$.ajax({
url: 'RecentUpdates.php', data: "", dataType: 'json', success: function(rows)
{
$('#RecentEdits').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var NewEdit = row[0];
var PreviousEdit = row[1];
var FunctionName = row[2];
var FunctionID = row[3];
$('#RecentEdits')
.append("<br>Page: <a href='Page.php?ID="+FunctionID+"'>"+FunctionName+"</a> - ");
$('#RecentEdits').append("<input type='button' onClick=ShowInfo('"+escape(PreviousEdit)+"','"+escape(NewEdit)+"'); value='Show'>");
}
}
});
});
// }, 1000);
</script>
which has enabled me to access the function from my Javascript printout.
I had troubles with the quotes wrapped around my html so i have decided to make two appends. And this seems to work just fine!

While firstly I think you should set the function showInfo outside of the loop and set 2 parameter for it. Below is the sample code that I didn't test but It should be almost like this.
function ShowInfo(orginVal,newVal)
{
var msg =('Original: <br>'+orginVal+'<br><br> New: <br>' +newVal);
$(<div>msg</div>).appendTo('body).dialog();//maybe you can add some options for dialog
}
below part seems be in another function.
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var NewEdit = row[0];
var PreviousEdit = row[1];
var FunctionName = row[2];
var FunctionID = row[2]
$('#RecentEdits').append("<br>Page: "+FunctionName+" - <a href='#' OnClick='ShowInfo(/*add your 2 parameters here*/)'>Info</a>");
} s

Related

Google apps script update specific cell based on if statement

Currently, my script is updating all cells within the selected range with "YES" but I only want it to update cells that meet the if conditions. Any help would be much appreciated.
//Active spreadsheet var that can be used anywhere in the programme
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get and check if there is an email address
function checkSendEmailAdd () {
//Getting the array of values
var activeSheet = ss.getActiveSheet();
var emailCol = activeSheet.getRange(2, 9, activeSheet.getLastRow() - 1, 2).getValues();
//Looping over the array of values
emailCol.forEach(function(val){
var email = val[0].toLowerCase();
var sentEmail = val[1];
//If the send date column is empty and the email column has a # within the string an email will be sent
if (email.indexOf("#") !== -1 && sentEmail == ""){
//Email contents
var subject = "Survey";
var body = "Hi" + "<br><br>" +
"Testing 123";
GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
//Update and set a new value in the sent email column
var newSetValue = "YES";
var updateSentEmail = activeSheet.getRange(2, 10, activeSheet.getLastRow() - 1, 1).setValue(newSetValue);
} else {
}
});
The problem I'm facing is that the sent column is updating every cell but I only want it to update the cells that have an email in the email column.
Image of what is being executed currently
Try it this way:
I tried to determine the columns from your question. I believe email was column one and sentMail was column two but if I'm wrong you can change them to whatever you need.
function sendEmail() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet0');
var vA=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
var sentA=sh.getRange(2,2,sh.getLastRow()-1,1).getValues();
var html='';
for(var i=0;i<vA.length;i++) {
var email=vA[i][0].toString().trim().toLowerCase();
var sentEmail=vA[i][1];
if(email && email.indexOf("#")>-1 && !sentEmail){
var subject = "Survey";
var body = "Hi<br><br>Testing 123";
//GmailApp.sendEmail(email, subject, "", { htmlBody: body } );
html+=Utilities.formatString('<br />%s -<br />Email: %s<br />Subject: %s<br />Body: %s<br /><hr/>', Number(i+1),email,subject,body);
sentA[i][0]="Yes";
}
}
sh.getRange(2,2,sh.getLastRow()-1,1).setValues(sentA);
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Emails Sent');
}
Spreadsheet before sending:
Spreadsheet after sending:
I removed the Gmail line and used a dialog to display the emails:

PHP Table inline editing - Javascript Function

I am trying to create an inline edit function on my table, the user should be able to retype the values, and click the 'Save' button to update the database record.
I've hit a problem with the javascript function, its not reverting me to the next page as per 'window.location.href', which would be the php update qry page, that reverts me back to the original page to view the changes made.
The javascript function is meant to get the old id , and all of the possibly new td's within the record, which the user may have inline edited.
I had this working for the id itself, but with the addition of all the new values, ive messed up either on the js function or the action but (may the 'this'?) not exactly sure. I know mysql is rubbish and so on, im focusing on functionality at the time being.
JS FUNCTION
function edit_user(id,a,b,c,d,e,f,g,h,i,j,k) {
var tr = a.parentNode.parentNode;
var awb = String(tr.querySelector(".a").innerHTML);
var tb = b.parentNode.parentNode;
var del = String(tb.querySelector(".b").innerHTML);
var tc = c.parentNode.parentNode;
var vsl = String(tc.querySelector(".c").innerHTML);
var td = d.parentNode.parentNode;
var cli = String(td.querySelector(".d").innerHTML);
var te = e.parentNode.parentNode;
var pcs = String(te.querySelector(".e").innerHTML);
var tf = f.parentNode.parentNode;
var wgt = String(tf.querySelector(".f").innerHTML);
var tg = g.parentNode.parentNode;
var car = String(tg.querySelector(".g").innerHTML);
var th = h.parentNode.parentNode;
var snd = String(th.querySelector(".h").innerHTML);
var ti = i.parentNode.parentNode;
var stt = String(ti.querySelector(".i").innerHTML);
var tj = j.parentNode.parentNode;
var ard = String(tj.querySelector(".j").innerHTML);
var tk = k.parentNode.parentNode;
var ctm = String(tk.querySelector(".k").innerHTML);
// run query on server:
window.location.href = 'http://at-web2.comp.glam.ac.uk/students/14075377/14075377/php/edit-livedashboard-import.php?id='+id+'&newawb='+awbno+'&newvsl='+vsl+'&newcli='+cli+'&newpcs='+pcs+'&newwgt='+wgt+'&newcar='+car+'&newsnd='+snd+'&newstt='+stt+'&neward='+ard;;
return false;}
TABLE ACTION BUTTON
$awb = $get_info["AwbNo"];
echo "<a href='' onclick='return edit_user($awb,here,here,here,here,here,here,here,here,here);'>&nbspSave&nbsp</a>";
PHP UPDATE
include("../dbinfo.inc.php");
$comm=#mysql_connect(localhost,$username,$password);
$rs=#mysql_select_db($database) or die( "Unable to select database");
$id = $_GET['id'];
$newawb = $_GET['awbno'];
$newvsl = $_GET['vsl'];
$newcli = $_GET['cli'];
$newpcs = $_GET['pcs'];
$newwgt = $_GET['wgt'];
$newcar = $_GET['car'];
$newsnd = $_GET['snd'];
$newstt = $_GET['stt'];
$neward = $_GET['ard'];
$sql = "UPDATE tbl_import SET AwbNo='$newawb',ClientCode='$newcli',VesselName='$newvsl',Pieces='$newpcs',Weight='$newwgt',Carrier='$newcar',Sender='$newsnd',Status='$newstt',ArrivalDate='$neward',WHERE AwbNo='$id';";
echo ("id=$id,awb=$newawb,vsl=$newvsl,cli=$newcli,pcs=$newpcs,wgt=$newwgt,car=$newcar,send=$newsnd, status=$newstt, date=$neward .\n\n\n");
mysql_query($sql)or die("Update Error: ".mysql_error());
mysql_close();
//commented header so can see echoed vals sent from js
//header("Location: ../livedashboard.php"); //redirect to relevant page
First thing try to print:
console.log('php/edit-livedashboard-import.php?id='+id+awb+del+vsl+cli+pcs+wgt+car+snd+stt+ard+ctm);
it should be like this:
'php/edit-livedashboard-import.php?id='+id+ '&awb='+awd+'&del='+del...etc;
Second thing:
Add full url instead of dir :
window.location.href = 'php/edit-livedashboard-import.php?id='+id+aw...;
ex.
window.location.href = 'http://example.com/php/edit-livedashboard-import.php?id=...';

Getting data from jQuery ajax

I am trying to make an AJAX filter for car list and I got stuck in the last stage. I have two files, index.php and filter.php.
In index.php I have form with drop-down lists and sliders. Code for sending the form is as follows:
$(document).ready(function(){
$("#send").click(function(){
var salon=$("#salon-list").val();
var make=$("#make-list").val();
var model=$("#model-list").val();
var cenaLow=$("#cenaLow").val();
var cenaHigh=$("#cenaHigh").val();
var tachometrLow=$("#tachometrLow").val();
var tachometrHigh=$("#tachometrHigh").val();
var palivo=$("#palivo-list").val();
var karoserie=$("#karoserie-list").val();
var prevodovka=$("#prevodovka-list").val();
var pohon=$("#pohon-list").val();
var barva=$("#barva-list").val();
var dvere=$("#dvere-list").val();
var objem=$("#objem-list").val();
var stav=$("#stav-list").val();
$.ajax({
type:"post",
url:"filter.php",
data:"salon="+salon+"&make="+make+"&model="+model+"&cenaLow="+cenaLow+"&cenaHigh="+cenaHigh
+"&tachometrLow="+tachometrLow+"&tachometrHigh="+tachometrHigh+"&palivo="+palivo+"&karoserie" +
"="+karoserie+"&prevodovka="+prevodovka+"&pohon="+pohon+"&barva="+barva+"&dveře="+dvere+"&objem" +
"="+objem+"&stav="+stav,
success:function(data){
$("#result").html(data);
}
});
});
});
In the filter.php file I get the data from $_POST and then I search through database. After that I want to echo results into #result div but it does not work. Any echo statement doesn't work, variables I want to list aren't empty, I checked.
echo 'iAmHere'; /*just checking*/
$post["salon"] = htmlspecialchars($_POST["salon"]);
$post["make"] = htmlspecialchars($_POST["make"]);
$post["model"] = htmlspecialchars($_POST["model"]);
$post["cenaLow"] = htmlspecialchars($_POST["cenaLow"]);
$post["cenaHigh"] = htmlspecialchars($_POST["cenaHigh"]);
$post["rokLow"] = htmlspecialchars($_POST["rokLow"]);
$post["rokHigh"] = htmlspecialchars($_POST["rokHigh"]);
$post["tachometrLow"] = htmlspecialchars($_POST["tachometrLow"]);
$post["tachometrHigh"] = htmlspecialchars($_POST["tachometrHigh"]);
$post["palivo"] = htmlspecialchars($_POST["palivo"]);
$post["karoserie"] = htmlspecialchars($_POST["karoserie"]);
$post["prevodovka"] = htmlspecialchars($_POST["prevodovka"]);
$post["pohon"] = htmlspecialchars($_POST["pohon"]);
$post["barva"] = htmlspecialchars($_POST["barva"]);
$post["dvere"] = htmlspecialchars($_POST["dvere"]);
$post["objem"] = htmlspecialchars($_POST["objem"]);
$post["stav"] = htmlspecialchars($_POST["stav"]);
echo '<p class="make">'.$post["make"].'</p>'; /*does not work*/
echo "<script>window.alert('".$_POST["make"]."');</script>"; /*another checking, this works*/
Thanks for any help.
Try this :
$(document).ready(function(){
$("#send").click(function(){
var salon=$("#salon-list").val();
var make=$("#make-list").val();
var model=$("#model-list").val();
var cenaLow=$("#cenaLow").val();
var cenaHigh=$("#cenaHigh").val();
var tachometrLow=$("#tachometrLow").val();
var tachometrHigh=$("#tachometrHigh").val();
var palivo=$("#palivo-list").val();
var karoserie=$("#karoserie-list").val();
var prevodovka=$("#prevodovka-list").val();
var pohon=$("#pohon-list").val();
var barva=$("#barva-list").val();
var dvere=$("#dvere-list").val();
var objem=$("#objem-list").val();
var stav=$("#stav-list").val();
var data= {
make: make,
model: model,
cenaLow: cenaLow,
cenaHigh: cenaHigh,
tachometrLow: tachometrLow,
tachometrHigh: tachometrHigh,
palivo: palivo,
karoserie: karoserie,
prevodovka: prevodovka,
pohon: pohon,
barva: barva,
objem: objem,
stav : stav
};
$.ajax({
type:"post",
url:"filter.php",
data:data,
success:function(data){
$("#result").html(data);
}
});
});
});
From here:
JavaScript inserted as DOM text will not execute.
And this says:
You have to use eval() to execute any script code that you've
inserted as DOM text.
So you can try an alternate approach to test your code (though I've not tested).
In filter.php:
<?php
$post["salon"] = htmlspecialchars($_POST["salon"]);
$post["make"] = htmlspecialchars($_POST["make"]);
$post["model"] = htmlspecialchars($_POST["model"]);
$post["cenaLow"] = htmlspecialchars($_POST["cenaLow"]);
$post["cenaHigh"] = htmlspecialchars($_POST["cenaHigh"]);
$post["rokLow"] = htmlspecialchars($_POST["rokLow"]);
$post["rokHigh"] = htmlspecialchars($_POST["rokHigh"]);
$post["tachometrLow"] = htmlspecialchars($_POST["tachometrLow"]);
$post["tachometrHigh"] = htmlspecialchars($_POST["tachometrHigh"]);
$post["palivo"] = htmlspecialchars($_POST["palivo"]);
$post["karoserie"] = htmlspecialchars($_POST["karoserie"]);
$post["prevodovka"] = htmlspecialchars($_POST["prevodovka"]);
$post["pohon"] = htmlspecialchars($_POST["pohon"]);
$post["barva"] = htmlspecialchars($_POST["barva"]);
$post["dvere"] = htmlspecialchars($_POST["dvere"]);
$post["objem"] = htmlspecialchars($_POST["objem"]);
$post["stav"] = htmlspecialchars($_POST["stav"]);
echo $post["make"];
In index.php:
$.ajax({
...
success:function(res){
$("#result").html(res);
alert(res);
}
});
Try this:
die('<p class="make">'.$post["make"].'</p>');
or
echo '<p class="make">'.$post["make"].'</p>';exit;
instead of
echo '<p class="make">'.$post["make"].'</p>'; /*does not work*/
echo "<script>window.alert('".$_POST["make"]."');</script>"; /*another checking, this works*/
It does not work without an exit. I do not know why but it should do the trick. Also, your code has a lot of room for improvement. Do keep looking for better ways to enhance your skills!! Enjoy!!

Converting a html table into a json object and sending it to a php page ,the table has a input field

i have got a html table which is dynamically created by php code taking db data.
the table's last field is a input field for entering a number.
the data from the table has to be sent to another php page for sql insert.
i am new to xml and ajax pls help me out with the above javascript code.
<script>
$(document).ready("enter").click(function(event){
event.preventDefault();
var elementTable = document.getElementById("form_table");
var jObject = [];
for (var i = 0; i < elementTable.rows.length; i++)
{
jObject[i] = [];
jObject[i][0] = elementTable.rows[i].cells[1].innerHTML;
jObject[i][1] = elementTable.rows[i].cells[2].innerHTML;//data from input field
}
console.log(jObject);
var JSONObject = encodeURIComponent(
JSON.stringify(jObject));//GETTING ERROR HERE
var url = "submit.php";
var requestData = "&dtable=" + JSONObject;
var XMLHttpRequestObj = FileResort.Utils.createRequest();
XMLHttpRequestObj.open("POST", url, true);
XMLHttpRequestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XMLHttpRequestObj.send(requestData);
});
</script>
as long as you are using JQuery, adapt this jsfiddle example
$("button").click(function(event){
event.preventDefault();
var tableArray = [];
$("table tbody tr:has(td)").each(function(index,element){
tableArray.push([
$(this).find("td:eq(1)").html(),
$(this).find("td:eq(2)").html()
]);
});
console.log(tableArray);
$("div").text(encodeURIComponent(
JSON.stringify(tableArray)
));
return false;
});
which is mostly what you want for the table serialization minus the ajax call ( which I think should be a POST, but that is my personal opinion )

calling JQuery HTTP GET request inside javascript function

I will start off by saying I am new to Javascript and JQuery. What I want to accomplish is have a submit button on an HTML page that will call the dbQuery function in my .js file that will print the value of variables to the screen and then add them into a MySQL database.
I need to use the JavaScript variable selectedVisibleValue that is defined in my first function dbQuery The reason I want to do this is because I have four drop downs, three of which are hidden drop downs that are only shown depending on the first non hidden dropdown, only one of the hidden drop downs is ever visible.
I want to work with these variables in my PHP page formPage to do the Database functions. My code is below I want to add the testing1 function into the dbQuery function.
I have tried just copying and pasting it into the dbQuery function but it does not work. I am not trying to work with the selectedVisibleValue in the code below. I am just trying to do some testing with some bogus variables.
var dbQuery = function(){
var description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
var selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
var selectedVisibleValue = $(".unitDropDowns select:visible").val();
document.getElementById("descriptionSummary").innerHTML = "<h3>Description</h3>" + "<p>" + description + "</p>";
document.getElementById("equipmentRan").innerHTML = "<h3>Equipment Ran </h3>" + "<p>" + selectedEquip1 + "</p>" + "<h3>Unit Number</h3>" + "<p>" + selectedVisibleValue + "</p>";
document.getElementById("equipmentRan").style.display = "block";
document.getElementById("descriptionSummary").style.display = "block";
}
var testing1 = function() {
$.get(
"formPage.php",
{paramOne : 123, paramX : 'abc'},
function(data) {
document.getElementById("equipmentRan").innerHTML = ('page content: ' + data);
}
);
}
//cache references to static elements
var jobDescription = $('#jobDescription')
, selectedEquip = $('#equipmentList')
, descriptionSummary = $('#descriptionSummary')
, equipmentRan = $('#equipmentRan')
;
function dbQuery(){
//gather params
var params = {
jobDescription : jobDescription.val(),
selectedEquip1 : selectedEquip.val(),
selectedVisibleValue = $(".unitDropDowns select:visible").val()
}
//show summary
descriptionSummary.html('<h3>Description</h3><p>'+description+'</p></h3>').show();
equipmentRan.html('<h3>Equipment Ran</h3><p>'+selectedEquip1+'</p><h3>Unit Number</h3><p>'+selectedVisibleValue+'</p>').show();
//do a get
$.get('formPage.php',params,function(data) {
equipmentRan.html('page content: ' + data);
}
}
jsFiddle DEMO
Passing variables between functions might come in useful for your project.
HTML:
<div id="theBox"></div>
<button>Press Me</button>
JS
$(document).ready(function() {
// This is some other Do More function, defined prior to the next variable function.
// This is your .get() request.
function doMore(target){
// For the incomming targer, add a class style of a larger font.
$(target).css('font-size', 30);
}
// The main function.
var dbQuery = function() {
// Show dynamic text on the HTML page.
var extra = $('#theBox').html('Dynamic Text Results');
// Run some other function, also... send the private variable in use.
doMore(extra);
};
// The submit button.
$('button').on('click', function() {
// Start the function.
dbQuery();
});
});
Here is the working code:
function dbQuery() {
window.description = document.getElementById("jobDescription").value;
var selectedEquip = document.getElementById("equipmentList");
window.selectedEquip1 = selectedEquip.options[selectedEquip.selectedIndex].text;
window.selectedVisibleValue = $(".unitDropDowns select:visible").val();
testing1();
}
function testing1() {
$(document).ready(function() {
$.get(
"formPage.php",
{paramOne : window.selectedVisibleValue, paramX : window.description, paramY : window.selectedEquip1},
function(data) {
document.getElementById("equipmentRan").innerHTML = (data);
}
);
});
}

Categories