How to post and update jQuery Serialize using AJAX - php

Please note, I have gone through the below StackOverflow question which is exactly what i need but unfortunately, it isn't posting
Question similar to
My Code -
Test.php
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
<ul id="sortable">
<li id="item-1">Item 1</li>
<li id="item-2">Item 2</li>
</ul>
Span 1: <span id="span"></span>
Span2: <span id="span2"></span>
<script>
$(document).ready(function () {
$('ul').sortable({
axis: 'y',
stop: function (event, ui) {
var data = $(this).sortable('serialize');
$('#span2').text(data);
$.ajax({
data: data,
type: 'POST',
url: 'test2.php',
success: function(data){
$("#span").text(data);
}
});
}
});
});
</script>
Test2.php
<?php
include('../db.php');
$date = $_POST["data"];
$conn = new mysqli ($servername, $dbusername, $dbpassword, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE table SET something = '$something'
WHERE id = '$id'";
if(mysqli_query($conn, $sql)){
echo $date;
}
$conn->close();
?>
Can anyone help me out why the data is not posting to test2.php page
and
how can i sort the table using the data posted to test2.php
Thanks in advance.

For those who came across the same problem here's the solution :
Test.php
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
} );
</script>
<ul id="sortable">
<?php
$q = ' SELECT * FROM temp';
$result = mysqli_query($conn, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<li id='sort_<?php echo $items['id'] ?>'>
<ul style="display:inline-block;"><?php echo $items['name'] ?></ul>
<ul style="display:inline-block;"><?php echo $items['name'] ?></ul>
</li>
<?php
}
}
?>
</ul>
<script>
$(document).ready(function () {
$('#sortable').sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'test2.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
});
$('#sortable').disableSelection();
</script>
Test2.php
<?php
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $conn->prepare(" UPDATE temp SET o_id = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$conn->close();
}
?>
Hope it helps the one in need.

Related

How can I not open a link in jQuery UI

I use jquery-ui (v1.12.1).
https://jqueryui.com/tabs/#ajax (TABS LOAD AJAX)
$( function() {
$("#tabs").tabs({
beforeLoad: function (event, ui) {
$('#preloader').show();
if (ui.tab.data("loaded")) {
event.preventDefault();
$('#preloader').hide();
return;
}
ui.ajaxSettings.cache = false,
ui.panel.html('<img src="assets/ajax-loader.gif"> Loading...'),
ui.jqXHR.success(function() {ui.tab.data( "loaded", true ); $('#preloader').hide();
}),
ui.jqXHR.error(function () {ui.panel.html("Couldn't load Data. Plz Reload Page or Try Again Later."); });
}
});
});
I want to not open the tabs "herf" in the form of a link.
<div class="part" id="tabs">
<ul>
<li>Apple</li>
<li>Samsung</li>
<li>Sony</li>
<li>HTC</li>
</ul>
</div>
What's wrong with the code?
I modified this code.
I have extracted the following code from this site:
http://demo.webslesson.info/jquery-ui-tooltip-with-ajax-php/
But I want to write as the tab of Ajax.
index.php
<?php
include('database_connection.php');
$query = "SELECT * FROM tbl_student ORDER BY student_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="part" id="tabs">
<ul>
<?php
foreach($result as $row)
{
echo '<li><a id="'.$row["student_id"].'" href="#">'.$row["student_name"].'</a></li>';
}
?>
</ul>
</div>
<script>
$(document).ready(function(){
$("#tabs").tabs({
beforeLoad: function (event, ui) {
$('#preloader').show();
$.post('fetch.php', { id:$(this).attr('id') }, function(data){ result(data); });
if (ui.tab.data("loaded")) {
event.preventDefault();
$('#preloader').hide();
return;
}
ui.ajaxSettings.cache = false,
ui.panel.html('<img src="assets/ajax-loader.gif"> Loading...'),
ui.jqXHR.success(function() {ui.tab.data( "loaded", true ); $('#preloader').hide();}),
ui.jqXHR.error(function () {ui.panel.html("Couldn't load Data. Plz Reload Page or Try Again Later."); });
}
});
});
</script>
fetch.php
<?php
if(isset($_POST["id"]))
{
$query = "SELECT * FROM tbl_student WHERE student_id = '".$_POST["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<img src="images/'.$row["image"].'" class="img-thumbnail" />
<h4>Name - '.$row["student_name"].'</h4>
<h4>Phone No. - '.$row["student_phone"].'</h4>
';
}
echo $output;
}
?>
When I click that tab, That text doesn't show.
Is jQueryUI code loaded incorrectly?

Success function doesn't work

I'm trying to delete image box with ajax, my class="box" doesn't disappear when i click delete but my image has been deleted from database and unlink from folder, can anyone see if somethings wrong with my code, thanks in advance!
My code :
<ul>
<?php while ($result = mysql_fetch_array($sql)) { ?>
<li class="box">
<div class="image-box">
<div class="items-image" style="background-image: url(upload/<?php echo $result['img_1']; ?>);"></div>
<p class="error" style="display: none;">Can't delete</p>
<div class="items-footer">
<a class="delete" id="<?php echo $result['img_id']; ?>"><i class="fa fa-trash fa-lg"></i></a>
</div>
</div>
</li>
<?php } ?>
</ul>
$(document).ready(function(){
$(".delete").on('click', function(evt){
var del_id = $(this).attr('id');
var prop_id = "<?php echo $ID; ?>";
$.ajax({
type:'POST',
url:'image_delete.php',
data: ({delete_id : del_id, product_id: prop_id}),
success: function(data) {
if(data == '0') {
$(".error").show();
} else if(data == '1') {
$(this).parents(".box").animate({ backgroundColor: "#003" }, "slow").animate({ opacity: "hide" }, "slow");
}
}
});
});
});
image_upload.php
<?php
include 'connect.php';
$path = "upload/";
if(isset($_POST['delete_id'])){
$delete_id = $_POST['delete_id'];
$product_id = $_POST['product_id'];
$check = mysql_query("SELECT COUNT(img_id) as cnt FROM fm_product_image WHERE p_id_img = '$product_id'") or die(mysql_error());
$getcheck = mysql_fetch_array($check);
if($getcheck['cnt'] == '1') {
echo '0';
} else {
$sql = mysql_query("SELECT img_1 FROM fm_product_image WHERE img_id = '$delete_id'") or die(mysql_error());
$result = mysql_fetch_array($sql);
$delete = $result['img_1'];
$unlink = $path.$delete;
if (unlink($unlink)) {
mysql_query("DELETE fm_product_image FROM fm_product_image WHERE img_id = '$delete_id'") or die(mysql_error());
echo '1';
} else {
echo '0';
}
}
}
?>
Use remove:
$(document).ready(function(){
$(".delete").on('click', function(evt){
var del_id = $(this).attr('id');
var prop_id = "<?php echo $ID; ?>";
var box = $(this).closest(".box");
$.ajax({
type:'POST',
url:'image_delete.php',
data: ({delete_id : del_id, product_id: prop_id}),
success: function(data) {
if(data == '0') {
$(".error").show();
} else if(data == '1') {
box.animate({ backgroundColor: "#003" }, "slow").animate({ opacity: 0 }, "slow");
box.remove();
}
}
});
});
});
note: $(this) refers to the ajax object and opacity is a value from 1 to 0

Isotope .ajax() not work

I appreciate any help you can give me .
I commented I'm doing an infinite scroll through a foreach php and ajax to load the part of the page that I need, the only detail is that isotope use and when I try to load the new content in the isotope in the sucess function ajax , not load anything, the code above the call if the content loads correctly but not within the isotope.
This is the content of foreach
<ul class="projects_wrapper">
<?php if(isset($feed['gallery']['data'])) { ?>
<?php foreach($feed['gallery']['data'] as $k=>$v){ ?>
<li class="mix <?php echo strtolower($v['parent']['title']); ?>">
<div class="project_item">
<img class="project_item_img" src="<?php echo $v['logo']['src-s'];?>" alt="">
<div class="project_item_description">
<h3 class="project_item_title"><?php echo $v['title']; ?></h3>
<p><?php echo $v['description'];?></p>
<a class="button button_view button_project" href="/<?php echo $v['permalink'];?>">View More</a>
</div>
</div>
</li>
<?php } ?>
<?php } ?>
<div id="loadmoreajaxloader" style="display:none;"><center><img src="http://www.iec.ch/img/loading_sliders_2.gif" /></center></div>
</ul>
This is the content for javascript
var $isotope_container = $('.projects_wrapper');
var current = 2;
var catg = 'all';
$(document).ready(function(){
setTimeout(function(){
$isotope_container.isotope({
itemSelector: '.mix'
});
},1000);
// bind filter button click
$('.filter-link').on( 'click', function() {
catg = $(this).data('filter');
$( ".mix" ).filter(catg).css( "background-color", "red" );
$('.filter-link').removeClass('selected');
$(this).addClass('selected');
var filterValue = $( this ).attr('data-filter');
//use filterFn if matches value
//filterValue = filterFns[ filterValue ] || filterValue;
$isotope_container.isotope({ filter: filterValue });
});
/*$('.add_more').on('click',function(){
var elems = getItemElement().add( getItemElement() ).add( getItemElement() );
//console.log(elems);
// append elements to container
$isotope_container.append(elems).isotope('appended',elems);
});*/
$(window).scroll(function()
{
if($(window).scrollTop() == $(document).height() - $(window).height())
{
$('div#loadmoreajaxloader').show();
$.ajax({
url: "/projects",
data: {pag: current, content_only: 1, category: catg},
success: function(data)
{
if(data)
{
//$(".projects_wrapper").append(data);
$(".projects_wrapper").isotope("appended",data);
$('div#loadmoreajaxloader').hide();
current++;
console.log('Me Ejecuto');
}else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
console.log('Termine');
}
}
});
}
});
});
i resolve this for destroy isotope and reconstruct after like this:
function redo_isotope(){
$isotope_container.isotope('destroy');
$isotope_container.isotope({
itemSelector: '.mix'
},1000);
}
var $isotope_container = $('.projects_wrapper');
var current = 2;
var catg = 'all';
$(document).ready(function(){
setTimeout(function(){
$isotope_container.isotope({
itemSelector: '.mix'
});
},1000);
// bind filter button click
$('.filter-link').on( 'click', function() {
catg = $(this).data('filter');
$( ".mix" ).filter(catg).css( "background-color", "red" );
$('.filter-link').removeClass('selected');
$(this).addClass('selected');
var filterValue = $( this ).attr('data-filter');
//use filterFn if matches value
//filterValue = filterFns[ filterValue ] || filterValue;
$isotope_container.isotope({ filter: filterValue });
});
/*$('.add_more').on('click',function(){
var elems = getItemElement().add( getItemElement() ).add( getItemElement() );
//console.log(elems);
// append elements to container
$isotope_container.append(elems).isotope('appended',elems);
});*/
$(window).scroll(function()
{
if($(window).scrollTop() == $(document).height() - $(window).height())
{
$('div#loadmoreajaxloader').show();
$.ajax({
url: "/projects",
method: "get",
data: {pag: current, content_only: 1, category: catg},
success: function(data)
{
if(data)
{
$(".projects_wrapper").append(data);
redo_isotope();
//$(".projects_wrapper").append(data);
$('div#loadmoreajaxloader').hide();
current++;
}else
{
$('div#loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
});
}
});
});

ajax a href onclick get php variable and execute php file

Before I ask this question, I have already referred to the example of this question. However, it seems doesn't work. Without using ajax, I can get my post deleted but after implement ajax, the deleteAtc.php seems to be not working.
My delete page code (delete.php)
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> Delete<br />
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = <?php echo $article['article_id']; ?>;
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id"+id+,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
<div id="success"></div><br />
<?php } ?>
While my deleteAtc.php code:
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
echo "Article deleted";
}
}
?>
What I'm trying to do here is to delete the record without redirect to deleteAtc.php, it will remove out the record and replace Article Deleted
May I know where did I go wrong in ajax side?
Please refer below for updated question
Based on the answer below, here is my updated code:
delete.php
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
deleteAtc.php
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
Somehow, if I delete two record at a time, only the first record echo the result, the second result deleted doesn't echo out the result.
Am wondering, possible to add jquery animation to .show the success message and .hide the record deleted?
First of all IDs are not meant to be duplicated, use class selector instead. Also you could make use of custom data attributes to store the id of the article.
Try
<h4>Select an Article to Delete:</h4>
<div id="message"></div>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span>
Delete<br />
<?php } ?>
Script
<script type="text/javascript">
$(function(){
$('.link').click(function(){
var elem = $(this);
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+elem.attr('data-artid'),
dataType:"json",
success: function(data) {
if(data.success){
elem.hide();
$('#message').html(data.message);
}
}
});
return false;
});
});
</script>
And in server side
<?php
session_start();
include_once('../includes/connection.php');
if (isset($_SESSION['logged_in'])) {
if (isset($_GET['id'])) {
$id = $_GET['id'];
$query = $pdo->prepare('DELETE FROM articles WHERE article_id = ?');
$query->bindValue(1, $id);
$query->execute();
//Also try to handle false conditions or failure
echo json_encode(array('success'=>TRUE,'message'=>"Article deleted"));
}
}
?>
The above script won't work you have to change like below. You are repeating the same identifier function again and again. Keep the jquery script out of foreach loop. You have to add the class property with the article id.
<h4>Select an Article to Delete:</h4>
<?php foreach ($articles as $article) { ?>
<span><?php echo $article['article_title']; ?></span> <a href="#" id="link" class='<?php echo $article['article_id']; ?>' >Delete</a><br />
<div id="success"></div><br />
<?php } ?>
<script type="text/javascript">
$(function(){
$('#link').click(function(){
var id = $(this).prop('class');
$.ajax({
type: "GET",
url: "deleteAtc.php",
data: "id="+id,
sucess: function() {
$('#sucess').html(data);
}
})
return false;
});
});
</script>
You create several links with id="link". ID must be unique.
You have to write
id="link<? echo $article['article_id']; ?>"
as well as
$('#link<? echo $article["article_id"]; ?>').click(function() {...})
<script language="javascript">
$(document).ready(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this record? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "products/delete_record.php",
data: info,
cache: false,
success: function(){
setTimeout(function() {
location.reload('');
}, 1000);
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
//location.reload();
});
});
</script>

Why is this facebook app refreshing endlessly

I kindly request that you help me identify the reason in the code why my app keeps refreshing endlessly. This does not allow me to navigate to other pages, Iam a learner in php and I suspect this could be the issue, help. Could it be a problem with the php arrangement?
Here is the code in index.php
<script type="text/javascript">
$(document).ready(function() {
$('#premium_b').click(function(e) {
e.preventDefault();
$('#tabs').tabs( "select" , 4 );
});
$('#tabs').bind('tabsselect', function(event, ui) {
if (ui.index == 4 )
$('#premium_b').css ('display', 'none');
else
$('#premium_b').css ('display', 'block');
});
});
</script>
<div id="bloc_134" class="li_bloc"><ul class="menu"><li>Home
</li>
<li>Config
</li>
<li>Customize
</li>
<li>Export
</li>
<li>Premium
</li>
<li>Statistics
</li>
<li>Doc
</li>
<li>About
</li>
<li>Other Apps
</li>
<li>FAQ
</li>
</ul>
Upgrade to Premium to get white branding and help us improve your favourite apps! : Click her
<div class="clear"></div>
</div>
</div>
<div id="alerts">
</div>
<div id="zone2" class="li_zone li_x1 li_y2">
<div id="contact_form_about"><div class="zone2">
</div></div>
<div id="contact_form_config"><div class="zone2"><script type="text/javascript">
function refreshApp (url) {
$.get(url, function(data) {
$('*').html(data);
});
}
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#tab_info_form_0').ajaxForm(options);
});
function addToPage() {
var obj = {
method: 'pagetab',
redirect_uri: 'https://apps.facebook.com/mtkenya-dev/?page_id=#contact_form_config',
};
FB.ui(obj);
}
</script>
<script>top.location.href='https://www.facebook.com/dialog/oauth?client_id=461688580525581&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fmtkenya-dev%2F%3Ftab%3Dcontact_form_config&scope=email,manage_pages'</script></div>
<div class="zone2"><script type="text/javascript">
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#contact_form').ajaxForm(options);
$('#customize_css').ajaxForm(options);
});
</script>
<div id="bloc_133" class="li_bloc"><p>Page non trouv?e</p>
</div>
</div>
</div>
<div id="contact_form_css"><div class="zone2"><script type="text/javascript">
function refreshApp (url) {
$.get(url, function(data) {
$('*').html(data);
});
}
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#tab_info_form_0').ajaxForm(options);
});
function addToPage() {
var obj = {
method: 'pagetab',
redirect_uri: 'https://apps.facebook.com/mtkenya-dev/?page_id=#contact_form_css',
};
FB.ui(obj);
}
</script>
<script>top.location.href='https://www.facebook.com/dialog/oauth?client_id=461688580525581&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fmtkenya-dev%2F%3Ftab%3Dcontact_form_css&scope=email,manage_pages'</script></div>
</div>
<div id="contact_form_doc"><div class="zone2"><script type="text/javascript">
$(function() {
$("#bloc_223").tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html( "Couldn't load this tab. We'll try to fix this as soon as possible. ");
}
},
cache: true
});
});
</script>
</div>
</div>
<div id="contact_form_export"><div class="zone2"><script type="text/javascript">
function refreshApp (url) {
$.get(url, function(data) {
$('*').html(data);
});
}
$(document).ready(function() {
var options = {
success: showResponse,
beforeSubmit: disableButton
};
$('#tab_info_form_0').ajaxForm(options);
});
function addToPage() {
var obj = {
method: 'pagetab',
redirect_uri: 'https://apps.facebook.com/mtkenya-dev/?page_id=#contact_form_export',
};
FB.ui(obj);
}
</script>
<script>top.location.href='https://www.facebook.com/dialog/oauth?client_id=461688580525581&redirect_uri=https%3A%2F%2Fapps.facebook.com%2Fmtkenya-dev%2F%3Ftab%3Dcontact_form_export&scope=email,manage_pages'</script></div>
<div id="footer" class="li_zone li_x1 li_y4"> </div>
</div>
</body>
</html>
Well, I see 3 times:
top.location.href=....
without any condition and not in a function call. That would certainly keep your page jumping.

Categories