I have been working on this all weekend and cant get it to work. I can get it working using get but not post. Im using Laravel 4 and jquery.
My JS looks like this:
$('.status').on('click', function(){
var $modal = $('#ajax-modal');
var id = $(this).attr("id");
setTimeout(function(){
$modal.load('../status/'+id, '', function(){
$modal.modal();
});
});
});
which opens a bootstrap modal just fine and loads the status page. On that page, I set a button with an id of the user, and when that is clicked, I call another JS snippet:
$modal.on('click', '.update', function(){
$modal
.find('.modal-body')
.html('<div class="progress progress-striped active"><div class="bar" style="width: 100%;">Processing ...</div></div>');
var PostData = 'UserId='+$(this).attr("id");
$.ajax({
type: "POST",
url: "",
data:PostData,
success: function(msg){
$('.update').prop('disabled', true);
setTimeout(function(){
$modal
.find('.modal-body')
.html('<div class="alert-show-success"><img src="../../../public/assets/img/icons/accept.png" />This user was successfully de-activated!</div>');}, 1500);
},
error: function(){
//alert("failure");
setTimeout(function(){
$modal
.find('.modal-body')
.html('<div class="alert-show-failed"><img src="../../../public/assets/img/icons/failed.fw.png" />There was an error processing this request!</div>');}, 1500);
}
});
});
The modal loads fine, and it finds the status page fine, but nothing actually happens in the controller: (I hard coded the 2 in there to test it.
public function postStatus()
{
DB::table('users')
->where('id', 2)
->update(array('activated' => 0));
}
Not sure what I am missing. Any help is greatly appreciated.
I'd recommend making the changes suggested by #Arda, but I believe your jquery is incorrect. You are setting the key to be unique, and the value to be data.
Try this:
$("a.delete").click(function () {
var id = $(this).attr("id");
$.ajax({
type: 'post',
url: "{{URL::route('user_status')}}",
data: {'id' : id}
});
This requires using a blade template, but that's pretty good practice anyway.
Try like this:
First, make your route named for URLs to be more dynamic:
Route::post('users/status', array('as'='user_status', 'uses'=>'Controllers\UsersController#postStatus');
Then, alter your post jQuery (which I think is the error's source)
$("a.delete").click(function () {
var $id = $(this).attr("id");
$.post('{{URL::route('user_status')}}',
{
id: $id
}
);
});
And your controller method:
public function postStatus()
{
if(Request::ajax()) {
$thisID = Input::get('id');
DB::table('users')
->where('id', $thisID)
->update(array('activated' => 0));
}
}
Didn't try, but should work.
Related
I want to show this jquery variable's value into WordPress shortcode.
I already tried but not working.
Jquery code:
jQuery('.button').on('click', function(){
var post_id = jQuery(this).attr('data-product_id');
//alert(post_id);
});
PHP Code:
echo do_shortcode('[product_page id="36"]');
It's a bit more complicated than you might think. What you have isn't going to work because PHP processes on the server and jQuery runs in the clients browser.
A potential solution could be.. on button click send the variable (post_id) via an AJAX request to the server, this would then process and generate the shortcode html which will then return the html for you to use in your JS.
Below is an example of what I mean...
jQuery
$('.button').on('click', function() {
var $button = $(this);
var post_id = $button.data('product_id');
$button.prop('disabled', true); // Disable button. Prevent multiple clicks
$.ajax({
url: myLocalVariables.ajax,
method: 'post',
data: {
action: 'render-product-shortcode',
id: post_id
}
}).then(function(response) {
if (response.success) {
var $shortcode = $(response.data);
// Do what ever you want with the html here
// For example..
$shortcode.appendTo($('body'));
} else {
alert(response.data || 'Something went wrong');
}
}).always(function() {
$button.prop('disabled', false); // Re-enable the button
});
});
functions.php
// Set local JS variable
add_action('wp_enqueue_scripts', function() {
wp_localize_script('jquery', 'myLocalVariables', [
'ajax' => admin_url('admin-ajax.php')
]);
});
// Handle AJAX request
add_action('wp_ajax_render-product-shortcode', 'render_product_shortcode');
add_action('wp_ajax_nopriv_render-product-shortcode', 'render_product_shortcode');
function render_product_shortcode() {
$product_id = !empty($_POST['id']) ? (int)$_POST['id'] : 0;
if ($product_id) {
return wp_send_json_success( do_shortcode('[product_page id="'.$product_id.'"]') );
}
return wp_send_json_error('No ID in request.');
}
I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.
I'm trying to do detach some data from my database. I'm trying to send 2 different data to my controller with Ajax but couldn't make it. I need the domain_id and the tag_id.
Thats how it looks right now:
#foreach($domains as $domain)
<tr>
<td>
#foreach($domain->tags as $tag)
<span><a href="#" data-tag-id="{{ $tag->id }}"
data-domain-id="{{ $domain->id }}">{{ $tag->name }}</a></span>
#endforeach
</td>
</tr>
#endforeach
Now I have the domain_id and the tag_id in the <a> tag. I'm trying to send both of them to my controller with Ajax, To detach them from my pivot table and thats it.
JS code:
$('a[data-tag-id]').click(function () {
var tag_id = $(this).attr('data-tag-id');
var domain_id = $(this).attr('data-domain-id');
$.ajax({
url: 'detaching',
type: 'GET',
data: {tag_id: tag_id, domain_id: domain_id},
dataType: 'json',
success: function (data) {
console.log('worked!');
}
});
});
Route Code:
Route::get('detaching', 'DomainController#detach2');
Controller Code:
public function detach2()
{
$input = Input::get('all');
$domain = Domains::findOrFail($input['domain_id']);
$domain->tags()->detach($input['tag_id']);
}
This don't work and I don't even know if the gets Ajax code called. I'm trying to console.log() some things out but I don't get anything back. I don't even know if the code reaches the controller function. I don't have much knowledge about Ajax or JS at all. Can someone maybe help me there?
LITTLE UPDATE
I've tried an easy:
$('a[data-tag-id]').click(function () {
console.log('YES');
});
But this haven't worked either, So it doesn't jumps in the click function all I guess.
Try This,
Give a class to your anchor tag like.
{{ $tag->name }}
Change your route to
Route::get('detaching/{tag_id}/{domain_id}', 'DomainController#detach2');
Chnage your controller function to
public function detach2($tag_id, $domain_id)
{
//$input = Input::get('all');
$domain = Domains::findOrFail($domain_id);
$domain->tags()->detach($tag_id);
}
Change your JS file to
(function ($) {
$(document).ready(function () {
$(document).off('click', '.get-link');
$(document).on('click', '.get-link', function () {
var domain_id = $(this).data('domain-id');
var tag_id = $(this).data('tag-id');
$.ajax({
type: 'GET',
url: 'detaching'+ '/' + tag_id + '/' + domain_id + '/',
success: function (data) {
console.log('worked!');
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
})(jQuery);
Sorry for the most simplest of questions but I can't seem to get anything to work. It's the first time I've really played around with AJAX.
I'm developing in codeigniter and I have a link that when clicked runs the controller: photo function: like and allows the logged in user to like the photo then redirects the user back to the photo and displays a slightly different version of the button showing that the user likes the photo.
<?php if ( $like_count > '0' ) { echo $like_count; } ?>
It works fine but I thought it would be cool to replace it with an ajax function so it's more of a fluid motion instead of navigating off the page and then back again.
Any help would be greatly appreciated.
$(".uk-button").click(function(e) {
e.preventDefault();
//Here you can add your ajax
$.ajax({
url: site_url + 'photo/like',
data: {
liked : 1
},
type: 'POST',
dataType: 'json',
async : false,
success: function(success_record) {
console.log(success_record,":success_record");
//You might receive your like count from PHP here
}
});
});
In your success record you would get your PHP record values. Based on that you can increment or decrement count in success function
You can do something like this:
$(document).ready(function()
{
$('.likeLink').on('click', funciton()
{
var obj = $(this);
var id = obj.attr('id'); //anything you want to pass to update your like somewhere
$.ajax(
{
type: 'POST',
url: 'YourFilePathWhereYouWillDoTheLike',
data:
{
id: id,
},
cache: false,
success: function(response)
{
obj.html("You have liked this!");
}
});
return false;
})
})
this is a snippet of a js file>
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList',
type: 'POST',
data: {id: id, userT: usertype},
success: function(html){
$('[data-id='+id+']').parents('tr').remove();
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
as you can see there is an alert message after deleting a user from a list.
I want to refresh the page after ok on alert message is pressed so i added the line>
window.location.reload();
but it's not working, why is this? how can i fix it?
I've been trying to use alternative to this like
location.href = '....';
window.location = '/some/url';
but nothing seems to work!
this is in my admin.php, the code for deleting user from the database:
public function deleteUserFromList(){
if ((isset($_POST['id']) && (isset($_POST['userT'])))){
$rowId = $_POST['id'];
$userType = $_POST['userT'];
$result = array();
if($userType == 'front'){
$front = UserManager::getInstance()->getUser($rowId);
UserManager::getInstance()->deleteItem($front);
}else{
$back = UserBackManager::getInstance()->getUser($rowId);
UserBackManager::getInstance()->deleteItem($back);
}
$result["message"] = "Usuario eliminado";
echo json_encode($result);
}
}
In order to simulate redirect in your browser try to:
Javascript way:
window.location.replace("http://stackoverflow.com");
jQuery way:
var url = "http://stackoverflow.com";
$(location).attr('href',url);
Try this and let me know it it works for you or not.
EDIT:
Inside ajax success. Try to close modal window and try to replace method.
EDIT 2:
Put this part of code inside of your document ready block and check is it fired or not if it is fired it means your form is reloading correctly.
$( window ).unload(function() {
alert( "Bye now!" );
});
Elaborating on #charlietfl's comment, could you try something like this?
Return the count from the ajax script and insert it into your page:
$('#btnYes').on('click', (function() {
var id = $('#myModal').data('id');
var usertype = $('#myModal').data('usert');
$.ajax({
url: '{site_url()}admin/deleteUserFromList', // this returns the user count as data
type: 'POST',
data: {id: id, userT: usertype},
success: function(data){
$('[data-id='+id+']').parents('tr').remove();
$('#countDisplayElement').text(data); // insert new count into current page
$('#myModal').modal('hide');
alert('usuario borrado');
window.location.reload();
}
});
return false;
}));
That would eliminate the need to refresh the page entirely and be a bit more friendly to use.