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

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

Related

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.

Refreshing the page after completing uploads in jQuery Multi file Uploader

I'm using jQuery Multifile uploader (https://github.com/blueimp/jQuery-File-Upload) with PHP
and I want to refresh the uploads page once all files got uploaded, I'm using basic plus UI, please tell me if is there any easy way to achieve it
Use the done and fail events along with some counters. Found these events in the options documentation.
var fileCount = 0, fails = 0, successes = 0;
$('#fileupload').fileupload({
url: 'server/php/'
}).bind('fileuploaddone', function(e, data) {
fileCount++;
successes++;
console.log('fileuploaddone');
if (fileCount === data.getNumberOfFiles()) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
location.reload();
}
}).bind('fileuploadfail', function(e, data) {
fileCount++;
fails++;
console.log('fileuploadfail');
if (fileCount === data.getNumberOfFiles()) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
location.reload();
}
});
You can use the stop event. It is equivalent to the global ajaxStop event (but for file upload requests only).
stop: function(e){
location.reload();
}
I have used this code and so far it works well.
$('#fileupload').bind('fileuploadstop', function (e) {
console.log('Uploads finished');
location.reload(); // refresh page
});
I used ryan's code, but there was a problem. The value of data.getNumberOfFiles() was decreasing as the files were uploaded while fileCount was increasing, so my upload script got interrupted at the middle of my upload where data.getNumberOfFiles() was equal to fileCount.
Here is how i tweaked ryan's script and now it's working like a charm:
var fileCount = 0, fails = 0, successes = 0;
var _totalCountOfFilesToUpload = -1;
$('#fileupload').bind('fileuploaddone', function (e, data) {
if (_totalCountOfFilesToUpload < 0) {
_totalCountOfFilesToUpload = data.getNumberOfFiles();
}
fileCount++;
successes++;
if (fileCount === _totalCountOfFilesToUpload) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
location.reload();
}
}).bind('fileuploadfail', function(e, data) {
fileCount++;
fails++;
if (fileCount === _totalCountOfFilesToUpload) {
console.log('all done, successes: ' + successes + ', fails: ' + fails);
// refresh page
//location.reload();
}
});
I hope this will help other people as well as! :)

Dynamically load image with different GET parameters

I'm trying to load an image (created with PHP) with jQuery and passing a few variables with it (for example: picture.php?user=1&type=2&color=64). That's the easy part.
The hard part is that I've a dropdown which enables me to select background (the type parameter) and I'll have an input for example to select a color.
Here're the problems I'm facing:
If a dropdown/input hasn't been touched, I want to leave it out of the URL.
If a dropdown/input has been touched, I want to include it in the url. (This won't work by just adding a variable "&type=2" to the pre-existing string as if I touch the dropdown/input several times they'll stack (&type=2&type=2&type=3)).
When adding a variable ("&type=2" - see the code below) to the pre-existing URL, the &-sign disappears (it becomes like this: "signature.php?user=1type=2").
Here's the code for the jQuery:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url += "&type="+$(this).val();
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
Here's the code where I load the image:
<div id="loadsignature">
<div id="loadingsignature" style="display: block;"><img src="img/loading-black.gif" alt="Loading.."></div>
</div>
I don't know how more further I could explain my problem. If you have any doubts or need more code, please let me know.
Thank you for your help!
EDIT:
Here's the current code:
<script>
var url = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
function LoadSignature()
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(url, function() {
$("#loadingsignature").css("display", "none");
});
}
function updateQueryStringParameter(uri, key, value)
{
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re))
{
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
}
else
{
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
</script>
EDIT2:
Here's the code for signatureload.php
<?php
$url = "signature.php?";
$count = 0;
foreach($_GET as $key => $value)
{
if($count > 0) $url .= "&";
$url .= "{$key}={$value}";
}
echo "<img src='{$url}'></img>";
?>
If I understood your question correctly, it comes down to finding a proper way of modifying GET parameters of the current URI using JavaScript/jQuery, right? As all the problems you point out come from changing the type parameter's value.
This is not trivial as it may seem though, there are even JavaScript plugins for this job. You could use a function like this and in your signature_type change event listener,
function updateQueryStringParameter(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i"),
separator = uri.indexOf('?') !== -1 ? "&" : "?",
returnUri = '';
if (uri.match(re)) {
returnUri = uri.replace(re, '$1' + key + "=" + value + '$2');
} else {
returnUri = uri + separator + key + "=" + value;
}
return returnUri;
}
$('#signature_type').change(function () {
// Update the type param using said function
url = updateQueryStringParameter(url, 'type', $(this).val());
LoadSignature();
});
Here is a variant where all the data is keept in a separate javascript array
<script>
var baseurl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
var urlparams = {};
$(document).ready(function() {
window.setTimeout(LoadSignature, 1500);
});
$("#signature_type").change(function() {
urlparams['type'] = $(this).val();
LoadSignature();
});
function LoadSignature()
{
var gurl = baseurl; // there is always a ? so don't care about that.
for (key in urlparams) {
gurl += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(urlparams[key]);
}
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(gurl, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>
With this color or any other parameter could be added with urlparams['color'] = $(this).val();
Why don't you try storing your selected value in a variable, and then using AJAX post data and load image. That way you ensure there is only one variable, not repeating ones. Here's example
var type= 'default_value';
$("#signature_type").change(function() {
type = $(this).val();
});
then using ajax call it like this (you could do this in your "change" event function):
$.ajax({
type: 'GET',
url: 'signatureload.php',
data: {
user: <?php echo $_SESSION['sess_id']; ?>,
type: type,
... put other variables here ...
},
success: function(answer){
//load image to div here
}
});
Maybe something like this:
<script>
var baseUrl = "signatureload.php?user=<?php echo $_SESSION['sess_id']; ?>";
$(document).ready(function() {
window.setTimeout(function(){
LoadSignature(baseUrl);
}, 1500);
});
$("#signature_type").change(function() {
var urlWithSelectedType = baseUrl + "&type="+$(this).val();
LoadSignature(urlWithSelectedType);
});
function LoadSignature(urlToLoad)
{
$("#loadingsignature").css("display", "block");
$('#loadsignature').delay(4750).load(urlToLoad, function() {
$("#loadingsignature").css("display", "none");
});
}
</script>

Tabbed jQuery search results

I have a Google Instant style jQuery search script that queries a PHP file then parses the results into an HTML div. It uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/.
My problem is, when the user searches for something and then selects a new search type (clicks on a tab) they have to go to the text box and press enter to submit their query again. How can I make it so when a search is active and a tab is clicked that it loads the results straight away instead?
I hope you can understand what I'm trying to describe. JSfiddle: http://jsfiddle.net/phWSR/
My current jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
});
$('#type_search').click();
$('input').keyup(function () {
query = $(this).val();
url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search Script';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
});
My current HTML code is:
<div id='nav'>
<a id='type_search'>All</a>
<a id='type_images'>Images</a>
<a id='type_videos'>Videos</a>
<a id='type_news'>News</a>
<a id='type_social'>Social</a>
</div>
<input type='text' autocomplete='off'>
<div id='results'></div>
You could isolate the code for the ajax call (currently in $('input').keyup()) in a separate function, and bind it to both $('input').keyup() and $('#nav a').click().

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