Jquery load() puts display and opacity in element style - javascript

I have an html that, by AJAX, fetches data from a php file and shows a table with the content ofthe database.
In another file, I try to call load(initial.html) to a div and the code shows up fine, but when I hit the button to retrieve the table, the element style of the div where the tabçe will be written shows up automatically "display: none; opacity: 0". And than in that table I have a tablesorter and it doesn't work.
But if I enter the original page all works, but I can't put it work if I load the html to another file.
Anyone can help me?
Thanks very much
EDIT:
I tried other way, but now the ("#teste").on('submit') doesn't work.
and if I put the code in the main page and forget the load() it works fine. Why is that?
Thank you for the help
Here is the code:
the main page, when o click link_1 I call load() to populate the div id="principal"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Teste </title>
</head>
<link rel="stylesheet" href="css/index.css" />
<link rel="stylesheet" href="css/procura.css" />
<link rel="stylesheet" href="css/theme.blue.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="js/procura.js"></script>
<script type="text/javascript" src="js/jquery.metadata.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.widgets.js"></script>
<body>
<div id="banner-image">
<img src="images/logo.jpg" />
</div>
<div id="banner-content">
<a id="link_1" href="">Procurar Colaborador</a>
<a id="link_2" href="">Confirmação de Colaboradores</a>
</div>
<div id="principal">
</div>
</body>
</html>
The Html that I call called procura.html
<form action="" id="teste" method="post" enctype="multipart/form-data">
<div id="itemRows">
<p>
<select name="tipo_procura[]" >
<option value="" selected></option>
<option value="loja_integracao">Loja de Integração</option>
<option value="nome_completo">Nome</option>
</select>
<input name="valor_procura[]" type="text" maxlength="255" size="50" />
<input onclick="addRow(this.form);" class="form_button" type="button" value="Adicionar Procura" />
</p>
</div>
<input id="submit_button" type="submit" value="Procurar" />
</form>
<div class="result" id="result">
</div>
THE JS file procura.js
$(document).ready(function() {
$("#link_1").click(function(event) {
$("#principal").load("procura.html");
event.preventDefault();
});
$('#teste').on('submit', function(event) {
$.ajax({
url : 'procura_colaborador.php',
data : $(this).serialize(),
type : 'POST',
success : function(data) {
console.log(data);
$("#result").fadeOut('slow', function() {
$(this).html(data);
}).fadeIn("slow");
}
});
event.preventDefault();
});
});
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '"><select name="tipo_procura[]" ><option value="" selected></option><option value="loja_integracao">Loja de Integração</option><option value="nome_completo">Nome</option></select><input name="valor_procura[]" type="text" maxlength="255" size="50" /><input type="button" value="Remover Procura" class="form_button" onclick="removeRow(' + rowNum + ');"></p>';
jQuery('#itemRows').append(row);
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
And the PHP file
$query = "SELECT * FROM colaboradores";
$result = mysqli_query($con, $query) or die(mysqli_error($con));
echo '<table id="tabela_resultados" class="tablesorter-blue">';
echo '<thead><tr><th>Loja de Integração</th><th>Nome</th><th>Telemóvel</th><th>NIF</th><th>Data de Nascimento<th>Nacionalidade</th><th>Acção</th></tr></thead><tbody>';
while ($gear = mysqli_fetch_array($result)) {
echo "<tr><td>";
echo $gear['loja_integracao'];
echo "</td><td>";
echo $gear['nome_completo'];
echo "</td><td>";
echo $gear['num_tlm'];
echo "</td><td>";
echo $gear['num_nif'];
echo "</td><td>";
echo $gear['data_nascimento'];
echo "</td><td>";
echo $gear['nacionalidade'];
echo "</td><td><a href=''>Contrato</a></td></tr>";
}
echo '</tbody></table>';
echo '<script type="text/javascript">$("#tabela_resultados").tablesorter();</script>';

if i understand you correctly
try to change your json function to retrive html data , because you cant't retrive json when you
do echo in php file if you want to retrive your table you must add to json function , dataType: "html"
$('#teste').on('submit', function(event) {
$.ajax({
url : 'procura_colaborador.php',
data : $(this).serialize(),
type : 'POST',
dataType: "html",
success : function(data) {
console.log(data);
$("#result").fadeOut('slow', function() {
$(this).html(data);
}).fadeIn("slow");
}
});
event.preventDefault();
});
});

Related

javascript php AJAX refresh part of a DIV

I was trying to refresh the sidebar class "login" only when a user clicked on the button, however, I am not being able to access the login.php when the user makes the click. When I click on it it's doing nothing and it's refreshing the entire page too.
For what I could understand AJAX needs to be used to refresh only that DIV and the console.log is not being triggered. What I am doing wrong here?
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form action="" method="post">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#login_button").click("login.php", function() {
console.log("login_button clicked");
});
})
</script>
<?php
}
else {
echo '<p>User is logged in</p>';
echo '<form action="" method="post">';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
?>
<script language='javascript'>
$(".login").load( function(event) {
event.preventDefault();
$("#logout_button").click("logout.php", function() {
console.log("logout_button clicked");
});
})
</script>
<?php
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
</body>
Thanks in advance
Your page is refreshing because of action="" on your form tags.
Also you don't need method="POST" on form tag if you are using AJAX to do so. Just remove it!
You may efficiently use ajax request in your scenario.
A suggestion: you could separate your js code out of the PHP code.
so your code will look like this -
<body>
<div id="main-container">
<div class="sidebar" id="sidebar">
<div class="login">
<?php
session_start();
if ( !( isset( $_SESSION['user']) && $_SESSION['user'] != '')) {
echo '<p>User is logged out</p>';
echo '<form id="loginForm">';
echo '<label for="username">Username</label>';
echo '<input type="text" name="username" id="username_input" required/>';
echo '<label for="password">Password</label>';
echo '<input type="text" name="password" id="password_input" required/>';
echo '<input type="submit" value="Login" id="login_button">';
echo '</form>';
} else {
echo '<p>User is logged in</p>';
echo '<form>';
echo '<input type="submit" value="Logout" id="logout_button">';
echo '</form>';
}
?>
</div>
<div class="sideMakers" id="sideMakers">
<p>Markers</p>
</div>
</div>
<div id="map"></div>
</div>
<script src="map.js"></script>
<script type="text/javascript">
$("#login_button").click(function () {
var data = $("#loginForm").serialize();
$.ajax({
type: "POST",
url: 'login.php',
data: data,
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("login_button clicked");
});
$("#logout_button").click(function () {
$.ajax({
type: "POST",
url: 'logout.php',
success: function (data) {
console.log(data);
},
error: function (error) {
console.error(error);
}
});
console.log("logout_button clicked");
});
</script>
</body>

.html file redirect to .php file after clicking a button

<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<!-- View Cart Box Start -->
<?php
if(isset($_SESSION["cart_products"]) && count($_SESSION["cart_products"])>0)
{
echo '<div class="cart-view-table-front" id="view-cart">';
echo '<h3>Your Shopping Cart</h3>';
echo '<form method="post" action="cart_update.php">';
echo '<table width="100%" cellpadding="6" cellspacing="0">';
echo '<tbody>';
$total =0;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];;
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td>Qty <input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /><strong>Remove</strong></td>';
echo '</tr>';
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
echo '<td colspan="4">';
echo '<button type="submit">Update</button>Checkout';
echo '</td>';
echo '</tbody>';
echo '</table>';
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
?>
<!-- View Cart Box End -->
<!-- Products List Start -->
<?php
$results = $mysqli->query("SELECT product_code, product_name, product_desc, product_img, price FROM products ORDER BY id ASC");
if($results){
$products_item = '<ul class="products">';
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
$products_item .= <<<EOT
<li class="product">
<form method="post" action="cart_update.php">
<div class="product-content"><h3><strong>{$obj->product_name}</strong></h3>
<div class="product_img"><img src="product_images/{$obj->product_img}"class="img-responsive img-thumbnail" width="150px" height="150px"></div>
<div class="product-desc">{$obj->product_desc}</div>
<div class="product-info">
<div class="product-price"><strong>
Price {$currency}{$obj->price}
</strong>
</div>
<fieldset>
<label>
<span>Quantity</span>
<input type="text" size="2" maxlength="2" name="product_qty" value="1" />
</label>
</fieldset>
<input type="hidden" name="product_code" value="{$obj->product_code}" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="{$current_url}" />
<div align="center"><button type="submit" class="add_to_cart">Add to cart</button></div>
</div></div>
</form>
</li>
EOT;
}
$products_item .= '</ul>';
echo $products_item;
}
?>
Im developing a ecommerce website. I'm new to AJAX.I don't know how to solve this problem. In index.html i put ajax code to load the index.php inside the html body. And when i click "add to cart" "checkout" "update" button its redirecting to index.php instead staying on index.html.
UPDATED*
<script >
function load_data(){
$.ajax({
url: "index.php",
dataType: 'html',
cache: false,
success: function(data){
$("#mydiv").html(data);
}
});
}
$(document).ready(function(){
load_data();
});
</script>
index.html
index.php
The jQuery $.ajax() function is used to perform an asynchronous HTTP request. It was added to the library a long time ago, existing since version 1.0. The $.ajax() function is what every function discussed in the previously mentioned article calls behind the scene using a preset configuration. The signatures of this function are shown below:
$.ajax(url[, options])
$.ajax([options])
The url parameter is a string containing the URL you want to reach with the Ajax call, while options is an object literal containing the configuration for the Ajax request.
In its first form, this function performs an Ajax request using the url parameter and the options specified in options. In the second form, the URL is specified in the options parameter, or can be omitted in which case the request is made to the current page.
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
In Your case your code should be
$(document).ready(function(){
auto_load();
});
setInterval(auto_load,10000);
function auto_load(){
$.ajax({
url: 'path/to/file/index.php',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
alert(data);
//auto_load(); your code assignment and result goes here
},
type: 'GET'
});
}
and also refer https://www.sitepoint.com/use-jquerys-ajax-function/

submitting a form through ajax for each ID

please guys, have some posts which i outputted from my database and now i want to make a comment form for each post and the form will be submitted through ajax method, but my problem is
the ajax method works for only the first outputted post and the form inserts into the database the mysqli_num_rows($query). ie if mysqli_num_rows($query) is =5, the form inserts into 5 rows in the database.
the remaining outputted forms reloads the page when the submit button is clicked.
This is what I want to achieve:
I want each form to be submitted without reloading.
I want the form to be inserted in only one row for each.
Here is my code:
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>
Change the input type="submit" to type="button" and make ajax on click of button.
For eg.:
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form">
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="button" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $("#my-form").serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
Above code will post the data without refreshing the page.
try this code
<?php
$con = mysqli_connect('localhost', 'root', '') or die ('error');
mysqli_select_db($con, 'test') or die ('error');
$query = mysqli_query($con, "SELECT * FROM testing");
while($sql = mysqli_fetch_array($query)){
$id = $sql['id'];
$post = $sql['post'];
echo "<p>".$id.". ".$post."<br>";
$pop_id = $id."pop";
?>
<style>
.plop {
display:none;
height:200px;
border-bottom:1px solid #000;
}
</style>
<a href="javascript:;" style="float:right
;margin:20px 20px;" onclick="document.getElementById('<?php echo $pop_id; ?>').style.display='block'">comment</a></p><br>
<div id="<?php echo $pop_id; ?>" class="plop">
close
<script type="text/javascript" src="jquery.js"></script>
<form id="my-form-"<?php echo $id; ?>>
<input type="text" id="comment" name="comment" />
<input type="hidden" id="post" name="post" value="<?php echo $id; ?>" />
<input type="submit" id="submit" value="post" />
</form><div id="tutorial"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#my-form-<?php echo $id; ?>').submit(function(e) {
e.preventDefault();
$.ajax({
method: "GET",
url: "dote.php",
data: $(this).serialize(),
beforeSend: function(){
$('#tutorial').html("<img src='progress-dots.gif' />");
},
success: function(status) {
$('#post').val('');
$('#tutorial').html("");
}
});
});
});
</script>
</div>
<?php
}
?>

jQuery Ajax data to same PHP page not working as INTENDED?

I have 22.php that both form and PHP script reside.
Problems;
1) when I submit, result shows below. But duplicates the form.
2) Further entering in the top (above) form, changes the result accordingly.
3) When I enter in the bottom form, then also the result changes accordingly and disappear the bottom from.
What I have tried so far as solutions;
1) removed totally - url: '',
2) replaced to the same page - url: '22.php',
3) replaced to this - var yourData = $(this).serialize();
4) Placed the PHP script just soon after body tag
None of above solve! Please help!
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>
Just place PHP code top and put exit();. Here is your full code:
<?php
if ( isset($_POST['name']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
exit;
}
?>
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
var yourData ='name='+myname+'&age='+myage; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
//url: '22.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
<div id='result'></div>
</body>
</html>

How to fetch data from sql databse when it changes and updatde to div without reloading page

I'm making a simple comment and reply to comment page. I've some code that can post comment and display with ajax, but when I open same page in two browser it works in one browser and in second browser's div it doesn't update comment. My problem is I want if I post from one browser I want another browser also update div.
My index.php file is like below:
<?php
include('config.php');
$to = 1;
$from = 1;
$pak = 1;
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="jquery.min.js"></script>
<script src="process.js"></script>
</head>
<body>
<div id="responds"></div>
<form action="process.php" method="post" name="content_txt" id="contentd">
<input name="from" type="hidden" value="<?php echo $from; ?>" id="from">
<input name="to" type="hidden" value="<?php echo $to; ?>" id="to">
<input name="pak" type="hidden" value="<?php echo $pak; ?>" id="pak">
<textarea id="john" placeholder="whats on your mind ?" name="content"></textarea><br>
<div id="button" style="width:100%;height:33px;font-family:tahoma;">
<div id="update_button">
<input type="submit" value="POST" style="padding:5px;" class="uupdate"/>
</div>
</div>
</form>
<img src="loading.gif" id="LoadingImage" style="display:none" />
</body>
</html>
and process.js file is below
$(document).ready(function() {
//##### send add record Ajax request to process.php #########
$(".uupdate").click(function (e) {
e.preventDefault();
if($("#john").val()==='')
{
alert("Please enter some text!");
return false;
}
$(".uupdate").hide(); //hide submit button
$("#LoadingImage").show(); //show loading image
var to = document.getElementById("to").value;
var from = document.getElementById("from").value;
var pak = document.getElementById("pak").value;
var content = document.getElementById("john").value;
var myData = 'to=' + to + '&from=' + from + '&pak=' + pak + '&content=' + content;
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "process.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$("#responds").append(response);
$("#john").val(''); //empty text field on successful
$(".uupdate").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$(".uupdate").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
});
and process.php file is
<?php
include('config.php');
if(isset($_POST["content"]) && strlen($_POST["content"])>0)
{
$to = $_POST['to'];
$from = $_POST['from'];
$pak = $_POST['pak'];
$content = htmlspecialchars($_POST['content']);
$time=time();
$john = $mysqli->query("INSERT INTO status(eto, content, efrom, pak, created)VALUES('$to', '$content', '$from', '$pak', '$time')");
if($john) {
$my_id = $mysqli->insert_id;
echo '<div id="item_'.$my_id.'">';
echo '<form class="rep_wrapper" method="post" action="reply.php"><input type="text" class="rep_box" id="rep-'.$my_id.'">';
echo '</form>';
echo $content;
echo '</div>';
$mysqli->close(); //close db connection
}else{
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
}
?>
this works fine in single browser but doesn't update
<div id="responds"></div> on second browser.
but when I added following code on index.php
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#responds').load('check.php').fadeIn("slow");
}, 1000);
</script>
this code works on both browser but
it doesn't let me type reply on
<input type="text" class="rep_box" id="rep-'.$my_id.'">
because that js reloads my div every second.
How I can fix this problem?
Anyone please answer.

Categories

Resources