AJAX Form duplicate entries on submission - php

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.

Related

AJAX - PHP how to return a variable to the original AJAX script and alter an input value

I am protecting my forms with a captcha code to prevent using bots submitting loads and loads of forms.
This form works with AJAX and won't refresh the page like it usually does.
I have everything set now and it is working. but..
So this is the form im talking about to help understand.
When you click on request a new password, i need the code to change on the input field.
I do change the code after requesting a password like this in newpass.php
$_SESSION['capcode3'] = $capcode3;
This is my javascript code:
<script>
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
document.getElementById("captcha").value = "<?php echo $_SESSION['capcode3']; ?>";
});
</script>
So by using document.getElementById it would change the input value but, instead of setting the new value, it sets the old value.
So if the code is ABC123 and the new code is DEF456 it wont change to DEF456
Is there a better way to send the new code back to the input field?
Note: I have tested if $_SESSION['capcode3'] will change it's value with a positive result.
You did not specify a success handler in your ajax. Ajax is handled async, thus needs a callback to where the data will be passed when the request is succesfuly handled
$.ajax({
type: "POST",
url : "data/newpass.php/",
success: function(data) {
//change UI here
document.getElementById("captcha").value = data;
},
});
Please add code in success of ajax because may be session value will be changed on ajax success.
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data,
success :function(data){
document.getElementById("captcha").value = data;
}
});
Please try with this.

Intermittent results from AJAX PHP request

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?

Send AJAX request by clicking a link without redirecting user

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

Ajax Post PHP Div Refreshing

It is me again. I am getting so frustrated with this code it is not even funny. It's not that I am wanting to post it again. It is just that now I understand the where the problem was in the code and wanted to see if you guys can help me figure the last part out.
Basically I am trying to refresh a div without reloading the entire page. It's killing me. Here is some more information on it:
here is my js file first
$(function() {
$(".button").click(function() {
// validate and process form
// first hide any error messages
var email = $("input#email").val();
//var dataString = '&email=' + email; commented out
var dataString = email;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: {email:dataString},
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function() {
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
$("#email").val('');
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
Now the problem that I am running into with this code is on the Ajax part. After placing the alert(), I have relized that if I use the function() like this:
success: function(data)
Then the alert came out blank. The reason behind it is that my URL is going to my php file, but my div that I am trying to refresh is on my html file. Meaning if I do this:
success: function(data) {
$("#div").html(data)}
I am sending blank data because it's trying to get the div from my php file instead of my html file.
Now if I do this:
$("#div").html()
Then that gives me the div that is in my html file.
By knowing what is going on now, Can you guys please help me???
My dear you should generate some sort of html in your php file that you want to generate in your div. Then you will see that you are having some content in data in the success function. This is an easy approach.
But there is also some other approach that is more efficient but it needs some sort of search. This is the implementation of Client Side Scripting. You can do this with the help of a jquery plugin jquote2. I hope it will work for you.
You're using
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
Both are wrong, jQuery .fadeIn() and .fadeOut() arguments are either [duration,] [callback] or [duration,] [easing,] [callback]. None take HTML as input.
Try changing
$("#div").fadeOut($("#div").html());
to
$("#div").fadeOut();
and moving it outside the $.ajax call to hide the previously showed (if any) results before the post and also change
$("#div").fadeIn($("#div").html());
to
$("#div").html(result).fadeIn();
Also change
success: function()
to
success: function(result)
Hope it helps.
This might be a problem relating to the response from the php script. Jquery doesn't always correctly render the Ajax response as html.
Setting dataType: html in the $.ajax({ ... }) call can help. Also setting header("Content-Type: text/html"); at the top of your php ajax script.

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