get method in php not working using bootgrid - javascript

could you help me to solve this problem
i tried to pass the selected value to create query in bootgrid when an item selected in command edit but i have problem in get method this is my code
thanks
<?php
//include("formClient.php");
if (isset($_GET["id"])) { $ClientId = $_GET["id"]; } else { $ClientId=0; };
echo $ClientId;
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script langauge="javascript">
var grid = $("#grid-data").bootgrid({
ajax: true,
ajaxSettings: {
method: "GET",
cache: false
},
url: "clientdata.php",
formatters: {
"commands": function(column, row)
{
return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.ClientId + "\"><span class=\"glyphicon glyphicon-pencil\"></span></button> " +
"<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.ClientId + "\"><span class=\"glyphicon glyphicon-trash\"></span></button>";
}
}
}).on("loaded.rs.jquery.bootgrid", function()
{
/* Executes after data is loaded and rendered */
grid.find(".command-edit").on("click", function(e)
{
var id=$(this).data("row-id");
$.ajax({
url: '<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>',
type: "GET",
data: ({id: id}),
success: function(data){
console.log(data);
alert(data);
}
});
}).end().find(".command-delete").on("click", function(e)
{
//alert("You pressed delete on row: " + $(this).data("row-id"));
var x;
if (confirm("Are you sure to delete this record?") == true) {
x = "OK";
} else {
x = "CANCEL";
}
if (x=="OK"){
//window.location.href="DeleteClient.php?id="+ $(this).data("row-id");
}
});
});
</script>

Related

WordPress ajax load more not working properly?

I'm trying to load more posts via load more button when it will be clicked but its not working properly my first three posts repeat again and again, anyone can help me?
Here is my query which I placed in template file.
$paged=get_query_var('paged') ? get_query_var('paged') : 1;
$the_queryx = new WP_Query(array(
'post_type' => 'exhibitions',
'posts_per_page' => 3,
'post_status' => 'publish',
'order' => 'DESC',
'paged'=>$paged,
'post__not_in'=> array($sticky_post_id),
)
);
$the_max_num_pagesx = $the_queryx->max_num_pages;
if ($the_queryx->have_posts()) {
echo '<div id="post_cat_home" class="row">';
while ($the_queryx->have_posts()) {
$the_queryx->the_post();
get_template_part('loop-templates/content', get_post_format());
}
echo '</div>';
if ($the_max_num_pagesx > 1) {
echo '<div class="load-more-posts" style="width:100%; text-align:center;">
<button id="more_posts_home_exb" data-sticky="' . $sticky_post_id . '" data-pages="' . $the_max_num_pagesx . '" data-pn="'.$paged.'" class="btn more_posts"> </button>
</div>';
}
/* Restore original Post Data */
wp_reset_postdata();
}
And here is my ajax script:
$("#more_posts_home_exb").on("click", function (e) {
e.preventDefault();// When btn is pressed.
$(this).attr("disabled", true); // Disable the button, temp.
var total = $(this).data('pages');
var sticky = $(this).data('sticky');
load_posts_home_exb(total, sticky);
});
//home exhibitions loading
function load_posts_home_exb(total, sticky) {
var pageNumber = 1;
var ppp = 3; // Post per page
var str = '&sticky_ignore=' + sticky + '&pageNumber=' + pageNumber + '&total=' + total + '&action=more_post_home_exb_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function (data) {
var $data = $(data);
pageNumber++;
if ($data.length) {
$("#post_cat_home").append($data);
$("#more_posts_home_exb").attr("disabled", false);
} else {
$("#more_posts_home_exb").attr("disabled", true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
This is my final function file code which function call through via ajax script.
function more_post_home_exb_ajax()
{
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
// $paged = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$sticky_ignore = (isset($_POST['sticky_ignore'])) ? array($_POST['sticky_ignore']) : '';
$paged = $_POST['pageNumber'] +1;
header("Content-Type: text/html");
$loop_template = 'loop-templates/content';
$args = array(
// 'suppress_filters' => true,
'post_type' => 'exhibitions',
'posts_per_page' => $ppp,
'post__not_in' => $sticky_ignore,
'order' => 'DESC',
'post_status' => 'publish',
'paged' => $paged,
);
$loop = new WP_Query($args);
$out = '';
if ($loop->have_posts()) :
while ($loop->have_posts()) : $loop->the_post();
get_template_part($loop_template, get_post_format());
endwhile;
endif;
exit;
}
add_action('wp_ajax_nopriv_more_post_home_exb_ajax', 'more_post_home_exb_ajax');
add_action('wp_ajax_more_post_home_exb_ajax', 'more_post_home_exb_ajax');
This code works but first three posts repeat when button clicked. Thank you!
I've tried some condition in ajax script and it is working now. ;)
//home exhibitions loading
function load_posts_home_exb(total, sticky) {
var pageNumber = 0;
var ppp = 3; // Post per page
pc_x++;
pageNumber = pc_x;
if (total > pageNumber - 1) {
var str = '&sticky_ignore=' + sticky + '&pageNumber=' + pageNumber + '&total=' + total + '&action=more_post_home_exb_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function (data) {
var $data = $(data);
if ($data.length) {
$("#post_cat_home").append($data);
$("#more_posts_home_exb").attr("disabled", false);
} else {
$("#more_posts_home_exb").attr("disabled", true);
}
},
error: function (jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
else{
$("#more_posts_home_exb").hide();
}
return false;
}

PHP not getting first post value

Experts, my php is not showing the first value of the input field but console.log showing correctly
console.log
PHP Output
function summary() {
$(document).ready(function (e) {
var date = $("#dddeliverydate").val();
var soid = $("#sssoid option:selected").val();
var form = $("#formsum").serialize();
console.log(form);
$.ajax({
url: "test.php",
method: "POST",
data: "&date=" + date + "&soid=" + soid + "&form=" + form,
success: function (data) {
var w = window.open("about:blank", "windowname");
w.document.write(data);
},
});
});
}
below is my PHP code
<?php
for ($count = 0; $count < count($_POST['invoiceno']); $count++) {
$data = array(
$invoiceno = $_POST['invoiceno'][$count],
$amount = $_POST['finalamount'][$count],
);
echo "Invoice NO " . $invoiceno . " Amount " . $amount . '<br>';
}
?>
what I am doing wrong need your help thanks in advance
You can change the code as below
function summary() {
$(document).ready(function (e) {
var send_data= $("#formsum").serialize();
send_data += '&date='+$("#dddeliverydate").val();
send_data += '&soid ='+$("#sssoid option:selected").val();
$.ajax({
url: "test.php",
method: "POST",
data: send_data,
success: function (data) {
var w = window.open("about:blank", "windowname");
w.document.write(data);
},
});
});
}

innerHtml on responding ajax method

I am using ajax for sending data to PHP script and set a query in my database. my codes :
HTML script :
<span id="btn_span_<?php echo $user_id ?>">
<?php if ($online == 1) { ?>
<button onclick="update_online(1,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-delete btn btn-status">is active</button>
<?php } elseif ($online == 0) { ?>
<button onclick="update_online(0,<?php echo $user_id; ?>,'btn_span_<?php echo $user_id ?>')" class="btn-custom-services btn btn-status">active
</button>
<?php } ?>
</span>
JAVASCRIPT script :
function update_online(status, id, span_id) {
var settings = {
"async": true,
"crossDomain": true,
"url": "script_edit_status.php?status=" + status + '&id=' + id + '&span_id=' + span_id,
"method": "GET"
};
$.ajax(settings).done(function (response) {
var obj = JSON.parse(response);
var btn = document.getElementById(span_id);
if (obj.status == "1") {
btn.innerHTML = "<button onclick='update_online(1,obj.id,obj.span_id)' class='btn-custom-services btn btn-status'>active</button>";
} else if (obj.status == "0") {
btn.innerHTML = "<button onclick='update_online(0,obj.id,obj.span_id)' class='btn-custom-delete btn btn-status'>is active</button>";
}
});
}
PHP script :
<?php
include_once "../db/connection.php";
$id = $_GET['id'];
$status = $_GET['status'];
$span_id = $_GET['span_id'];
try {
if ($status == 1) {
$sql_edit_status = "update api_user set online=0 where id='$id';";
} elseif ($status == 0) {
$sql_edit_status = "update api_user set online=1 where id='$id';";
}
$conn->query($sql_edit_status);
$status_arr = array(
"id" => $id,
"status" => $status,
"span_id" => $span_id
);
echo json_encode($status_arr);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
it is ok for the first action but when I want to click to button for second time consol shows following error :
Uncaught ReferenceError: obj is not defined
The error is for innerHTML that don't send correctly methods...
Can you help me?
btn.innerHTML = "<button onclick='update_online(0," + obj.id + "," + obj.span_id + ")' class='btn-custom-delete btn btn-status'>is active</button>";

How to get success message after submit on same page - not in new page

My submit success message is displaying in a new page.
How can I have it display in the same page as the submit button?
contact.php
<?php
// configure
$from = 'email';
$sendTo = 'email';
$subject = 'new message';
$fields = array('uname' => 'Jmeno', 'surname' => 'Spolecnost', 'phone' => 'Telefon', 'uemail' => 'Email', 'message' => 'Obsah zpravy'); // array variable name => Text to appear in email
$okMessage = 'success';
$errorMessage = 'error';
// let's do the sending
try
{
$emailText = "Mate novou zpravu z web formulare: example.cz\n=============================\n";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
mail($sendTo, $subject, $emailText, "From: " . $from);
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('location: contact.php?success=1');
echo $encoded;
}
else {
echo $responseArray['message'];
}
?>
JS for submit button:
$(".open4").click(function() {
$('#basicform').validator();
$('#basicform').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#basicform').find('.messages').html(alertBox);
$('#basicform')[0].reset();
}
}
});
return false;
}
})
There is 2 places where can be a problem:
1.PHP code redirects you to a new page (well, page is the same but it will be reloaded with ?success=1 parameter):
header('location: contact.php?success=1');
Try this if you don't want page to be reloaded:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo json_encode($responseArray);
} else {
echo $responseArray['message'];
}
2.HTML form submit event redirects you to new page. You can try to disable default behavior of form for submit event:
$(".open4").click(function() {
$('#basicform').validator();
$('#basicform').on('submit', function (e) {
//prevent Default functionality
e.preventDefault();
var url = "contact.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
$('#basicform').find('.messages').html(alertBox);
$('#basicform')[0].reset();
}
}
});
return false;
});
});

How can I add php variables to this Javascript?

I'm trying to build a simple news page with ajax filters depending on what category the user wants to see. The javascript below connects to a php file and outputs HTML with data from the mysql database. I need to know how to tell the JS to put the data from the "heading" column into a php variable so that it wraps it in the correct href link.
This is the php that creates the heading and the link
$data_fields = '`id`, `heading`, `date`, `copy`, `summary`, `article`, `press_release`, `video`';
$from = '`media`';
$news_result = $db->selectByStrings($data_fields, $from, $where_conditions, $order_by);
$news = $db->getAllRows($news_result);
foreach ($news as $new) {
echo '<h2 class="news"><a class="news" href="'.$base_href.$new['id'].'">'.$new['heading'].'</a></h2>';
}
I somehow need to include this is the separate JS file, making sure it is only applied to data from the heading column.
Javascript
function makeTable(data) {
var tbl_body = "";
$.each(data, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>" + v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
function getEmployeeFilterOptions() {
var opts = [];
$checkboxes.each(function () {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts) {
$.ajax({
type: "POST",
url: "filter3.php",
dataType: 'json',
cache: false,
data: {filterOpts: opts},
success: function (records) {
$('#employees div').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function () {
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
The php file the above connects to:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
$where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
$where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
$where .= " AND video = 1";
}
$sql = $select.$from.$where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I think you are looking for something like this :
var base_href = 'http://www.stackoverflow.com/';
function makeTable(data) {
var tbl_body = "";
$.each(data, function (index, row) {
var tbl_row = "";
$.each(row, function (k, v) {
if(k == 'heading' && 'id' in row) {
v = '<a class="news" href="' + base_href + row.id +'">' + v + '</a>';
}
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
+ v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}

Categories