fnDraw to redraw the datatable populated from DB - php

I use fnDraw to redraw the table. Look at the code below. This thread is similar to my previous one, but this provides an extended solution. The idea is to first call 'estimate.php' that updates DB and then reload the table that is populated from DB. The problem is that I can successfully call 'estimate.php', however the 'success' part of ajax is not performed well and the datatable stays unchanged.
<div id="refresh">
<button id="refresh-table">Refresh</button>
<br>
</div>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#newspaper-b').dataTable({
"sPaginationType":"full_numbers",
"aaSorting":[[5, "asc"]],
"bJQueryUI":true
});
$("#refresh-table").button().click(function() {
$.ajax({
url: "callpage.php?page=estimate.php",
success: function(html) {
var table=$("#newspaper-b").dataTable();
table.fnReloadAjax();
table.fnDraw();
}
});
});
});
</script>

Related

AJAX - form submit, same page, PHP

EDIT: I have changed the AJAX code to what I am now using and I have also included JQuery in my code
I've read up on as much AJAX as I can and I am flat out failing!
My HTML form looks like this:
<form action="match_details.php" method="post" id="match_details">
....
<button type="submit" form="match_details" name="match_details" class="w3-button w3-block w3-mam w3-section" title="Update Match Postcode">Update</button>
</form>
From Stack I've managed to get this AJAX:
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
I've tried changing it from button to input and back again but nothing seems to change. The form still submits but it ignores the AJAX and the page refreshes.
You need to prevent the JS from submitting the form, and you're using the wrong form ID. Also, judging by the comments, you need to include jquery.
In the head of your HTML file, between <head> and </head> or just before the closing </body> tag, you can use the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The following code may help you (though it's advised to not query the same page as your ajax request emits from):
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>

Problems in submitting form data using ajax

i am new in ajax. i am aware to html,php. i want to do the CRUD operation in ajax. i have created a two file
index.php
insert.php as below.
when i click on submit button it submit data and inserted in database. But it resfresh the page. please suggest me that where i made mistake.
my code as below:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</head>
<body>
<form id="contactForm1" action="insert.php" method="post">
<label>Name</label><input type="text" name="user_name"><br>
<label>Age</label><input type="number" name="user_age"><br>
<label>Course</label><input type="text" name="user_course">
<br>
<input type="submit" name="sumit" value="submit">
</form>
</body>
</html>
insert.php
<?php
$conn = mysqli_connect("localhost", "root", "" ,"aj");
$name = $_POST['user_name'];
$age = $_POST['user_age'];
$course = $_POST['user_course'];
$insertdata=" INSERT INTO test3 (name,age,course) VALUES( '$name','$age','$course' ) ";
mysqli_query($conn,$insertdata);
?>
Close the script tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Use when document is ready
$( document ).ready(function() {
var frm = $('#contactForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
frm[0].reset();
alert('ok');
}
});
ev.preventDefault();
});
});
The ready event occurs when the DOM (document object model) has been
loaded. Because this event occurs after the document is ready, it is a
good place to have all other jQuery events and functions. Like in the
example above. The ready() method specifies what happens when a ready
event occurs.
The JavaScript code, binding the event handler, is executed too early. The DOM is not fully loaded yet so the form can't be found. jQuery doesn't warn about this.
Either wrap your code in jQuery's on doc loaded method $(function(){ /* code here */ } ).
Or/and move your JavaScript to the bottom of your HTML. This is a preferred method. See Benefits of loading JS at the bottom as opposed to the top of the document for more details
There is no mistake. Technically, its correct. It's just not fitting in your use-case.
It's default behaviour that page refreshes when user submits form.
You have two options:
Stop further execution when your ajax call is completed. You can do this by javascript by using preventDefault method. Then, use return false.
Change the submit button to normal button. In other words, don't submit form normal way. Give an id to normal button and call javascript function upon its click.

SQL query without refresh

I've read all the related posted, watched videos, and read tutorials... But I still can't figure this out. I just want to run a mysqli_query insert without a refresh.
No inputs, no variables, just a pre-defined sql insert without a refresh.
Here is the main doc:
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
$("#click").click( function()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
});
</script>
</head>
<body>
<input type="button" id="click" value="Click">
</body>
</html>
Click.php (Has been tested standalone):
<?php
$db = mysqli_connect("localhost","root","","mytable")
or die("Error " . mysqli_error($db));
mysqli_query($db,"INSERT INTO items VALUES
('','test','test','total test','test','test','test','test')");
?>
This has been driving me crazy... I've read tutorials and watched many videos about ajax... but I can't figure this out.
Thank you for any advice.
To refresh a part of a page you got to bind the success function to a div in the html so add a div with an Id
<div id="myDiv"></div>
And then
$('#like$id').click(function()
{
$.ajax({
url: 'inc/scripts/liker_ajax.php?like=$id',
type: 'GET',
success:function(result){
$('#like$id').addClass('green');
$('#dislike$id').removeClass('red');
$('#myDiv').html(result);
}
});
});
You're binding the event $('#click').click() before there is an element to bind to (since $('#click') isn't loaded yet).
Just move your <script> tag with the click binding event into the <body> underneath the input button and it will work as expected.
You might also want to wrap in a jQuery document ready enclosure like:
$(function() {
});
to make sure it runs when DOM ready.
Try this.
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
function runAjax()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
</script>
</head>
<body>
<input type="button" id="click" onclick="runAjax()" value="Click">
</body>
</html>
You are binding the event to the element when the element is not exixting yet.
You have 2 options here.
Either move your script block to just below the end of body tag after the element.
Encase your code inside the script block under $(document).ready(function() {
// your code here
});
Also use the console tab under your developer tools to find the root cause if any errors are present.

Cant .ajax() submit a php form that has been loaded onto main page with jQuery .load()

I'm having the following problem. Below is an explanation of what my PHP pages are and how they work. When I access form.php directly and try to submit it via AJAX, it works perfectly.
Problem - When I .load() form.php into main.php, none of the jQuery code within form.php fires. (verified through firebug) No submits, no alerts, nothing. How can I get the jQuery code within form.php to work when its loaded into main.php?
main.php -> This is the main PHP page which has a link on it. Once this link is clicked, the following jQuery code fires to load "form.php" within a div called #formcontainer. This is the code within main.php that loads form.php.
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php");
});
});
</script>
form.php -> this is a form that gets loaded above. It submits data to MySQL through an jQuery .ajax() POST. Here is the jquery code which submits the form, which has an ID called #homeprofile.
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$(document).ready(function() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
});
Use on() for this like,
$(document).on('submit','#homeprofile',function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
return false;
});
You should be using the .on() syntax for targeting dynamically created elements (elements loaded into the DOM by JS or jQuery after the initial rendering)
Good
// in english this syntax says "Within the document, listen for an element with id=homeprofile to get submitted"
$(document).on('submit','#homeprofile',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Not as good
// in english this syntax says "RIGHT NOW attach a submit listener to the element with id=homeprofile
// if id=homeprofile does not exist when this is executed then the event listener is never attached
$('#homeprofile').on('submit',function(e){
//stop the form from submitting
e.preventDefault();
// put whatever code you need here
});
Hopefully this helps!
Small issue is that you reference formcontaineropen in the jquery call (this is probably a typo?). The cause is that that a JS code loaded via AJAX will get interpreted (therefore eval() is not needed) but the document ready event will get triggered immediately (which may be before the AJAX loaded content is actually inserted and ready in the document - therefore the submit event may not bind correctly). Instead you need to bind your code to success of the AJAX request, something like this:
main.php:
<html>
Foobar
<div class="formcontainer"></div>
<script src='jquery.js'></script>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontainer").load("form.php", '',
function(responseText, textStatus, XMLHttpRequest) {
onLoaded();
});
});
});
</script>
form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type="text/javascript">
function onLoaded() {
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
};
</script>
My solution is somewhat peculiar but anyhow here it is.
This would be your main.php:
Foobar
<div class="formcontainer"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#addHomeProfile").click(function(){
$(".formcontaineropen").load("form.php", '', function(response){
var res = $(response);
eval($('script', res).html());
});
});
});
</script>
And this is your form.php:
<form id="homeprofile"> <input type="text" name="name" id="name" />
<input type="submit" value="submit" id="submit"></form>
<script type = "text/javascript">
$('#homeprofile').submit(function(e){
e.preventDefault();
alert("form submitted");
$.ajax({ // Starter Ajax Call
type: "POST",
url: 'update.php',
data: $('#homeprofile').serialize(),
});
});
</script>

jQuery PHP passing values within functions vs live clicking?

I'm trying to pass some values through onclick which to me is so much faster. But I need to use some kind of "live" clicking and I was looking into .on() or .delegate(). However, if I do any of those, passing those values within followme() seems a little harder to get. Is there some kind of method that I'm not seeing?
<div class='btn btn-mini follow-btn'
data-status='follow'
onclick="followme(<?php echo $_SESSION['user_auth'].','.$randId;?>)">
Follow
</div>
function followme(iduser_follower,iduser_following)
{
$.ajax({
url: '../follow.php',
type: 'post',
data: 'iduser_follower='+iduser_follower+'&iduser_following='+iduser_following+'&unfollow=1',
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text('Follow');
}
});
}
As you can see, its easier to just pass values from PHP to jQuery... Is there another way?
You can assign more data values, and you know what use is logged in, all you need is to pass who to follow:
<div class='btn btn-mini follow-btn'
data-status='follow'
data-who='<?php echo $randId; ?>'
id='followBTN'>
Follow
</div>
<script>
$('#followBTN').on('click', function(){
$.ajax({
url: '../follow.php',
type: 'post',
data: {
iduser_following: $(this).attr('data-who')
},
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text(data.text);
}
});
});
</script>
You can process $_SESSION['user_auth'] and the status directly from PHP, there is no need for you to pass them in jQuery. Make sure document is ready when you insert on click event.
just use the jquery 'on' event. Attach a new attribute called data-session to the div and then retrieve it using .attr method. You have the example bellow to show you an alert with the data, you just have to substitute it with your code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '#follow-me-button', function(){
alert($(this).attr('data-session'));
})
})
</script>
</head>
<body>
<div id="follow-me-button" class='btn btn-mini follow-btn' data-status='follow' data-session ="MY-SESSION-DATA-FROM-PHP">
Follow
</div>
</body>
</html>

Categories