Textbox 'this.value' stops JavaScript with single quotes - php

I cannot get single quotes to work in JavaScript this.value. Double quotes work fine. I tried to use escape() and it didn't work and I cannot think of a way to use PHP to fix this, so does anyone else have any ideas?
function editItemInCart(newValue,fieldName,itemNum,cnt) {
//alert(newValue);
if (count == cnt) {
count = 0;
jQuery.ajax({
type:"POST",
url: "editItem.html",
data: "newvalue=" + escape(newValue) + "&fieldname=" + fieldName + "&itemNum=" + itemNum,
})
document.getElementById('status' + itemNum).innerHTML = "SAVED";
jQuery("#status" + itemNum).show();
setTimeout("fade_out('"+itemNum+"')", 1000);
}
//alert(newValue + fieldName + itemNum);
}
if ($cart['title'] != "")
echo "<label>Title: </label> <input type=\"text\" onKeyUp=\"doEditItemInCart(this.value,'title',".$itemNum.")\" onChange=\"editItemInCart(this.value,'title',".$itemNum.")\" value=\"".htmlspecialchars($cart['title'])."\"><br />";
function doEditItemInCart(newValue,fieldName,itemNum) {
count++;
setTimeout("editItemInCart(escape('"+newValue+"'),'"+fieldName+"',"+itemNum+","+count+")",200);
}

try this
jQuery.ajax({type:"POST",
url: "editItem.html?newvalue=" + escape(newValue) + "&fieldname=" + fieldName + "&itemNum=" + itemNum,
})
it also appears that you are setting the status of saved regardless of the ajax response. i suggest added an ajax success function
http://api.jquery.com/jQuery.ajax/

Related

Ajax: Getting a Post Error when trying to use Relative Path

Struggling to get the relative path of an Ajax post request to pickup the php file. I'm not getting an error just nothing happens.
Browsed this site, but cannot find a previous answer on Ajax relative paths that I understand. Still a novice at this. Would really appreciate it, if someone could explain it in layman terms.
I'm trying to access the php file 'search/search.php' from the root file 'index.php' (this file contains the Ajax request). This worked when both files were in the same directory.
File structure below:
JQuery code snippet:
$(function() {
$('form').on("submit", function(e) {
e.preventDefault();
$('#error').text(""); // reset
var name = $.trim($("#search").val());
if (name.match(/[^a-zA-Z0-9 ]/g)) {
$('#error').text('Please enter letters and spaces only');
return false;
}
if (name === '') {
$('#error').text('Please enter some text');
return false;
}
if (name.length > 0 && name.length < 3) {
$('#error').text('Please enter more letters');
return false;
}
$.ajax({
url: 'search/search.php',
method: 'POST',
data: {
msg: name
},
dataType: 'json',
success: function(response) {
$(".content").html("")
$(".total").html("")
if(response){
var total = response.length;
$('.total') .append(total + " Results");
}
$.each(response, function() {
$.each($(this), function(i, item) {
var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' : '';
$('.content').append('<div class="post"><div class="post-text"> ' + item.MessageText + ' </div><div class="post-action"><input type="button" value="Like" id="like_' + item.ID + '_' + item.UserID + '" class="like" ' + mycss + ' /><span id="likes_' + item.ID + '_' + item.UserID + '">' + item.cntLikes + '</span></div></div>');
});
});
}
});
});
});
The leading forward slash simply means “begin at the document root”, which is where index.php lives. So /search/search.php should be correct. If the server is unable to find the file, it stands to reason that there must be some url rewriting happening.
You can test by simply pointing your browser to http://localhost:8000/search/search.php. If you get a 404, you know it has nothing to do with ajax

TypeError: $ is undefined : $.widget("ui.combobox", {

I use jquery in comboboxes, and I'm not abele to get the comboboxes in the interface to be displayed. The error in firebug is the following :
TypeError: $ is undefined : $.widget("ui.combobox", {
I'm using the following file jquery.ui.combobox.js:
Code :
$.widget("ui.combobox", {
options: {
openDialogButtonText: "+",
dialogHeaderText: "Add option",
saveButtonImgUrl: null,
closeButtontext: "Ok"
},
_create: function() {
var selectBox = $(this.element),
id = selectBox.attr("id"),
self = this;
selectBox.addClass("ui-combobox");
// create HTML to inject in the DOM
this.addHtml(id, selectBox);
// turn dialog html into a JQuery UI dialog component
this.addDialog(id);
// #todo set proper button height (roughly equal to select height)
$("#" + id + "-button-opendialog").bind("click", function() {
$("#" + id + "-editor-dialog").dialog("open");
}).button();
$("#" + id + "-button-save").bind("click", function() {
self.addOption(id, selectBox);
}).button();
this._init();
return this;
},
addHtml: function(id, selectBox) {
var imgHtml = "";
if (this.options.saveButtonImgUrl != null) {
imgHtml = '<img src="' + this.options.saveButtonImgUrl + '" alt="opslaan" />';
}
$(' <button id="' + id + '-button-opendialog">' +
this.options.openDialogButtonText +
'</button>' +
'<div id="' + id + '-editor-dialog" class="ui-combobox-editor">' +
'<input id="' + id + '-newitem" type="text" /> ' +
' <button id="' + id + '-button-save">' +
imgHtml + ' Opslaan' +
' </button>' +
'</div>').insertAfter(selectBox);
},
addDialog: function(id) {
var options = this.options;
$("#" + id + "-editor-dialog").dialog( {
autoOpen: false,
modal: true,
overlay: {
opacity:0.5,
background:"black"
},
buttons: {
// #todo make button text configurable
"Ok": function() {
$("#" + id + "-editor-dialog").dialog("close");
return;
}
},
title: options.dialogHeaderText,
hide: 'fold'
});
},
addOption: function(id, selectBox) {
var newItem = $("#" + id + "-newitem");
// #todo do not allow duplicates
if (newItem !== null && $(newItem).val().length > 0) {
// #todo iterate over options and get the highest int value
//var newValue = selectBox.children("option").length + 1;
var highestInt = 0;
selectBox.children("option").each(function(i, n) {
var cInt = parseInt($(n).val());
if (cInt > highestInt) {
highestInt = cInt;
}
});
var newValue = highestInt + 1;
var newLabel = $(newItem).val();
selectBox.prepend("<option value='" + newValue + "' selected='selected'>" + newLabel + "</option>");
this._trigger("addoption", {}, newValue);
// cleanup and close dialog
$(newItem).val("");
$("#" + id + "-editor-dialog").dialog("close");
} else {
this._trigger("addoptionerror", {}, "You are required to supply a text");
}
},
_init: function() {
// called each time .statusbar(etc.) is called
},
destroy: function() {
$.Widget.prototype.destroy.apply(this, arguments); // default destroy
// $(".ui-combobox-button").remove();
// $(".ui-combobox-editor").remove();
}
});
Can you please help me?
The message "$ is undefined" means that the function called "$" is not defined anywhere on your page. Thus, when this code is executed, it does not know what to do when this line is encountered.
The $ function is defined by jQuery. Therefore, the message is indicating that it hasn't loaded the jQuery library by the time your code is executed. This could be for a number of things
You haven't included the full jQuery library on your page. This may be because you have forgotten to include it or you have only included some extension to jQuery such as jQuery.UI.
If you are unsure, try adding the following line to the top of your head element in your HTML. Make sure you haven't put any JS before this line:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
You have included jQuery but it is failing to load. This may be because the link you are using is incorrect. Double check by using the Net Panel in Firebug.
jQuery is included on your page, but you have included your own JS first. This won't work because the $ function won't get defined until jQuery is loaded, but your code will try and execute first. Check the order in which you are including your JS and make sure that jQuery is first.

Select boxes auto populated by JSON sometimes need a refresh before displaying

I have a JSON file that is being used to autopopulate some select boxes. Every now and then (I can't recreate the fault, it appears to be random) the items in the drop down do not display until I refresh the page.
I've checked the console and log etc, the file is loading fine, no errors are appearing and I'm a little at a loss.
Any ideas?
Example of JSON and the script that reads it below.
Thanks.
"radAbsorbed" : [
{
"value" : "rad",
"name" : "Rad(rd)"
},
{
"value" : "millirad",
"name" : "Millirad(mrd)"
}]
and the script:
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
</script>
EDIT:
Updated script.
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
EDIT: Thanks everyone for their help, it seems to be working fine and looked like an amateur mistake on my part.
I think the problem is that your script is sometimes running before the document is ready.
Try wrapping your code in a document ready function:
$(function() {
$.getJSON(...)
// ...
});
This will make it so that the code doesn't execute before the elements it's affecting are created. For instance, if your code executes before the element with the ID from gets created, then $('#from') will not match any elements, and it won't work.
Wrapping it in a document ready function will make sure that your code waits until the elements have been created before executing.
Alternatively, you could move your <script> tag out of the head and place it right after the #from element in your HTML. This might help it load slightly faster.

No results obtained with JQuery $.getJSON in the PhoneGap environment

Here is my funciton:
function getEmployeeList() {
alert("hello world3!");
$.getJSON(serviceURL + 'getemployees.php', function(data) {
alert("hello world4!");
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '"/>' +
'<h4>' + employee.firstName + ' ' + employee.lastName + '</h4>' +
'<p>' + employee.title + '</p>' +
'<span class="ui-li-count">' + employee.reportCount + '</span></a></li>');
});
$('#employeeList').listview('refresh');
});
}
When the page is ready, it will run this function, however, nothing is appended.
I have tested, all php can return correct format. What wrongs?? Please please help me...
You need to add the external host (in my case was mysite.localhost) in PhoneGap.plist under the "ExternalHosts" key.
I presume serviceURL is not on the same domain.
In that case you add callback=? in the end, and jQuery does some magic:
$.getJSON(serviceURL + 'getemployees.php?callback=?', function(data) {
...
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
jQuery API

Edit a comment - javascript, php working together

Hey all, I am facing a rather serious security error. Let me first outline my code.
<li class="comment">
<form action="" method="POST" name="edit-form" class="edit-area">
<textarea style="width: 100%; height: 150px;"><?php echo $response->comment; ?></textarea>
</form>
<div class="comment-area" style="padding-top: 2px"><?php echo (parseResponse($response->comment)); ?></div>
<p class="ranking">
<?php if ($response->user_id == $user_id) : ?>
Edit • Delete
<?php else : ?>
Like (<?php echo $response->likes; ?>) • Dislike (<?php echo $response->dislikes; ?>)
<?php endif; ?>
</p>
</li>
is what I got in my body, and here's the relevant JS
$('.editting').bind('click', function(event) {
var num = $(this).data('edit');
var user = $(this).data('user');
if ($(this).hasClass('done')) {
var newComment = $('#comment-' + num + ' .edit-area textarea').val();
var dataString = 'newComment='+ newComment + '&num=' + num;
if(newComment == '')
{
alert('Comment Cannot Be Empty!');
}
else
{
$.ajax({
type: "POST",
url: "edit.php",
data: dataString,
success: function(){}
});
$('#comment-' + num + ' .edit-area').slideDown('slow', function() {
$('#comment-' + num + ' .edit-area').addClass('invisible');
});
$('#comment-' + num + ' .comment-area').slideUp('slow', function() {
$('#comment-' + num + ' .comment-area').removeClass('invisible');
});
$(this).removeClass('done');
$(this).html('Edit');
}
}
else {
$('#comment-' + num + ' .comment-area').slideDown('slow', function() {
$('#comment-' + num + ' .comment-area').addClass('invisible');
});
$('#comment-' + num + ' .edit-area').slideUp('slow', function() {
$('#comment-' + num + ' .edit-area').removeClass('invisible');
});
$(this).html('Done');
$(this).addClass('done');
}
return false;
});
which works fine, but i'm having an issue. If the user finds a comment (not by them) and uses a plugin like firebug, they can replace the response->short with another, and edit ANY comment. Of course, within edit.php, I could check the short against the response table and see if the user checks out, but i'd like to find a way to not show the text area unless that response is for-sure by that user.
Is this possible?
Thanks in advance,
Will
Is this possible?
Sure...but it'll do nothing to stop the user/fix your security hole. To fix this check server-side, always double-check anything that should be secure server-side, never trust your input. The users trying to do something malicious won't be stopped by anything in JavaScript...sending data to your server that they shouldn't is exactly what they'll do first.
Like Nick said; never ever trust a JavaScript test!
It will/might work for "regular users", but when it comes down to avoiding hacks, you might as well ask the hacker to click a button to "prove" his input is valid!
Your validator script is running on someone else's computer, so he/she will be able to manipulate it (or even turn it of using NoScript etc. )

Categories