jquery infinite loop in form submit - php

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);
});

Related

Counting clicks on an <a> link in a MySQL database

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.

AJAX Form duplicate entries on submission

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.

ajax jquery call doesnt work for me

UPDATE:
I need to get the jason.. The click event doesnt work why..
update:
<script>
$(document).ready(function(){
$("#RefreshButton").click(function(){
$.ajax({
url: "/test2/ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
alert("This is my data: "+data);
$(".article").remove();
$.each(data, function(key, value){
$('articleColumn').append( '<p class="article"><font size="5"><b>'+value[0]+'</b></font><br/>'
+value[1]+' Read more...</p>');
});
},
error: function( error )
{
alert(JSON.stringify(error));
}
});
});
});
</script>
The ajax call works..but not when it is in the click event handler..why?!?
I think the solution to the problem lies in the html:
<a href="" id="RefreshButton" >Refresh</a>
may be it refreshes the page and then send the response. I think it is the problem in the way the event propogates ..hmm
Generally when making an ajax call using jQuery I use the short hand version of POST and GET methods. So in your case I would do something like this
$.get("ajax.php", function(data){
alert(data); //just to make sure it works
}, "json");
Be sure to send the response back from ajax.php as json using json_encode(array("key"=>"value","key"=>"value")); ?>)
Also since ajax cannot go across domains you don't have to specify http://localhost/ajax.php, rather you can just specify it as the relative path to where you are calling the jquery function from.

Dynamic Javascript Ajax + Php

I'm not sure this question has the best of titles but I'm not sure what else to call it so sorry for that.
I'm using ajax to pull in content for a div on my website (after an option is selected). The content is a form generated by a PHP script. When the form is submitted a JavaScript function should be called but I'm just getting an error that says the function can't be found.
The JavaScript is pulled in via ajax with the form and I can't really change that as it needs to change demanding on the option selected.
My question is should this work? if not I'll just have to re think the way I'm doing it, just wanted to check if it wasn't working because it never will or if I'm doing something wrong.
I would show the code but it's very long.
Thanks in advance!
Edit: thanks for all the comments ect, apologies for not including the code before here it is.
function select(id){
$.ajax({
url: 'select/'+id,
type: 'GET',
dataType: 'html',
success: function(msg) {
$('.product_details').html(msg);
return false;
}
});
}
Are you using a javascript library?
With jQuery specify a data type of html and make sure the script tags are before the HTML in the response
$.ajax({
url: "something.php",
dataType: "html",
success: function(data, text, request) {
...
}
});
in mootools...
var myRequest = new Request({
url: "something.php",
evalScripts: true,
onSuccess: function(responseText, responseXML){
....
}
});
myRequest.send();
Now your passed tags will be evaluated and available to the DOM

jquery ajax post - not working first time page loads

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

Categories