Is there a way to update a database using 1 click?
i.e
echo "<a href='".$wpdb->query(" UPDATE partners SET active='no' WHERE partner_id='$active_partner->partner_id' ")."'>Disable</a>";
You need to react on a click with an ajax function.
i.e.
$('#your_button_id').bind('click', function () {
function_with_ajax();
})
function function_with_ajax() {
$.ajax({
here you could call the update.php script and transmit dynamic data
});
}
<button id="btn-save" type="button">
save
</button>
<script type="text/javascript">
jQuery(document.ready(function ($) {
$("#btn-save").click(
function () {
$.ajax({
type:"POST",
url:"/wp-admin/wp-ajax.php",
data:{
action:"save_data",
data:"data-update",
condition:"data-condition"
},
success:function (response) {
console.log(response);
},
error:function (error) {
console.log(error);
}
})
}
);
}))
</script>
and add to file function:
add_action("wp_ajax_save_data",function ()
{
global $wpdb;
$wpdb->update("your-table",
["your_field" => $_POST['data']]
,["condition-filed"=>$_POST['condition']]);
});
Related
i am sending json object from front-end using ajax call as the following:
<button id="btn">click me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#btn').click(function () {
$.ajax({
url:"/execute",
type:"POST",
contentType: 'json',
data:{
"test":"hello"
},
success:function (data) {
console.log(data.status);
}
});
});
</script>
and i want to decode this json object in laravel, here is my controller code:
public function executeFunction(Request $request){
if($request->header()['content-type'][0] === 'json')
{
Log::info(json_decode($request->getContent(),true));
}
return response()->json(["status"=>"success"]);
}
json_decode returns null here, what might be the problem? Thanks.
I found a solution to this problem, the trick is to use JSON.stringify(data) in front end and json_decode will works fine.
Front end code:
button id="btn">click me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#btn').click(function () {
$x = {
"test":"hello"
};
$.ajax({
url:"/execute",
type:"POST",
contentType: 'application/json',
data:JSON.stringify($x),
success:function (data) {
console.log(data);
}
});
});
</script>
Controller code:
public function executeFunction(Request $request){
if($request->header()['content-type'][0] === 'application/json')
{
Log::info(json_decode($request->getContent())->test);
}
}
If you dump the content, this will be the result:
object(stdClass)#423 (1) {
["test"]=>
string(5) "hello"
}
In my laravel project, i want to refresh my page after an ajax success but my page would refresh after the success. I tried to refresh with laravel redirect in the controller and it didn't work, i have also tried to refresh in the ajax and nothing happened? How do i do this right? How do i do this right?
Controller
if(request()->ajax()) {
//do something
return ['success' => 'successfully done'];
return redirect('admin/all')->with('status','Successfully done!');
JS
<script type="text/javascript">
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.approve_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
location="/admin/all";
}
else if (data['error'])
{
alert(data['error']);
}
else
{
//alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
window.location.href="/your/url" ;
$.each(allVals, function( index, value )
{
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
alert(data['success']);
location="/admin/all";
}
else if (data['error']) {
alert(data['error']);
}
else
{
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
You need to use javascript to refresh the page. You can use location.reload()
if ( data['success'] )
{
alert(data['success']);
location.reload();
}
For those of you still looking for a Solution, This is how you can resolve this issue.
First of all, just return a simple message in your controller.
class SettingsController extends Controller
{
public function __construct()
{
}
public function destroy($id)
{
$user = User::findOrFail($id);
$user->delete();
return 'Record successfully deleted';
}
}
Secondly, Add this code in your javascript file to refresh the page.
setTimeout(function () { document.location.reload(true); }, 5000);
<script type="text/javascript">
function deluser(id)
{
event.preventDefault();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url:"{{ route('settings.destroy','')}}/"+parseInt(id),
method: 'delete',
data:{
id: id,
},
success: function(data)
{
$('#validation-message').append('<div class="alert dark alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span> </button><b>'+data+'</b></div>');
setTimeout(function () { document.location.reload(true); }, 5000);
},
error: function(xhr)
{
$('#validation-message').html('');
$.each(xhr.responseJSON.errors, function(key,value) {
$('#validation-message').append('<div class="alert dark alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span> </button><b>'+value+'</b></div>');
});
}
});
}
</script>
Finally in your HTML.
<!DOCTYPE html>
<html>
<body>
<div class="col-xl-12 form-group" id="validation-message"></div>
<button onclick="deluser('ID_NUMBER_GOES_HERE')">Click me</button>
</body>
</html>
You can try something like this
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
}
this is simple test for ajax and i want to send variable t in my index.php and get data(t) in my process.php and alert digit 15 when i click on button but my problem is not alerting anything
this is my index.php
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}
})
})
})
</script>
<button id="btn">Click!</button>
this is my process.php
<?php
$res = $_POST['t'] + 5;
return $res
?>
Change codes like below:-
1.jQuery:-
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'t':t},
success:function (response) { //remove (
alert(response);
}
});
});
});
2.Php:-
<?php
$res = $_POST['t'] + 5;
echo $res; //use echo rather than return
?>
Reason:-
return is used for returning a value from a function to another piece of PHP code.jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
Note:- After doing These changes, Please check the browser console while running the ajax and see any error happen there? If yes share with us
i) Change your code with following code
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}) //Close brace missing
})
})
});
2) Change return to echo
$(document).ready(function(){
$("#btn").click(function (){
var t = 10;
$.ajax({
type:'post',
url:'process.php',
data:{
t:t
},
success:(function (response) {
alert(response);
// you didnt close )
}) // close of success
})// close of ajax
})// close of click
}); // close of document
Process.php
<?php
$res = $_POST['t'] + 5;
echo $res;
?>
You should add jQuery like this
<script src="jquery-3.2.1.min.js"></script>
If you actually have downloaded and placed the file in the same directory.
You can include in from a CDN if you don't want to download it.
use this instead:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
And fix your JS code: (remove the extra '}' ...)
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'test.php',
data:{
't':t
},
success:(function (response) {
alert(response);
})
})
});
});
Below is my PHP code. I am displaying 3 images, if I Click over any image or product I need to add that product in the popup modal. I am trying to get the product name but I can't. How to solve this issue.
<?php
$i = 0;
while ($row = mysql_fetch_assoc($result))
{
echo"<td style='background-color:#FFFFFF;' height='383'>
<a href='#myModal?productname={$row["productname"]} 'id='burl' role='button' data-productname='{$row["productname"]}' data-toggle='modal' data-target='#myModal'>
<img src='images/{$row["productname"]}.jpg' width='255'/>
</a>
</td>";
}
mysql_free_result($result);
?>
JQuery Codings:
$(document).ready(function () {
$('#myModal').on('shown.bs.modal', function () {
console.log($(this).data('productname'));
})
})
$(this) inside modal event is not your clicked element instance, but the modal itself. You should use relatedTarget like so :
$(document).ready(function () {
$('#myModal').on('shown.bs.modal', function (e) {
// ^--- Add here
var
relatedData = $( e.relatedTarget ),
productname = relatedData.data( 'productname' );
console.log( productname );
})
})
$(document).ready(function ()
{
$('#myPopup').on('show.bs.modal', function (e)
{
var rowid = $(e.relatedTarget).data('productname');
alert(rowid);
$.ajax(
{
type: 'GET',
url: 'fetch_data.php', //Here you will fetch records
data: 'productname=' + rowid, //Pass $id
success: function (data)
{
$('.fetched-data').html(data);//Show fetched data from database
}
});
});
});
This coding solved my problem.
Thanks for all your reply.
I am trying to load content of a URL which is in a href of a Link using AJAX/JQUERY.
For some reason, the AJAX doesn't get executed and when i click on the Link, the URL will open in a new window!
but I need to load the content of URL on the same page that has the AJAX without opening a new window!
this is my current code:
<div id="content"></div>
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
and the AJAX:
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href);
return false;
});
</script>
just to clarify, I do have the jquery lib included in my page header and I am using it for other stuff on the same page. so the issue is not that.
could some please advise on this issue?
Thanks
You need to prevent the default action of the link:
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$("#content").load(this.href);
return false;
});
</script>
You need to do something with your AJAX return :
<script type="text/javascript">
$("#listc").click(function() {
$("#content").load(this.href, function(result){
alert("AJAX done");
});
return false;
});
</script>
You can change the href from the actual page, to a javascript: call. This way, you wouldn't have to concern about the default link redirect.
<a id='listc' class='lisitem' href=javascript:LoadFunction('file.php?id=".$id."'); >".$id."</a>
JS:
function LoadFunction(url) {
$("#content").load(url, function(result){
//something
});
}
Give the following a try:
document.getElementById('listc').addEventListener('click', function() {
$("#content").load(this.href);
return false;
});
UPDATE
Change:
<a id='listc' class='lisitem' href='file.php?id=".$id."' >".$id."</a>
to:
<a id="listc" class="listitem" data-id="<?= $id; ?>" href="#"> <?= $id; ?></a>
And AJAX to:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$('#content').load('file.php?id=' + id);
return false;
}
or:
$(document).delegate('.listitme','click',(function() {
var id = $(this).data('id');
$.post('file.php', {id : id}, function(answer) {
$('#content').html(answer);
});
}
Try something like that :
When you click on the link, do an AJAX call then print the result in your container.
<script type="text/javascript">
$("#listc").click(function(e) {
e.preventDefault();
$.ajax({
url: $(e.currentTarge).attr('href'),
complete: function () {
// remove loading status if neeed
},
success: function (response) {
$("#content").html(response)
},
error: function() {
//manage error here
}
});
});
</script>