Ajax form submitting incrementing times - php

I've got a form that submits using ajax, however for some reason if you change the values and submit it again it then it inserts 2 duplicate rows, submit again and it inserts 3 duplicate rows the next time, and so on... Somewhere it's storing the number but being new to ajax i'm not 100% sure what I should or shouldn't be adding. Here's the code:
$(document).on('submit', '#add-badge-form', function(e)
{
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data)
{
$(".add-badge-result").fadeIn(500).show(function()
{
$(".add-badge-result").html(data);
});
$('#add-badge-form').trigger("reset");
}
});
return false;
});
EDIT: The PHP that handles the form:
if($_POST['form-name'] == 'add-badge') {
$name = $_POST['name'];
$description = $_POST['description'];
$level = $_POST['level'];
$result = mysqli_query($con,"INSERT INTO Badges (Name,Description,Level) VALUES ('$name','$description','$level')") or die(mysql_error());
mysqli_close($con);
if($result)
{
echo $name." added successfully.";
}
else
{
echo "Error adding ".$name.".";
}
UPDATE:
I've now found that this only occurs after you change pages (also using ajax). So if you insert a form, then insert again without leaving the page, it works fine. If you insert, then change the page, then go back and insert again, it inserts a duplicate. Here's how I change the page:
$(".button").click(function(){
$(".nav li ul a").removeClass("current");
if (this.id == "add-badge") {
$("#rightContainer").load("add-badge.php");
$(this).addClass("current");
} else if (this.id == "edit-badge") {
$("#rightContainer").load("edit-badges.php");
$(this).addClass("current");
} else if (this.id == "award-badge") {
$("#rightContainer").load("award-badge.php");
$(this).addClass("current");
}
});

I have fixed this now. Because of $(document).on('submit', '#add-badge-form', function(e) when loading the page, it was loading the instance of the form each time and thus if I loaded the page 5 times, it was having 5 instances of the form. I changed that to $( "#add-badge-form" ).submit(function(e) and it now only submits one version no matter how many times the page has been loaded. Simple solution!

I would recommand you to get only the fields you need from your form:
var data = { field1 : $("#field1").val(), ... };
This will prevent someone manually adding fields to your form.
I think the way you serialize data is the problem so it should fix it.

Related

send ajax request with no data, PHP check isset

I have this following code that works at the moment. What I want is to remove the url and process the ajax request on the same page. Since I am not sending any data, how can I have php check when my ajax function is ready to send a request to the database?
I'm using jquery mousedown to hold on to a button, then after 1 second the user receives a prompt to delete. If the user holds button 5 on the list, it will delete row 5 in mysql table, button 10 will delete row 10 etc.
$("#outter_div_5").mousedown('#button_5', function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user== "d")
{
$.ajax({
url: './ajax/5/delete.php', // <-- I want to remove this line and process this ajax request on the same page
type:'POST',
data: {},
success:function(result){
$("outter_div_5").fadeOut(125);
},
complete:function(data){
$.ajax({
url:'reload_table.php',
method:'POST',
success:function(data){
// reload javascript variables and html table
$("#my_table").html(data);
}
});
}
});
}
}, 1000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});
And my delete.php page is a simple mysql query, I'm not using a php isset since I am not passing any data.
include_once './includes/db.inc.php';
$sql = "UPDATE my_table SET row = '' WHERE id = '5' ";
mysqli_query($conn,$sql);
I need to create a php isset so that I can process this ajax request on the same page. How can I do this?
<?php
if( isset($_POST['']) ){
$sql = "UPDATE my_table SET row = '' WHERE id = '5' ";
mysqli_query($conn,$sql);
}
?>
<script>
$("#outter_div_5").mousedown('#button_5', function(e) {
clearTimeout(this.downTimer);
this.downTimer = setTimeout(function() {
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user== "d")
{
$.ajax({
url: './ajax/5/delete.php', // <-- I want to remove this line and process this ajax request on the same page
type:'POST',
data: {},
success:function(result){
$("outter_div_5").fadeOut(125);
},
complete:function(data){
$.ajax({
url:'reload_table.php',
method:'POST',
success:function(data){
// reload javascript variables and html table
$("#my_table").html(data);
}
});
}
});
}
}, 1000);
}).mouseup(function(e) {
clearTimeout(this.downTimer);
});
</script>
The main advantage of an HTTP (with AJAX in your case) request is that you don't have to reload the page or redirect the user to pass information the server. Some other advantages and more info can be found here. Note that php code is run before any of your javascript is run.
If you don't want to use an HTTP request, you have multiple solutions. Here's mine:
Rather than such HTTP request, you can use a form with method="POST" (read all about that) that uses a prompt before submitting:
$("#delete_button").click(function( event ){
event.preventDefault();
var prompt_user = prompt('Enter "e" to Edit \nEnter "d" to Delete');
if (prompt_user == "d") {
console.log("submitted");
//$("#myForm").submit();
}else if( prompt_user == "e" ) {
console.log("editing");
// Add your actions for editing the thing you want to edit.
}else {
console.log("aborted");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form id="myForm" action="" method="POST">
<!-- You can add inputs here to add to your POST
This data can be read when the form is submitted and the page is consequently reloaded. -->
<input id="delete_button" type="submit" value="delete">
</form>
However, if I'm being honest, I would stick with the HTTP request as this can provide a more slick user experience.
I understand you are a beginner so please feel free to ask questions if you don't understand something, we have all been there (and maybe I am still there :p).

I have encountered a really weird thing while Inserting jquery var in mysql table from a php page

I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});

How to stop jQuery post page refresh

I am getting data from an MySQL database through PHP. I am sending the and getting the data from PHP using jQuery. Here is the code.
$.POST("SubmitCode.php", $("#questionCodeForm").serialize(),'json').done(function(data) {});
Now the problem is that once I send this data the page refreshes. How can I stop the page refresh. If I delete 'json' then the page stops refreshing but the problem is that I want to get the json data without page refresh. How can I do this?
-------------------------------------------after edit-----------------------------------------------------------------------------
Here is the updated code
$(document).ready(function() {
initialization();
codeSubmission();
});
function initialization() {
$("#answerForm").hide();
}
function codeSubmission() {
$("#submitButton").click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize()).done(function(data) {
var questionName = data.questionName,
options = data.options,
pollingStatus = data.pollingStatus,
codeExist = data.codeExist;
alert(data);
alert(data[1]);
alert(questionName);
alert(options);
if(codeExist == true) {
$("#questionTitle").text("questionName");
for(rowNum=1;rowNum<=5;rowNum++) {
$("#checkbox-"+rowNum).val("Answer1");
$("#checkbox"+rowNum+"label").text("Answer"+rowNum);
}
$("#answerForm").slideDown(500);
} else if(codeExist == false) {
alert("This quiz code is invalid");
}
},'json');
//return false;
});
//return false;
}
Now the problem is that the output of alert(questionName) is undefined. The data is passed as a string. How do I get the correct information in the correct variables?
Try this instead: (note the placement of the callback function, and lowercase .post method)
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
Also make sure that whatever is triggering the post isn't an actual link and if it is, you need to stop the default action from occuring. For example:
Click here to submit
javascript:
$(a).click(function(e) {
e.preventDefault();
$.post("SubmitCode.php", $("#questionCodeForm").serialize(),function(data) {
//manipulate your data here
},'json');
});
You also have to parse the json on the client side. You can do this using
obj = jQuery.parseJSON(data);

jQuery get() php button submit

I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});

Jquery Form Validation and Checking the values with Mysql Database through PHP Script

I have a form which has a input textbox and submit button.
On submission of the form the textbox value should get pass to an php script and check the values whether it exists in the Mysql Database. If it exists then we need to show an alert box stating that "Entered Value is already exists, Try something new". If the value not exists the form can be submitted to the php script which is in the form action.
I tried with the jquery and the code is below:
$(document).ready(function() {
$("#form_add").submit(function () {
var pval = $("#name").val();
var datastring = 'pname'+pval;
$.post("unique_valid.php", {pname:pval }, function (data){
alert('duplicate');
});
return false;
});
});
Problem with this code is It shows alert box on every case but its not allowing to submit the form if the values is not exists in the database.
Php code :
$pname = $_POST['pname'];
if( $pname == $row['name']){
echo "success";
}else{
echo "failure";
}
Suggest the better solution for this problem.
That's because you're alerting 'duplicate' no matter what the PHP output is. Try checking the value of data before alerting, like this:
$(document).ready(function() {
$("#form_add").submit(function () {
var pval = $("#name").val();
var datastring = 'pname'+pval;
$.post("unique_valid.php", {pname:pval },
function (data){
if(data == 'failure'){
alert('duplicate');
}else{
alert('not a duplicate');
}
});
return false;
});
});
And I'm assuming your PHP code will actually be saving the record if it's not a duplicate (your code doesn't indicate as much, though)?

Categories