ajax update mysql field without refreshing page - php

I'm trying to get my announce box that has a X button on the top right, to be clicked and it remove the message, and update a mysql query field without refreshing the page
HTML
<form id="myForm" action="delanno.php" method="post">
<div class='announce-box'>
<div class='announce-message'>$show_message</div>
<div class='announce-delete'>
<a class='deleter'>
<button type='submit' id='sub' name='$show_id' style='height:35px; width:40px'>
<img src='../css/images/delete_25.png' width='25' height='25'>
</button>
</a>
</div>
</div>
</form>
php (delanno.php)
<?php
include("conn.php");
foreach($_POST as $name => $content) { // Most people refer to $key => $value
$something = "$name"; //ignore this, i did this for testing purposes
$query = mysql_query("UPDATE announce SET active='disabled' WHERE id='$something' ") or die(mysql_error());
}
?>
ajax // This is supposed to update the php field without refreshing or sending to another page
<script type="text/javascript">
$("#sub").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info){ $("#result").html(info);
});
});
$("#myForm").submit( function() {
return false;
});
</script>
more ajax // this is supposed to remove the announce div when the delete button is clicked.
<script>
$('.deleter').on('click', function(){
$(this).closest('.announce-box').remove();
})
</script>
if i remove
return false
it sends it to the php page and it obviously works. i'm not sure what to do from here
EDIT: The script doesn't work unless it's being sent to the php page

Javascript selecting DOM elements should be inside a ready function when the DOM is actually ready, e.g.
$(document).ready(function() {
// $('#some-id') .. etc
});
.
I just searched SO for a duplicate, I think it's out there but I didn't find it, so just posting as an answer and if someone else does, just flag it.

Related

mysqli insert / update and ajax issue

I have question regarding inserting and updating a MySQL database from a form which is loaded in a div via ajax. I have taken various examples from different websites to check if it was an error on my part but they all work when the page is loaded independently and insert or amended to the database. When the form is loaded into the div, the inputs are completed and submitted it then redirects to the home page as defined in the script file but no information is inserted into the database:
(ajax_url.length < 1) {
ajax_url = 'app/pages/home.php';
}
As I said the form works and inserts if I load the form page directly. For that reason I have also tried the following while giving the form an id of "dataforms" and the submit button an id of "sub":
$("#sub").click( function() {
 $.post( $("#dataforms").attr("action"),
         $("#dataforms :input").serializeArray(),
         function(info){ $("#result").html(info);
   });
clearInput();
});
 
$("#dataforms").submit( function() {
  return false;
});
function clearInput() {
    $("#dataforms :input").each( function() {
       $(this).val('');
    });
}
Is there something basic I am completely missing?
This is an example I was trying to get to work:
<?php
        include_once('/config.php');
        $task_name = $_POST['task_name'];
       
        if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
         echo "Successfully Inserted";
        else
        echo "Insertion Failed";
?>
<span id="result"></span>
<form id="dataforms" action="" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
I have also attempted to define the php in a separate file and call it on action and I end up with what looks like the post values not being carried across as I get an error showing $task_name is not defined.
The js script file is referenced in the footer and have no issues with datatables displaying and selecting data from the database so I guess it has something to do with how the form is being submitted and reloading. Do I need to treat form submissions differently when ajax is involved? I have used various insert and update scripts to test and all behave the same way.
First Page — can be .html or .php, doesn't matter:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#sub").click( function() {
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
$("#dataforms").submit( function() {
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
Second page — insert-task.php:
<?php
//include_once('/config.php');
$task_name = $_POST['task_name'];
//if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
// echo $task_name; die;
if(true)
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
The two pages do work in tandem. Though there are a couple of things to note, please:
The database operations aren't yet a part of the executable code.
However, if // echo $task_name; die; was uncommented, then the <span> in the first page would be populated with whatever value was keyed in the input field, which would establish that the form data is relayed properly to the backend.
EDIT:
To deal with the required fields, following change is required in the first page:
Get rid of the click function for $("#sub")
Prevent the default submit action when dataforms is submitted
So, in effect, the updated code would look like follows:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name" required><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#dataforms").submit( function(e) {
e.preventDefault();
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
}
);
clearInput();
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
This would still show up Please fill out this field message if no data was entered in the input field and, at the same time, prevent the unexpected pop-up as a consequence of clearing the field after a successful submit.

Redirecting to PHP page with post data format

I have seen many of the posts in stackoverflow but i'm unable to find my answers so thats why i'm posting here.
Scenario is this:
My Page is having many div containers and each div is having EDIT Button and when a user clicks EDIT of any DIV i want the user to be redirected to another page with ID of that DIV,
I want to do this whole this using POST method.
File edit.php
<button class="edit_btn" onclick="edit_ID('$btn_id')">
<script type="text/javascript">
function edit_ID(array){
$.ajax({ type:"POST",
url:'redirecter.php',
data:{editorID:array.split("_")[1]},
success:function(data){
//window.location.href="editapplication.php";
}
});
}
</script>
File redirector.php
<form action='editapplication.php' method='post' name='frm'>
<?php
foreach ($_POST as $a => $b) {
echo "<input type='hidden' name='".htmlentities($a)."' value='".htmlentities($b)."'>";
}
?>
</form>
<script language="JavaScript" type="text/JavaScript">
document.frm.submit();
</script>
you need to hook the click event of the button, and perform your actions there:
$(function() {
$('#buttonID').bind('click', function(event){
var id = $(this).parent().id;
$.ajax({....});
});
});

post data not set using jQuery post method on button selected by class

This site has been really helpful while writing this program. Unfortunately, I hit a snag at some point, and have boiled the problem down quite a bit since. At this point, I am looking at three files, a .html that contains a form, a .js that contains my event handlers, and a .php that receives my post variables and contains new content for the form.
I am getting the post data from the initial text input just fine. The new form content is set as I would expect. However, after this form content is set to a new input of type button with a class of button, the post method in my button class handler is not setting post data on login.php as I expect it to.
Here is my code:
Contents of interface.html page:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="interface" action="login.php" method="post">
<input type="text" value="enter username here" name="user"/>
<button id="submit">submit</button>
</form>
<script src='events.js'></script>
</body>
</html>
Contents of events.js file:
$("#submit").click(function(){
$.post(
$("#interface").attr("action"),
$(":input").serialize(),
function(info){$("#interface").html(info);}
);
});
$(".button").click(function(){
var $this=$(this);
$.post(
$("#interface").attr("action"),
{data:$this.val()},
function(info){$("#interface").html(info);}
);
});
$("#interface").submit(function(){
return false;
});
Contents of login.php file:
<?php
if(isset($_POST['user'])){
echo '<input type="button" class="button" value="set data"/>';
}else if(isset($_POST['data'])){
echo 'data is set';
}
?>
You need to wait until the button exists to bind an event to it. Additionally, i'd switch from click to submit and drop the click event binding on .button completely.
//$("#submit").click(function () {
$("#interface").submit(function (e) {
e.preventDefault();
var $form = $(this), data = $form.serialize();
if ($form.find(".button").length && $form.find(".button").val() ) {
data = {data: $form.find(".button").val()};
}
$.post($form.attr("action"), data, function (info) {
$form.html(info);
});
});
//$("#interface").submit(function () {
// return false;
//});
Since the form is not being replaced, and the event is on the form, you no longer need to re-bind anything.

Ajax form submits

Hey guys I'm not getting any post data coming out here, and am pretty positive this isn't working at all. The big deal was it firing a accept/deny with an id # attached, and a value for that forms checkbox. I'm getting no errors, and no warnings so am having an issue stepping through it =( Hopefully another set of eyes?
Sorry ahead of time I know my JQuery blows.
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.6");
</script>
<script>
$(".audit").submit(function()
{
return false;
});
$(".accept, .deny").click(function(event)
{
$form = $(this).parent("form").get(0);
$gruden = $form(function(index) { attributes.push($(this).val());});
$.post($form.attr("action"), $form.serialize() + "&submit=" + $(this).attr("value") + "&gruden=" + $gruden, function(data) {
console.log(data);
});
});
</script>
.......................
<?php foreach($obj->photos as $pending) { ?>
<div class='container' id='photo-<?=$pending->id;?>'>
<span class='shadow'>
<a href='/<?=$pending->large;?>'><img src='http://<?=$_SERVER['HTTP_HOST'].'/'.$pending->small;?>'/></a>
</span>
<form class='audit' name='audit-<?=$pending->id;?>' action='<?=$_SERVER['PHP_SELF'];?>'>
<div class='box'>
<ul>
<li>ID: <?=$pending->id;?></li>
<li>Date: <?=$pending->created_at;?></li>
<li>User: <?=$pending->fb_id;?></li>
<li> </li>
<li>
<input class='gruden' value='gruden-<?=$pending->id;?>' type='checkbox' />
<a name='submit' value='accept-<?=$pending->id;?>' class='accept' href=''></a>
<a name='submit' value='deny-<?=$pending->id;?>' class='deny' href=''></a>
</li>
</ul>
</div>
</form>
</div>
<?php } ?>
I think I see your problem now. I've re-written your code so it makes more sense. Comments to explain what's going on
<script>
$(".audit").submit(function(){
return false; //Preventing the form from submitting if someone hits Enter
});
$(".accept, .deny").click(function(event) {
var form = $("form.audit"); //Always use var to declare variables in Javascript. It's not PHP; we don't use $, unless you want it to be a part of the variable name. Also fixed your selector
var gruden = $form(function(index) { attributes.push($(this).val());}); //Are you trying to find out if the checkbox with class gruden is checked? Please answer in the comments so I can correct this line
$.post(form.attr("action") + "&submit=" + $(this).attr("value") + "&gruden=" + gruden, form.serialize(), function(data) {
console.log(data);
}); //I assume that you want to pass submit and gruden as GET params here, since you're appending them to the URL. If you want them to go as POST vars, then let me know in the comments
});
</script>
No offense, but I think you might benefit from reading a bit more about Javascript and jQuery. At least read up on how selectors work in jQuery, and some basic Javascript syntax
This line surely doesn't return your form element as it only looks at the direct parent.
$form = $(this).parent("form");
Try something like this:
$form = $(this).parents("form").get(0);

replacing div content after form submission

I have a div with a form in it. After a user submits the form, I want to load new content into the div, replacing the form.
The new content will be static.
Do I need AJAX for this?
you don't HAVE to use ajax for this, after submitting the form you can issue a redirect to a static page without the form(post-redirect-get pattern).
But note that in this case the entire page will refresh while submitting,
and if the submit might fail from some reason(who said validation), hitting F5 will pop up the ugly "do you want to send crap..."
so no, you don't have to use ajax, but it is so easy with the form plugin that it is a crime not to.
if you do use the form plugin, then at the success callback hide the form with the static content
You do need Ajax: (I'll do it like SimpleCoder said, but with the ajax call)
$('#myForm').submit(function(){
var field1 = $("#field1").serialize(); // If this doesn't work just remove the serialize()
var field2 = $("#field2").serialize();
$.ajax({
type: "POST",
url : "???", //your processing page URL instead of ???
data: "&field1="+field1+"&field2="+field2,
success: function(){
$("#formHolder").html("Your static content");
}
});
});
( You should replace field1, field2 with your fields, and if it doesn't work, remove the serialize() function. )
All you have to do is .html() the static content in the success function of the ajax call.
Assuming your HTML looks something like this:
<div id="formHolder">
<form id="myForm">
...
</form>
</div>
Do something like this:
$("#myForm").submit(function(){
$("#formHolder").html("Your static content");
});
You can find an example of this here
https://www.write-about-property.com/seo-services/ the code to work on the form submit uses an instance of the object created in form.js
If you have a crack at it then come back we will help you perfect it for your purpose. You would put the div you wanted to update in the toupdate var
ajform.toupdate = $("#update")
you can simply make the divs invisible, and the submit button is just a button with js action to make the div visible
<script type="text/javascript" language="javascript">
function step2() {
document.getElementById('step1_container').style.display = 'none';
document.getElementById('step2_container').style.display = 'block';
}
function step3() {
document.getElementById('step2_container').style.display = 'none';
document.getElementById('step3_container').style.display = 'block';
}
</script>
...
<form action="validate.php" method="post">
<div id="step1_container">
PAGE 1 here
<input type="button" onclick="javascript:step2();" value="submit"/>
</div>
<div id="step2_container" style="display: none;">
Page 2 here
<input type="button" onclick="javascript:step3();" value="submit"/>
</div>
<div id="step3_container" style="display: none;">
Page 3 here
<input type="button" onclick="javascript:step4();" value="submit"/>
</div>
</form>
And so on
You don't need ajax, using only on-page javascript would be enough.
However, with ajax you can display the content from the page you're submitting the form to.
Try the jQuery From plugin for an elegant ajax solution:
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#divToUpdate',
url: 'comment.php',
success: function() {
alert('Thanks for your comment!');
}
});
});
</script>

Categories