preventdefault() not working in IE8 - javascript

I'm working on a page that makes fairly heavy use of ajax. All the ajax forms appear to be working fine across browsers but one final step on the page is broken in IE8 and below.
Here is a demo page showing the problem: http://jolora.com/~fwm/
To reproduce the issue please fill in the final form (email name etc) - a list of markers will be shown on the map. The 'Request Appointment' button should fire an ajax function but instead it actually submits the form in IE7 and IE8 so it appears preventDefault isn't working.
Here's the relevant jQuery:
// Request appointment
$('#map').on('submit', 'form', function(event) {
event.preventDefault();
var solicitorID = $(this).attr('id');
solicitorRequest(solicitorID,applicationID);
});
function solicitorRequest(requestedSolicitor,currentApplication) {
$.ajax({
url: siteurl + 'wp-admin/admin-ajax.php',
data:{
'action':'do_ajax',
'fn':'request_solicitor',
'solicitor': requestedSolicitor,
'application': currentApplication
},
dataType: 'JSON',
success:function(data){
alert('Please check your email - this success function needs improving');
},
error: function(errorThrown){
alert('error');
//console.log(errorThrown);
}
});
}
The popups are built using Leaflet's bindPopup method http://leafletjs.com/reference.html#popup and here's the structure of the content I insert into the popup:
var popupContentBegin = '<form id="'
+ solicitor.id + '">'
+ '<h3>' + solicitor.name + '</h3>'
+ '<div class="contact-details">'
+ '<span class="addr">' + solicitor.address + '</span>';
var popupContentTel = '';
if(solicitor.telephone != false) {
popupContentTel = '<span class="tel">'
+ solicitor.telephone
+ '</span>';
}
var popupContentEnd = '</div>'
+ '<button type="submit">Request appointment</button>'
+ '</form>';
var popupContent = popupContentBegin + popupContentTel + popupContentEnd;
var marker = L.marker([lat, lng], {icon: solicitorIcon}).bindPopup(popupContent, popupOptions);
Any help would be greatly appreciated! Thanks.

Try changing your selector to:
$(document).on('submit', '#map form', function(event) {...
http://api.jquery.com/live/
EDIT: You need to call this function inside a ready function so that you can be sure the DOM was completely loaded:
$(function () {
// Put code here
});

Related

HTML submit text used for Javascript query with API

For a project, I am trying to make a HTML form that when a movie is searched it can access the Rotten Tomatoes API and queries the user's submitted text and returns with the movie.
The javascript* code from Rotten Tomatoes was provided
<script>
var apikey = "[apikey]";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
// construct the uri with our apikey
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
var query = "Gone With The Wind";
$(document).ready(function() {
// send off the query
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "jsonp",
success: searchCallback
});
});
// callback for when we get back the results
function searchCallback(data) {
$(document.body).append('Found ' + data.total + ' results for ' + query);
var movies = data.movies;
$.each(movies, function(index, movie) {
$(document.body).append('<h1>' + movie.title + '</h1>');
$(document.body).append('<img src="' + movie.posters.thumbnail + '" />');
});
}
</script>
I have an API key, my question is how would I be able to create a form that would change out the value for var query = "Gone With The Wind"; as the user submitted an input search with a HTML form such as this:
<input id="search">
<input type="submit" value="Submit">
Also would this be able to lead to another HTML page once searched?
complete rewrite ...
You should wrap the supplied (and modified) code in a function which you can then call through an event binding, like a submit event on your input form.
Below you will find a complete and working example of how you could do it. I replaced the given URL with a publicly available one from spotify. As a consequence I had to modify the callback function a little bit and also the dataType paramater in the $.ajax() argument object was changed to 'json' (instead of originally: 'jsonp').
At the end of the lookformovie() function you will find return false;. This prevents the submit event from actually happening, so the user stays on the same page.
function lookformovie(ev){ // ev is supplied by the triggered event
console.log('go, look!');
// the following WOULD be important, if this function was triggered
// by a click on a form element and you wanted to avoid the event to
// "bubble up" to higher element layers like the form itself.
// In this particular example it is superfluous
ev.stopPropagation();
var apikey = "[apikey]";
var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";
// construct the uri with our apikey
var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;
// --- start of spotify-fix ---
moviesSearchUrl="https://api.spotify.com/v1/search?type=track";
// --- end of spotify-fix -----
// the following gets the contents of your changed input field:
var query=$('#search').val();
$.ajax({
url: moviesSearchUrl + '&q=' + encodeURI(query),
dataType: "json", // spotify-fix, was: "jsonp"
success: searchCallback
});
return false; // this prevents the submit event from leaving or reloading the page!
}
// modified callback (spotify-fix!!):
function searchCallback(data){
console.log('callback here');
$('#out').html(data.tracks.items.map(
function(t){ return t.name;}).join('<br>\n'));
}
// original movie callback for Rotten Tomatoes:
function searchCallback_inactive(data) {var str='';
str+='Found ' + data.total + ' results.';
var movies = data.movies;
$.each(movies, function(index, movie) {
str+='<h1>' + movie.title + '</h1>';
str+='<img src="' + movie.posters.thumbnail + '" />';
});
$('#out').html(str);
}
$(function(){
$('form').on('submit',lookformovie);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="text" id="search" value="james brown">
<input type="submit" value="get tracks">
</form>
<div id="out"></div>
You might have noticed that I placed several console.log() statements at various places into the code. This helped me during debugging to see which part of the functionality actually worked, and where something got stuck. To see the output you need to have your developer console opened of course.
You can construct form, with input element named "q", then handle form submit event.
<form action="http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=API_KEY" method="get">
<input id="search" name="q">
<input type="submit" value="Submit">
</form>

How to use jQuery ajax in Google Chrome Extensions?

I have written a code for getting data from another server through JSONP call (based on jQuery) please look at the code below....
$("#submit").click(function() {
var state=$("#state").val();
var city=$("#city").val();
$.ajax({
type: "GET",
url: "http://www.dizainstore.com/chrome/info.php",
async: true,
data: "state="+ state+ "&city="+ city,
dataType: 'jsonp',
success: function(response) {
var centres=response.centres_info.centre;
var address=response.centres_info.address;
var val ;
var val1 ;
var und
$.each(centres, function(i,cent){
val += "<div class='box2-l'>" + cent + "</div><div class='box2-r'>" + address[i] + "</div>" ;
});
var new_val = "<div class='box1'><div class='box1-l'>Center List</div><div class='box1-r'>Address List</div>"+val+"</div>"
$(".result1").html(new_val);
}
});
return false;
});
It's working fine for me. but When i used in Google Chrome Extension, it's not working, error occurred :- we can't use jquery Ajax call, they suggest xmlhttprequest. But i dont know how to convert this code into XMLhttpRequest. So please suggest me.
Thanks
Since the return is JSONP, it appears dizainstore is using a RESTful API and expects you to use JSONP with script injection:
http://en.wikipedia.org/wiki/JSONP#Script_element_injection
Your code would instead look something like this:
function handleDizain(response)
{
var centres=response.centres_info.centre;
var address=response.centres_info.address;
var val ;
var val1 ;
var und
$.each(centres, function(i,cent){
val += "<div class='box2-l'>" + cent + "</div><div class='box2-r'>" + address[i] + "</div>" ;
});
var new_val = "<div class='box1'><div class='box1-l'>Center List</div><div class='box1-r'>Address List</div>"+val+"</div>"
$(".result1").html(new_val);
}
$("#submit").click(function() {
var state=$("#state").val();
var city=$("#city").val();
//Create a new script tag
var loader = document.createElement( "script" );
loader.setAttribute( "type", "text/javascript" );
//Set the source
loader.src = "http://www.dizainstore.com/chrome/info.php?state=" + state + "&city=" + city + "&callback=handleDizain";
//Add it to the body
document.body.appendChild( loader );
});
If you want to make a cross-origin call in a Chrome extension, you don't have to use JSONP. You can simply use the Chrome extension cross-origin permissions: http://developer.chrome.com/extensions/xhr.html
Regards,
Udi

jQuery append is executed when leaving the page aswell

I'm experiencing a really weird behaviour. I call a function when I change to a page (jQuery Mobile event "pagebeforeshow") like so:
$("#library").on("pagebeforeshow", function(event){
player.loadFiles();
});
The function I call looks like this:
Player.prototype.loadFiles = function(dir) {
dir = dir == undefined ? 'file://~' : dir;
if(dir.indexOf(data.lastDir) != 0){
console.log("fired");
$("li.item").remove();
$.ajax({
url: 'http://' + data.ip + ":" + data.port + '/requests/browse.xml',
data: 'uri=' + encodeURIComponent(dir),
dataType: "xml",
success: function (data, status, jqXHR) {
if(dir.indexOf(data.lastDir) != 0){
var html = "";
$(data).find("element").each(function(){
html += '<li class="item">' + $(this).attr('name') + "</li>";
});
$("#filelist").append(html);
$(".item").addClass("ui-li ui-li-static ui-btn-up-a ui-first-child ui-last-child")
}
},
error: function (jqXHR, status, error) {
alert("fail")
}
});
data.lastDir = dir;
}
}
Now it works fine if I visit the page for the first time. It appends the listitems to the ul #filelist and sets the variables right. Now when I leave the page it adds them again. The "fired" is not shown in the console though. If I visit the page again, they aren't added again, but if I leave it again they are. I can't figure out, why it's behaving like this and would be thankful for any tips!
stiller_leser

Extracting user playcount from Last.fm API using JSON

In a nutshell, I'd like to display the Last.fm user playcount figure on my site (see 'playcount' on http://www.last.fm/api/show/user.getInfo). I've tried the following, but confess I have no idea if I'm on the right lines here.
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getinfo&user=XXX&api_key=XXX&limit=5&format=json&callback=?", function(data) {
var html = '';
$.each(data.user.playcount, function(i, item) {
html += "<p>" + item.playcount + "</p>";
});
$('#count').append(html);
});
});
The inner foreach loop is unnecessary, user.getInfo returns only one user's information after all. The following should work:
$(document).ready(function() {
$.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getInfo&user=XXX&api_key=XXX&format=json", function(data) {
var html = "<p>" + data.user.playcount + "</p>";
$('#count').append(html);
});
});
I have also removed the limit and callback parameters from the URL for brevity.

How to get the value value of a button clicked Javascript or Jquery

I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}

Categories

Resources