This is making me crazy:
I can successfully pass arguments into this function, and display them in an alert. I can also populate the div by id, if I define the values in the function.
function getStuff( req, elementid ) {
//var req = 'slider';
//var elementid = '#slider';
//var req = 'thumbnails';
//var elementid = '#thumbnails';
$.ajax({
async: false,
url: '/update',
contentType: 'text/html',
data: { putski: req },
type: 'GET',
dataType: "html",
success: function(stuff) {
$( elementid ).html(stuff);
alert(req+elementid)
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) {
return false;
}
});
};
$(document).ready( getStuff( 'thumbnails', '#thumbnails' ) ); // alert shows thumbnails#thumbnails but div does not populate.
The following variation is populating and should rule out issues other than the one I've described.
function getStuff( req, elementid ) {
var req = 'slider'; //uncomment these definitions and the div populates
var elementid = '#slider';
//var req = 'thumbnails';
//var elementid = '#thumbnails';
$.ajax({
async: false,
url: '/update',
contentType: 'text/html',
data: { putski: req },
type: 'GET',
dataType: "html",
success: function(stuff) {
$( elementid ).html(stuff);
alert(req+elementid)
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) {
return false;
}
});
};
$(document).ready( getStuff ); // populated using the values defined at the top.
You are comparing apples to oranges
In the second version, you can try the following:
var req = 'thumbnails';
var elementid = '#thumbnails';
If this doesn't work then you know that either the server code is not dealing with the "thumbnails" parameter correctly, or the element id "#thumbnails" is not defined. I doubt that the problem is with passing the parameters vs. setting them in the function.
Okay, I fixed it but I have to admit, I don't really understand the behavior. I commented out "async: false," and it started working with the thumbnails. I added that line in the first place because the slider doesn't work without it. :p Maybe someone could shed some light on this?
Related
I am displaying Two or Three DataTables and each of these Tables are Independent of each other and are placed on their own parent container and have their own Ajax Operations. Now my concern is if any of the DataTable's Ajax Operations returns the Failure Response or (Success operations with Failed Data inside it), then all the Tables must be hidden and the Error Message Should display in the Page. How can I do this?
You can use about for cancel XMLHttpRequest are pending status
example
<!-- begin snippet: js hide: false console: true babel: false -->
var requestTable1 = $.ajax({
type: 'POST',
url: 'someurl1',
success: function (result) { }
});
var requestTable2 = $.ajax({
type: 'POST',
url: 'someurl2',
success: function (result) { }
});
var requestTable3 = $.ajax({
type: 'POST',
url: 'someurl3',
success: function (result) { }
});
$( document ).ajaxError(function( event, jqxhr, settings, thrownError ) {
if ( settings.url == "someurl1" ) {
requestTable2.about();// and alert msg
requestTable3.about();
}
else if ( settings.url == "someurl2" ) {
requestTable1.about();// and alert msg
requestTable3.about();
}
else if ( settings.url == "someurl3" ) {
requestTable1.about();// and alert msg
requestTable2.about();
}
});
I think it might help you.
I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help
( function( $ ) {
jQuery.support.cors = true;
function CleanQueryString( query )
{
return encodeURI( query );
};
$.fn.GoogleSearchResult = function( options ) {
var settings = $.extend( {
query: null,
googleApiKey: "something",
googleUrl: "https://www.googleapis.com/shopping/search/v1/public/",
concatUrl: "",
country: "UK",
cleanQuery: ""
}, options);
alert("im here"); // THIS ALERTS
return this.each( function() {
alert("q:" +settings.query); // THIS DOES NOT?
if( settings.query )
{
alert(":" + settings.query);
settings.cleanQuery = CleanQueryString( settings.query );
$.ajax({
dataType: "json",
async: false,
url: settings.googleUrl,
data: {
key: settings.googleApiKey,
country: settings.country,
q: settings.cleanQuery,
alt: 'json'
},
success: function( data ) {
alert( data );
return data;
},
error: function(xhr, status, error) {
alert("error " + status + " " + error);
}
});
}
} );
};
} )( jQuery );
My code is bumming out before return this.each jquery plugin, any ideas why?
I am calling it with:
$.fn.GoogleSearchResult( {
query: "the apple ipad"
} );
The .each() function iterates over the contents of the jQuery object that's it's context. In your case, you've got no context object at all, so .each() will do nothing.
Given the nature of your function, I don't see why it makes sense for it to be a jQuery function at all. You could hang it directly off the $ object I guess, and if you do that then you don't need .each() at all.
It's the way you call it. You need to call it on a selector and not on fn.
I'm trying to use autocomplete for getting movie suggestion from rottentomatoes in JSON format.
But the code below doesn't show any suggestion.
<script>
var apikey = "5xq9w7z2mp7a6cnchkfy52yd";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = "Rocky";
$(document).ready(function() {
$("#sample").autocomplete({
source: function( request, response ) {
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: function(data) {
var movies = data.movies;
response(function(movies) {
return {
label: movies.title,
value: movies.title
}
}));
}
});
}
});
});
</script>
For the complete page source: https://gist.github.com/2018447
I also need to include the movie thumbnail in the suggestion list. Could anyone help me on this?
You had a syntax error (extra )) and were missing the call to iterate over the movies array (typically using $.map()).
This is what it should look like (update: includes poster thumbnails)
$("#sample").autocomplete({
source: function( request, response ) {
$.ajax("http://api.rottentomatoes.com/api/public/v1.0/movies.json", {
data: {
apikey: apikey,
q: request.term
},
dataType: "jsonp",
success: function(data) {
response($.map(data.movies, function(movie) {
return {
label: movie.title,
value: movie.title,
thumb: movie.posters.thumbnail
}
}));
}
});
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
var img = $("<img>").attr("src", item.thumb);
var link = $("<a>").text(item.label).prepend(img);
return $("<li>")
.data( "item.autocomplete", item )
.append(link)
.appendTo(ul);
};
Working example here - http://jsfiddle.net/df7tp/6/
For some reason, Firefox is throwing "function not defined" errors at this piece of JS:
$(function() { // on document ready
function updateAlerts() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'checkAlerts'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
// Update the DOM to show the new alerts!
if (response.friendRequests > 0) {
// update the number in the DOM and make sure it is visible...
$('#notifications').show().text(response.friendRequests);
}
else {
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$('#notifications').show().text(ablanknum);
}
}
});
}
function friendRequestAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendFriendAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theFRAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
});
}
function messageAlert() {
$.ajax({
url : "/check.php",
type : "POST",
data : {
method : 'sendMessageAlert'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = $.parseJSON(data);
if (response.theAlert !== '0') {
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
});
}
});
I checked through my code and nothing seems to be wrong.
There is no reason to wrap your 3 functions in the document ready wrapper--nothing inside those functions (which may rely on the doc being ready) is executed until they are called. Further, by wrapping them in doc ready, you're forcing them into the scope of that anon function and they cannot be used from outside of it.
Unrelated, you should set your dataType to 'json' on the $.ajax calls and stop making manual calls to $.parseJSON.
New code:
function updateAlerts()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'checkAlerts'
},
dataType: 'json',
success: function( response )
{
// Update the DOM to show the new alerts!
if( response.friendRequests > 0 )
{
// update the number in the DOM and make sure it is visible...
$( '#notifications' ).show().text( response.friendRequests );
}
else
{
// Hide the number, since there are no pending friend requests or messages
var ablanknum = '0';
$( '#notifications' ).show().text( ablanknum );
}
}
} );
}
function friendRequestAlert()
{
$.ajax( {
url: '/check.php',
type: 'POST',
data: {
method: 'sendFriendAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theFRAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theFRAlert + '');
}
}
} );
}
function messageAlert()
{
$.ajax( {
url: '/check.php',
type : 'POST',
data: {
method : 'sendMessageAlert'
},
dataType: 'json',
success: function( response )
{
if( response.theAlert !== '0' )
{
// Display our fancy Javascript notification.
$.jgrowl('' + response.theAlert + '');
$('#therearemessages').show().text(response.theAlert);
}
}
} );
}
Scope in javascript is function based.
Since you define the 3 functions inside a function that is run on DOMready and then goes out of scope, so does the funcitons.
In other words: the 3 functions only exist inside the DOmready function, and you cannot use them from anywhere else outside that function.