I have some ajax/jquery code in one of my pages and the problem I'm having is that it doesn't work the first time the page is loaded. If I refresh the page it works no prob. It does work in firefox first time. All the variables that I'm using are ok as I've alerted them out. I don't get a success or error message. It justr doesn't appear to do anything?
Any ideas?
$('.window .request').click(function (e) {
var itm = document.getElementById('txtItm').value;
var qty = document.getElementById('txtQty').value;
var msg = document.getElementById('txtMessage').value;
var op_id = document.getElementById('txtOp_id').value;
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
It's hard to determine what the problem might be given the information and it sounds like you've not fully tested the page in a consistent manner. It seems likely there is another element on the page affecting the click event, as opposed to the handler logic itself, but there's no way to tell. Make sure you are binding to the click event after the page is ready:
$(document).ready(function(){
$("#uniquedomid").bind('click',function(){
// click handler logic
});
});
Also, as you're new to JQuery, one thing you're going to want to start looking at are all the various ways in which JQuery can improve your life. It does almost everything. But for starters, you're going to want to start using:
$("#uniquedomid")
Instead of
document.getElementById("uniquedomid")
And
$("#uniquedomid").val();
Instead of
document.getElementById("uniquedomid").value
Related
I have different links on my website which lead to other websites. I want to count the amount of clicks on the different links with my MySQL database.
I thought about doing a redirection over a php file which adds it in the database, but I would prefer to not redirect the user. Is it possible that the user just clicks on the tag gets immediately to the external website, and I can still count the click?
Thanks for you answers,
Till
yes you can run an ajax request and when the request is completed then you can redirect user to where ever you want to.
in the ajax request you will count the clicks and save it to the database.
you can do something like
$("a").click(function(){
$.ajax({url: "scriptthatwillcountclick.php", success: function(result){
window.open('redirect_here');
}});
});
Use ajax.
var data = {link:"value"};
$.ajax({
url : "your_file.php",
type: "POST",
data : data,
success: function(data, textStatus, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
You can run this code inside .click function when the link is pressed.
And in your php file just increment the count.
You can use jQuery Ajax funcionality to accomplish your goal, just create an on click even for your "a" element and execute your Ajax to save the click information on your database.
$('a').on('click', function(){
$.ajax({
method: "POST",
url: "save-my-click.php",
data: { 'extrainfo' : "Some extra info" }
});
});
Do not return false, or event.preventDefault() on your click event, because it will brake the redirection.
UPDATE:
You don't need to set the success and error functions because it is going to redirect anyway and you are not going to handle them.
I've got a PHP form set up and it works fine on it's own but now that I've hooked it up with AJAX I'm getting duplicate submissions when someone submits the form so even though they've only submitted the form once it's added the details to the database multiple times.
From my testing it seems as though its sending the data twice but looking at the submissions from other people it's possible that it's doing it more than twice under certain circumstances but I haven't been able to replicate that.
Here is the code I was using initially:
$("#email-gather").submit(function(e) {
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
e.preventDefault();
});
I have had a look around to find a solution and I saw a few people with similar issues saying that .live should be used instead of .submit so I amended my code this this:
$( "#email-gather" ).live( "submit", function() {
event.preventDefault();
var url = "https://www.ruroc.com/emailgather.php";
$.ajax({
type: "POST",
url: url,
data: $("#email-gather").serialize(),
complete: function(data) {
$('.email-win input.button').val("submitted").attr('disabled', 'disabled').css({'background-color' : '#b34c4c','text-shadow' : 'none'});
}
});
});
However this also resulted with the same issue so I'm hoping you might have a solution to this issue. I appreciate any help you can provide on the matter.
In the second part of code (that should work), you have event.preventDefault but event is not defined. try to add function(event) and it must work.
Else in the first one, you can put the prevent default before ajax call and take away the second submit. You need to add a return true in the ajax function to tell you script that the submit was successfull.
I have a select group populated by AJAX/PHP.
The issue i have although it works perfectly well, it does not return results 100% of the time of the page load.
Is there a specific reason why this might be happening?
the html
<div id='select_tags_div'>
</div>
the AJAX
$( document ).ready( function() {
selector_refresh();
});
function selector_refresh() {
url = '/home/bin/scripts/tags_list.php';
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
beforeSend: function() {
},
success: function(result) {
$("#select_tags_div").html(result);
$(".chosen-select").chosen();
$('.chosen-select').trigger('chosen:updated');
vid_tags();
}
});
}
I have checked the source on the both success and fail to show results, and the results actually are not populated at all. I thought it may have been a chosen.js issue but now its looking like it isn't that at all. Instead it seems it may be a PHP/AJAX issue not returning the results.
When i check the AJAX success with an alert, it confirms the AJAX is successful even on the times when the PHP has not populated correctly.
ADDED
I added a button which calls the function to populate the field, of which functions 100% of the time.
Could this be a case of DOM perhaps?
I've created a custom wordpress plugin that should do the following:
on page load, submits a form
ajax catches it and does some other functions
results are returned
Only problem is that the plugin started redirecting to another page and looping infinitely. I've isolated it to the jquery submit code but I can't figure out what I'm doing wrong. I was hoping you folks could lend a sleep-deprived programmer a hand.
$('#searchform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '../wp-content/plugins/otwcsl/getStores.php',
data: $('#searchform').serialize(),
success: function(response) {
searchLocations(response);
$('#searchform').unbind().submit();
}
});
});
It worked fine on my localhost environment but went berserk on the 'live' website. I can't figure out the disconnect but I'm pretty sure the problem lies here. Thanks in advance!
UPDATE: I've cut everything down until it looks like this:
$('#searchform').submit(function(e) {
return false;
}
It's stopped looping but it redirects from http://www.mypage.com/index.php/locations/ to http://www.mypage.com/index.php/?s=. I can't figure it out since it's clearly not ajax that's affecting it.
FINAL UPDATE: I've finally fixed the problem. I removed all 'submit' functions and used a button click instead. I used the answer found here in option 3. I'm guessing there was some previous script that was severely messing with the form. Unfortunately, it's not an option for me to go disabling the scripts to find the root cause at this point. Thanks everyone for helping me troubleshoot it!
You have this code in the ajax call:
$('#searchform').unbind().submit();
In it you submit the form again. I guess that is what's going wrong.
infinite loop because you submit the form again if submit is seccussfull:
success: function(response) {
searchLocations(response);
$('#searchform').unbind().submit();
}
why submit again on success? remove it and it will work!
it should be:
success: function(response) {
searchLocations(response);
}
UPDATE:
your submit function should be like this:
var _form = $('#searchform');
_form.unbind();
_form.submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "../wp-content/plugins/otwcsl/getStores.php",
data: _form.serialize(),
success: function(response) {
//searchLocations(response); // check this method may be its submit the form again
}
});
});
Check the response from the server and set the propper datatype in the ajax call.
you can debug your ajax by using:
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serializeArray()
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}).done(function(data, textStatus, jqXHR) {
console.log(data, textStatus, jqXHR);
});
I have a web application which features a bunch of different items, which are generated from a MySQL table. As users scroll through it, I want them to be able to click a link next to the item which will insert the request into a MySQL database. Normally, I’d do this by creating a PHP page (which I will do anyways) that grabs the item name & user id from the URI using the $_GET method & inserts it into the table. However, in this case, I don’t want the users to be redirected away from wherever they are. I just want the link to send off the request, and maybe display a small message after it is successful.
I figured jQuery/AJAX would be best for this, but as I’m not too familiar with it, I’m not sure what to do. Any tips are appreciated!
You have to do something like
$('.classofyourlink').click(function(e){
e.preventDefault();//in this way you have no redirect
$.post(...);//Make the ajax call
});
in this way the user makes an ajax call by clicking a link without redirecting. Here are the docs for $.post
EDIT - to pass the value to jQuery in your case you should do something like
$('.order_this').click(function(e){
e.preventDefault();//in this way you have no redirect
var valueToPass = $(this).text();
var url = "url/to/post/";
$.post(url, { data: valueToPass }, function(data){...} );//Make the ajax call
});
HTML
<a id="aDelete" href="mypage.php">Delete</a>
Script
$(function(){
$("#aDelete").click(function(){
$.post("ajaxserverpage.php?data1=your_data_to_pass&data2=second_value",function(data){
//do something with the response which is available in the "data" variable
});
});
return false;
});
See http://api.jquery.com/jQuery.ajax/
$('#my-link').click(function(){
$.ajax({
url: "mypage.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
return false;
});
$('.classOfYourLinkToBecliked').click(function(){
$.ajax({
type:'GET',
'url':'yoururl',
data: {yourdata},
processData: false,
contentType: false,
cache: false,
dataType: 'json',
success: function(response){
alert(response);
}
});
});