I am new to jquery and coding in general. This is what I am trying to do:
When a link is clicked, expand the #country_slide div
Show "loading" text
If ajax is successful, put the contents of an html file into the div
Otherwise alert an error and close the div
This is the code I now have:
http://jsfiddle.net/spadez/n9nVs/5/
window.onload = function () {
var a = document.getElementById("country_link");
a.onclick = function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").val('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
}
When the link is clicked, I never see the loading text in the box. Please can someone tell me where I have gone wrong here? Also if anyone can offer any words of advice about my first jquery script I would really appreciate it.
Your anchor's id is country, not country_link. So:
var a = document.getElementById("country");
or just use jQuery's id selector:
var a = $("#country");
or even better directly chain:
$(function() {
$('#country').click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
});
Notice that I have used the $(document).ready function instead of window.onload. Also I have replaced the onclick event subscription with jQuery's click function. If you are using jQuery it would be better to take full advantage of it.
Working jsFiddle Demo
You don't have any country_link element in your page.
Instead of using window.onload you can use DOM ready.
Attach click handler by jQuery with .on() method.
The .val() method is for <input />. For other elements, use .html() instead.
// DOM ready instead of window.onload
$(function () {
// attach click handler by jQuery instead of onclick
$('#country').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
// val() method is for <input />
// use html() instead
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});
References:
.html() - jQuery API Documentation
.on() - jQuery API Documentation
.val() - jQuery API Documentation
jQuery( callback ) - jQuery API Documentation
On the fiddle you have
<a href="#" id="country">
Where it should be:
<a href="#" id="country_link">
or change the JS to be
var a = document.getElementById("country");
Because there is no element with an ID country_link
document.getElementById() returns null if the element isn't found
document.getElementById('country').onclick = ...; //should work
In JavaScript, null is a special primitive and you cannot add properties to primitive types.
You have to add an element with id=country_link and the this code will work as NOX said. I have tried that in jsfiddle. try it using
$("#country").click(function(){
// your code goes here
})
that will works.
document.getElementById("country_link"); shall be replaced by document.getElementById("country"); as "country_link" is not the id of any <a> tag in the mark up.
If you are using jQuery library you may handle event like-
$(document).on("click","a",function(){
//ajax stuff
});
Updated Your jsfiddle Code. Just check. its going to failure method. In your workspace you should have the test.html returning the actual data. Thanks.
Don't use plain JS if you already have jQuery (it will be easier for you):
;$(document).ready(function(){
$(country_link).click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$(country_slide).show();
$(country_slide).val('<p>Loading</p>');
},
success: function (data, textStatus) {
$(country_slide).html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$(country_slide).hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});
Related
I made a simple autocomplete feature as follows:
$(document).ready(function(){
$('#search-field').keyup(function(e) {
ajaxAutocomplete(e);
});
});
function ajaxAutocomplete(e) {
var hash_tag = $.trim($(this).val());
$.ajax({
url : 'autocomplete.php',
method : 'GET',
dataType: 'html',
data : {tag : hash_tag}
})
.done(function(response) {
if (response) {
$('.datalistPlaceholder').html(response).show();
} else {
$('.datalistPlaceholder').hide();
}
})
.fail(function() {
alert('Something went wrong');
});
}
I am trying to use the event object in ajaxAutocomplete function as described by jQuery: https://learn.jquery.com/about-jquery/how-jquery-works/
The above set up does not work and returns this: jquery.js:7328 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
This does work after removing the callback from above:
$(document).ready(function(){
$('#search-field').keyup(ajaxAutocomplete);
});
function ajaxAutocomplete() {
var hash_tag = $.trim($(this).val());
$.ajax({
url : 'autocomplete.php',
method : 'GET',
dataType: 'html',
data : {tag : hash_tag}
})
.done(function(response) {
if (response) {
$('.datalistPlaceholder').html(response).show();
} else {
$('.datalistPlaceholder').hide();
}
})
.fail(function() {
alert('Something went wrong');
});
}
After combining Rory's answer above and reading about .call() from MDN I came up with the following that works:
$(document).ready(function(){
$('#search-field').keyup(function(e) {
ajaxAutocomplete.call(this, e);
});
});
function ajaxAutocomplete(e) {
console.log(e)
var hash_tag = $.trim($(this).val());
$.ajax({
url : 'autocomplete.php',
method : 'GET',
dataType: 'html',
data : {tag : hash_tag}
})
.done(function(response) {
if (response) {
$('.datalistPlaceholder').html(response).show();
} else {
$('.datalistPlaceholder').hide();
}
})
.fail(function() {
alert('Something went wrong');
});
}
Result on typing 'a':
j…y.Event {originalEvent: KeyboardEvent, type: "keyup", timeStamp: 1292.2500000000002, jQuery21406902543265129839: true, keyCode: 65…}
When calling a function, the context this gets lost. If you use the callback directly, the context is available.
The problem with your first example is because you wrap the call to ajaxAutocomplete() in an anonymous function which means that you lose the reference of this within your called function (it will point to the window instead of the #search-field element). This in turn means that $(this).val() returns nothing - hence the error coming from jQuery.
You need to either use .call(this) when calling your function to maintain the scope of this within the function:
$(document).ready(function(){
$('#search-field').keyup(function(e) {
ajaxAutocomplete.call(this);
});
});
Working example
Alternatively you can use your second method which passes the ajaxAutocomplete function reference to the event handler which then maintains scope:
$(document).ready(function(){
$('#search-field').keyup(ajaxAutocomplete);
});
Personally I prefer the latter approach for its brevity.
I am using the following code to get data from an input field and send it to PHP by POST but its not working
<script type="text/javascript">
$(document).ready(function () {
$("#id_1").change(function () {
var rat1 = $(this).val();
$.ajax({
url: "upload.php",
type: "post",
data: rat1,
success: function (response) {
// you will get response from your php page (what you echo or print)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
});
</script>
this is the input form
<input type="number" name="your_awesome_parameter" id="id_1" class="rating" data-clearable="remove"
data-icon-lib="fa" data-active-icon="fa-heart" data-inactive-icon="fa-heart-o"
data-clearable-icon="fa-trash-o"/>
You need to provide a name for the parameter. It should be:
data: { param_name: rat1 }
Then in upload.php you access it with $_POST['param_name']
Just in case, did you imported Jquery into your project?
I tested your code and I with the minor change that Barmar specified and it is working for me.
Try to use this code in your php file and see if you get any response in the developer tools console.
$data = $_POST["param_name"];
echo json_encode([$data]);
Try in this way men
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ejemplo_ajax_proceso.php',
type: 'post',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (response) {
$("#resultado").html(response);
}
});
}
change on input type number is not working in older versions of browsers, I think not sure. But try this below solution as you are using input type number.
$("#id_1").on("mouseup keyup",function () {
//your logic here
});
and passing data as already mentioned by others:
data: { param_name: rat1 }
I have a page where people can add things to their "favorites" list with this:
$(function(){
$('.doit-01234').click(function (e) {
e.preventDefault();
$.ajax({
url: "https://www.domain.com/page.php?add=01234",
type: "GET",
success: function (data) {
$(".result-01234").html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
$(".result-01234").html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
});
The items get added with page.php?add=01234. The same page may however have 20 or 30 items that people can add to their favorites. Is there an easy way to use just one instance of this script for multiple IDs instead of the same jQuery code over and over after each item?
Meaning page.php?add=9999 would then update .result-9999 when .doit-9999 is called and page.php?add=5151 would update .result-5151 and so on...
Give your elements a common class and a custom data attribute:
<div class="ajax doit-01234" data-id="01234"></div>
And then use 1 handler:
$('.ajax').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
success: function (data) {
//Concatenate a selector based on the "id" in the data attribute
$(".result-" + id).html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
//Concatenate a selector based on the "id" in the data attribute
$(".result-" + id).html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
Create this function like this:
function Name (e) {
var code = 01234;//extract your code like 1234 here by splitting or..
e.preventDefault();
$.ajax({
url: "https://www.domain.com/page.php?add=01234",
type: "GET",
success: function (data) {
$('.result-'+code).html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
$('.result-'+code).html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
Now where you want to call this function , you can call like this:
HTML:
<button onclick="Name(this);">Hello</button>
I have two pieces of code, first of all I have my code which toggles open a div with an included close button:
http://jsfiddle.net/spadez/uhEgG/27/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I also have my Ajax code which is designed to fire when the div has been opened:
$(function () {
$('#country_link').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
return false;
});
});
What I am stuck with now is, how do I make the ajax only execute when the div is being opened? Because I am working with a toggle and close button it seems difficult to work out what the click is doing, whether it is opening it or closing it.
I guess my options are to have some kind of flag or alternatively have some "if" code, so if class is equal to .hidden then do not execute. I haven't been able to integrate either of these solutions and I am unsure if either of them is the proper way to achieve this.
Include the check as part of your slide function:
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
Demo: http://jsfiddle.net/tymeJV/uhEgG/28/
if($("#country_slide").is(":visible"))
//call ajax
This code adds data to the element, to check if it's already loaded next time you click on it.
Currently I am not able to test it, so it may contain errors.
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
});
});
This is my ajax function and
$('#save_form_3').button({
icons: {
primary: "ui-icon-disk"
}
})
.click(function (event) {
if($('#guarantor_details').validate().form()){
var form_3_data = $("#guarantor_details").serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: form_3_data,
success: function(response, textStatus, xhr) {
alert(response);
if(response=="success"){
alert(response);
}
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
});
first alert gives me message "success" and second alert doesn't execute. seems like if condition not working under success function.
any idea why it doesn't?
im using jquery-1.6.2.min.js.
maybe problem in jquery 1.6.2 or am i doing something wrong?
Thanks
if($SQL_INSERT){
echo "success";
}else{
echo mysql_error();
}
thats insert.php anyway
if($.trim(response)=="success") works
try removing any whitespaces/newlines outside the tags in your insert.php file.
Maybe you could use a simple regex?
Instead of response=="success", try /success/.test(response)
This will return true if success is anywhere in the response string.