Form newline issue - php

I am sending a form with a notes field to an Oracle database and then displaying the notes. New notes can be added, and they will be appended to the previous note.
The problem I have is with the newline that I am inserting at the beginning of each notes update. I am sending notes updates to the database with a javascript in this manner: oldNote + "\n" + date + " " + username + ": " + newNote;.
This is the php part:
echo "<input class='button' type='button' id='Save' name='saveInteraction' onclick=\"saveInteractionInfo('$oldNote', '$date', '$username', '$interactionId', '$seqNum');\" value='Update'/>";
This is the entire javascript function:
function saveInteractionInfo(oldNote, date, username, interactionId, seqNum) {
var formData = {};
formData['interactionId'] = interactionId;
formData['seqNum'] = seqNum;
formData['notes'] = oldNote + "\n" + date + " " + username + ": " + document.all.notes.value;
trxId = readCookie("transactionId");
if(trxId)
formData["transactionId"] = trxId;
var respFunc = function(par1,par2,par3,par4) { postUpdateInteractionNotesResponseHandler(par1,par2,par3,par4); };
var errorFunc = function(reqId) { return showErrorCaseHandler(reqId); };
ajaxPostRequest("Interactions.php",formData,"Update Interaction Notes.","subExtra",respFunc,errorFunc);
}
Updating the notes works at it should, but when trying to update it for the second time I get an error in Firebug: unterminated string literal: saveInteractionInfo('Test, where saveInteractionInfo is the function I am passing the notes to and 'Test' is the form value. So the error occurs when the newline is passed to the function.
Any suggestions how I could get this working?
UPDATE So the problem is that the $oldNote has line breaks (\n) in it, which stops it from passing the data to the javascript function.
The tag now:
<input class='button' type='button' id='Save' name='saveInteraction' onclick="saveInteractionInfo('fdsfsfsf
dfdfdf
gdfgdg', '13/09/2011 16:11:13', 'blaha01', '7038245', '2');" value='Update'/>
The tag as it should be:
<input class='button' type='button' id='Save' name='saveInteraction' onclick="saveInteractionInfo('fdsfsfsfdfdfdfgdfgdg', '13/09/2011 16:11:13', 'blaha01', '7038245', '2');" value='Update'/>
Any other suggestions?

Replace the newlines by \\n using an RE, in PHP:
$oldNote = preg_replace('/\n/g', "\\n", $oldNote);
EDIT
Did you already handle characters such as '>' and '&'? If not, also use $oldNote = htmlentities($oldNote);. Otherwise, a " will break your code.

Maybe one or more of your PHP variables ($oldNote eg) has a single quote in it. When you write out the javascript you get:
onclick=\"saveInteractionInfo('Test''
Which would cause the JS to be invalid.
Suggest you change the onclick to take the single quote and wrap the php vars in \":
onclick='saveInteractionInfo(\"$oldNote\", ...

The solution was similar to the one posted by Rob W:
$oldNote = str_replace("\r\n", "\\n", $oldNote);

Related

jQuery don't work inside PHP echo

Value of $qty is in my database. I've read few similar questions and I already added $(document).ready but it's still not working.
echo "<div class='sp-quantity'>
<div class='sp-minus fff'><a class='ddd' href='#' data-multi='-1'>-</a></div>
<div class='col-xs-3 sp-input'>
<input type='text' class='quntity-input form-control qty' pid='$bookid' id='qty-$bookid' value='$qty'/>
</div>
<div class='sp-plus fff'><a class='ddd' href='#' data-multi='1'>+</a></div>
</div>";
echo "<script>";
echo "$(document).ready(function(){";
echo "$('.ddd').on('click', function() {";
echo "var $button = $(this);";
echo "var $input = $button.closest('.sp-quantity').find('input.quntity-input');";
echo "$input.val(function(i, value) {";
echo "return +value + (1 * +$button.data('multi'));";
echo "});";
echo "});";
echo "});";
echo "</script>";
You're getting your PHP & Javascript variable syntax confused. PHP uses $ as the start of every variable name. Javascript doesn't, plus jquery uses $ in a special way. On top of that, PHP does automatic string substitution of anything starting with a $ that can be a valid variable name as long as the string uses " instead of '. So the result of your code is:
<script>
$(document).ready(function(){
$('.ddd').on('click', function() {
var $button = $(this);
var $input = $button.closest('.sp-quantity').find('input.quntity-input');
$input.val(function(i, value) {
return +value + (1 * +$button.data('multi'));
});
});
});
</script>
$button and $input will be substituted with the contents of the PHP variables of those names. I suspect that's not what you want - though I have done things like that at times myself. What I think you want is:
<script>
$(document).ready(function(){
$('.ddd').on('click', function() {
var button = $(this);
var input = button.closest('.sp-quantity').find('input.quntity-input');
input.val(function(i, value) {
return +value + (1 * + button.data('multi'));
});
});
});
</script>
Two other suggestions:
1 - If you have absolutely no PHP values within a bunch of Javascript (or plain HTML) echo lines, you can exit out of PHP code mode by using ?> and not use echo and avoid any issues of string substitution.
2 - Personally, I prefer using {$string} for my variables inside strings as it makes the substitution more obvious and sometimes less ambiguous.

Insert form data into sqlite3 query without php in TideSDK

I have been searching for hours and it is probably just me being a novice but I am having a very hard time figuring out how to dynamically enter text into a sqlite3 query as they do not accept variables (or so I believe).
Here is what I am attempting to do:
A user can currently view recipes in my TideSDK app - the content of the recipe is generated from a file called recipes.db
This code loads an individual recipe into the main screen:
function doMainChange70() {
var db = Ti.Database.openFile(Ti.Filesystem.getFile(Ti.Filesystem.getApplicationDataDirectory(), 'recipes.db'));
var rows = db.execute("SELECT * FROM recipe WHERE number = '70'");
while (rows.isValidRow()) {
$('#foodFoto').empty();
$('#titleArea').empty();
$('#servings').empty();
$('#tagline').empty();
$('#ingredients').empty();
$('#directions').empty();
$('#nutrition').empty();
$('#foodFoto').append("<img src='foodPics/r" + rows.fieldByName('number') + ".jpg' />");
$('#titleArea').append("<p>" + rows.fieldByName('title') + '</p>');
$('#servings').append("<p>" + rows.fieldByName('servings') + '</p>');
$('#tagline').append("<p>" + rows.fieldByName('tagline') + '</p>');
//$('#ingredients').
$('#directions').append("<p>" + rows.fieldByName('directions') + '</p>');
$('#nutrition').append("<p>" + rows.fieldByName('nutrition') + '</p>');
$('#editBtn').remove();
$('#mainBtns').append("<a href='#' id='editBtn'" + 'onclick=' + 'editRecipe' + rows.fieldByName('number') + "()><img src='RecipeButton5.png' /></a>");
rows.next();
rows.close();
db.close();
return false;
}
}
I would now like the user to be able to edit the recipe. Currently when the edit button is clicked all of the fields of the recipe change to input tags and the user can edit:
function editRecipe70() {
$('#editBtn').removeAttr('onclick');
var db = Ti.Database.openFile(Ti.Filesystem.getFile(Ti.Filesystem.getApplicationDataDirectory(), 'recipes.db'));
var rows = db.execute("SELECT * FROM recipe WHERE number = '70'");
while (rows.isValidRow()) {
$('#editBtn').html("<img src='saveRecipeButton.png' />");
$('#formContainer').empty();
$('#formContainer').append("<form id='sendEdit'><textarea type='text' name='title' id='title'>" + rows.fieldByName('title') + "</textarea><br>" + "<textarea type='text' name='servings'>" + rows.fieldByName('servings') + "</textarea><br>" + "<textarea type='text' name='tagline'>" + rows.fieldByName('tagline') + "</textarea><br>" + "<textarea type='text' name='directions'>" + rows.fieldByName('directions') + "</textarea><br>" + "<textarea type='text' name='nutrition'>" + rows.fieldByName('nutrition') + "</textarea><br>" + "<input type='submit'></form>");
}
My problem is that at this point I can't figure out a way to capture what the user has placed in the input fields (or more accurately textareas) and place it into the sqlite3 query string.
I am able to query the db in js with something like this:
UPDATE recipeTable SET title='best recipe ever' WHERE number='70';
But nothing like this (which is what I need):
UPDATE recipeTable SET title = '[formValueForTitle]' WHERE number = '70';
Hopefully I am making sense, I do apologize it is my first question. I have looked at many posts here on the site and the immediate solution would seem to be preprocessing the form values using php but I have read the php module in TideSDK doesn't have sqlite3 support right now and I have been unable to bring the processed code back into the index.html to run in js.
So long and short, I would like to figure out a way to let users edit recipes and I am totally stuck. Any direction would be much appreciated!
Thank You
This is how I'd do it:
var inputfromform = 'I got this back from the form';
var number = 7;
db = Ti.Database.open(dbname); // or openFile etc
db.execute("BEGIN IMMEDIATE TRANSACTION;");
db.execute("UPDATE recipeTable SET title = ? WHERE number = ?;", inputfromform, number);
db.execute("COMMIT TRANSACTION;");
db.close();
Hope this helps

How can I use input Box ID from PHP to JavaScript?

My JavaScript function works fine, but I have problems getting different ids from the PHP input box.
JavaScript
window.onload = function()
{
new JsDatePick({
useMode:2,
target:"inputField1", //HERE I WOULD LIKE TO PASS DIFFERENT ID ex. "inputField1"+ "i"
dateFormat:"%Y-%M-%d",
yearsRange:[1978,2120],
limitToToday:false,
cellColorScheme:"beige",
imgPath:"main/img/",
weekStartDay:1
});
My PHP input box for loop
<div class = "start_date" >
<strong><label for="start_date">Start Date</label></strong>
<br/><br/>
<?php
for($k=1;$k<=$textboxindex;$k++)
{
echo "<input type=\"text\" class='textboxsize' id= \"inputField1\" name=\"start_date[]\" value=\"$start_date\" />";
echo "<br/>";
}
?>
</div>
It works fine, but I would like to have different ID names to use in the JavaScript function. Any ideas?
This doesn't work...
echo "<input type=\"text\" class='textboxsize' id= \"inputField+$k\" name=\"start_date[]\" value=\"$start_date\" />";
Any help will be appreciated.
It's most likely with JsDatePick widget. Its target parameter takes a single ID of an element, therefore you'd have to wrap the JS code in a loop and initiate a separate instance of the widget for each field ID.
Assuming your input field indexing starts with 1:
window.onload = function()
{
var i = <?=$totalNumberOfInputs;?>
for(j=1;j<=i;j++) {
new JsDatePick({
useMode:2,
target:"inputField" + j, //HERE I WOULD LIKE TO PASS DIFFERENT ID ex. "inputField1" + j
dateFormat:"%Y-%M-%d",
yearsRange:[1978,2120],
limitToToday:false,
cellColorScheme:"beige",
imgPath:"main/img/",
weekStartDay:1
});
}
}
You don't need to put the + sign to concatenate strings within double quotes (it's dot, by the way).
Change:
id= \"inputField+$k\" name=...
To:
id=\"inputfield$k\" name=...
What is screwing it up is the "+" sign. PHP uses "." to concatenate strings. ECHO out $k properly and you shouldn't have any trouble
//this is doesn't work
echo "<input type=\"text\" class='textboxsize' id= \"inputField$k\" name=\"start_date[]\" value=\"$start_date\" />";
just remove that + sign.

Strange POST data junk being returned

I'm writing a fairly basic commenting function for a site using post method to pass input values to a php file that performs the relevant mysql query.
The $.ajax part is as follows:
// AJAX URL ENCODING
$("#add").click(function() {
// POST COMMENT FORM VALUES
var ajaxOpts = {
type: "post",
url: "includes/addComment.php",
data: "&author=" + $("#author").find("input").val() + "&email=" + $("#email").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val() + "&parent=<?php echo $vid_id; ?>",
success: function(data) {
// IMMEDIATE DISPLAY
// Not relevant to this problem.
// CLEAR TEXTAREA FOR NEXT COMMENT
$("textarea").val('');
}
};
$.ajax(ajaxOpts);
});
This is passed through to addcomment.php:
require('connection.php');
//get POST data
$name = mysql_real_escape_string($_POST["author"]);
$email = strtolower(md5(trim(mysql_real_escape_string($_POST["email"]))));
$comment = mysql_real_escape_string($_POST["comment"]);
$time = Date ('c');
$parent = trim(mysql_real_escape_string($_POST["parent"]));
//add new comment to database
mysql_query("INSERT INTO comments VALUES(' $name ',' $email ',' $comment ', ' $time ', ' $parent ')");
Everything works fine except that the mysql_query doesn't end up inserting any values into my database. After a bit of digging I found this:
So i'm assuming my query isn't going ahead because the ' : ' bit of junk(?) data is throwing everything out?
I'm trying to figure out where this errant ' : ' has come from, anyone have any ideas?
P.S - Apologies for the length of this question, I've tried to narrow down possible culprits as much as I can.
You dont have to do that URI encoding yourself. Read the documentation of jquery, the 'data' to be sent could be a map/json.
http://api.jquery.com/jQuery.post/
change
data: "&author=" + $("#author").find("input").val() + "&email=" + $("#email").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val() + "&parent=<?php echo $vid_id; ?>"
into
{ author: 'something',email:'test' }
or more professionally
$("#testform").serialize() //here #("#testform") stands for a '<form>' tag
And try not to complicate the problem, start with some simple functions, use more echo() and alert() to debug.
what happens if you remove the & from the front of &author?
normally the first data field doesn't have an &
data: "&author="
also as others have mentioned this would be a welcome addition
or die (mysql_error())
and its usually good practice to name your database columns on the insert
otherwise you risk breaking the insert statement if you ever alter the table structure
insert into (colname1, colname2) values ('value1', 'value2')
you can print_r($_POST) to see if the colon is really there.
secondly, while debugging it wouldn't hurt to throw an
or die (mysql_error())
at the end of your query.
Without those two, it's hard to debug.
2 things :
ajaxOpts variable is out of scope , you will have a error ( ajaxOpts is not defined)
In you example, you miss }); at the end , you should check your JS validate too before checking your php script is working. If you have a JS error, the ajax call will not be called.

Inserting a string inside of a javascript defined in PHP

I just found myself in an odd position trying to put a string inside of javascript, that is defined in a php. The code I'm going to post isn't that actual code, but its the situation I'm in.
$script = "
var someVar = \"<input type='text' onchange='callScript('problem here') />' \";
";
so as you see, I'm setting a javascript variable that has html elements in it. the html element has an onchange event that is set to call a function that takes a string as a parameter. How would i insert that parameter?
I think if you call addslashes() on the string before inserting it into the variable, you should be fine as to escaping any possible unsafe characters, so:
$script = "var someVar = \"<input type='text' onchange='callScript(\\\"".addslashes($problem_here)."\\\") />' \";
Use String.fromCharCode:
$script = "
var someVar = \"<input type='text' onchange='callScript(\" + String.fromCharCode(34) + \"problem here\" + String.fromCharCode(34) + \") />' \";
";
Generated JavaScript would be:
var someVar = "<input type='text' onchange='callScript(" + String.fromCharCode(34) + "problem here" + String.fromCharCode(34) + ") />' \";
which evaluates to someVar being the string
<input type='text' onchange='callScript("problem here") />'
Try
$script = "
var someVar = \"<input type='text' onchange='callScript(\"problem here\")' />\" ";
Ideally your JavaScript will be inside a view file, so you won't print it out with PHP, more the other way around:
var jsVar = <?php echo json _encode($phpstring); ?>;
Or the shorter:
var jsVar = <?=json_encode($phpstring)?>;
Json encode will make sure the string is printed in a way that it will be read properly by JS.
http://php.net/manual/en/function.json-encode.php
In general, stay away from addslashes. Do what Robin Winslow said (I'm new here so I guess I can't reply directly) and use json_encode.
However, you'd still need to html-escape your that string in JS. Look into something like jQuery's templating system if you're generating HTML with JS.

Categories