Ajax call delete cakephp - html

I'm trying to use ajax delete to delete records that, when clicked, confirms before sending the request.
the record is deleted and it work but the problem is after deleting nothing change in the view until after I reload the page manually.
I want to show the result in view just after click "ok" in the dialog
my ajax code :
$(document).ready(function() {
if($('.confirm_delete').length) {
$('.confirm_delete').click(function(){
var result = confirm('Are you sure you want to delete this?');
$('#flashMessage').fadeOut();
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
}
});
}
return false;
});
}
});
in view :
echo $this->Js->link('Delete', array('controller' => 'publications', 'action'=>'delete', $publication['Publication']['id']),
array('escape' => false, 'class'=>'confirm_delete'));

$(document).ready(function(){
if($('.confirm_delete').length) {
$id=$(this).attr('id');
$('.confirm_delete').click(function(){
var result = confirm('Are you sure you want to delete this?');
$('#flashMessage').fadeOut();
if(result) {
$.ajax({
type:"POST",
url:$(this).attr('href'),
data:"ajax=1",
dataType: "json",
success:function(response){
}
});
$('#row'+$id).remove();
}
return false;
});
}
});
For some reason the $(this).attr('id') does not work ... how to get id of the element selected to remove it
I have on my view :
<div class="box_detail" id="row<?php echo $publication['Publication']['id']; ?>">

This is not a CakePHP problem but a JS problem only. If yor delete callback was successful without any error returned you have to remove the related content from the DOM tree. Using jquery this can be done by calling remove() on any selector you want to remove.

Related

How can we use the "GET" method for a form, but still hide URL parameters?

So, I have a form that contains a textarea field and a submit button:
<form class="popupForPosting">
<textarea id="postContent" name="postContent" rows="8" cols="80" class="postContent" placeholder="What's going on, <?php echo $firstname ?>?"></textarea>
<button id="pos" class="pos" onclick="makePost()">Post</button>
</form>
When I click my submit button, the call gets sent to my AJAX as a request and my postContent (whatever is entered in the textarea field) gets shown in the URL. I don't want this to happen.
Now, I don't want to use the POST method for this form. I want to use the GET method, but still hide the parameters displayed in the URL. According to the information and details given, how can I accomplish this?
EDIT:
<script>
const makePost(form) {
const text = form.postContent.value;
function makePost() {
var postContent = $("#postContent").val();
if (postContent.length > 0) {
jQuery.ajax({
url:"yourposts.php",
data:{
postContent: postContent
},
type:"POST",
success:function(data){
if (data == "success") {
$(".textpostFormat").html(postContent);
}
}
});
}
}
};
document.querySelector(".popupForPosting").addEventListener("submit",function(e) {
e.preventDefault();
makePost(this); // passing the form
});
</script>
Simplest answer for you
Change the form tag: action="yourposts.php" method="post"
Give the submit button an name and a value and remove the click handler
move your post.php to the top of the page
add a test isset($_POST["submitButtonName"])
empty the form field before returning the page
remove all ajax related script
Now the page will save the data if the button is clicked and not if the page is just loaded. The test for content will handler the reload
Ajax answer
Using AJAX does not show the data in the URL - just
remove onclick="makePost()"
use the submit event of the form instead of the click event of a submit button and use event.preventDefault():
NOTE I have wrapped in a load event handler
$(function() { // when form is available
$(".popupForPosting").on("submit", function(e) {
e.preventDefault(); // always prevent submit
const postContent = $("#postContent").val().trim();
$('#noText').css({visibility: postContent === "" ? "visible" : "hidden" })
$("#popUp").toggle(postContent==="")
if (postContent) {
$.ajax({
url: "yourposts.php",
data: {
postContent: postContent
},
type: "POST",
success: function(data) {
console.log(data)
if (data == "success") {
$(".textpostFormat").html(postContent);
}
}
});
}
});
});

Can i know what is the error in these lines of code

Code:
var formdate:{name:$("#name").val(), date:$("date").value
}
$.ajax({
type : "POST",
contentType : "application/json",
url : "localhost:8080/company/addrelease",
data : JSON.stringify(formdata),
dataType : 'json',
success : function(result) {
if(result.status == "Done"){
console.log("value added");
}else{
console.log("not done");
}
},
error : function(e) {
console.log("error");
}
});
Question
This is the line of code in which i'm trying to call my rest Api with ajax api call.
But it goes till the ajax statement but soon after that it gets refreshed and stops working and again. Any suggestions to get through this would be appreciated.
soon after that it gets refreshed
My guess is that you've placed this code inside form submit handler:
function onSubmit(e) {
e.preventDefault();
// your code
}
<form onsubmit={onSubmit}>
...
<button type="submit" />
</form>
If you don't call e.preventDefault() the form will try to submit itself, making a http request to url specified in the form. If no url attribute is specified, it will submit to the current url e.g. the page will refresh. Http request called by you (ajax) is async action, and you don't see it working because default submit action happens before that.

How to fetch a specific div id from an html file through ajax

I have two html files called index.html & video.html
video.html holds coding like:
<div id="video">
<iframe src="http://www.youtube.com/embed/tJFUqjsBGU4?html5=1" width=500 height=500></iframe>
</div>
I want the above mentioned code to be crawled from video.html page from index.html
I can't use any back-end coding like php or .net
Is there any way to do using Ajax?
Try this...
$.ajax({
url: 'video.html',
success: function(data) {
mitem=$(data).filter('#video');
$(selector).html(mitem); //then put the video element into an html selector that is on your page.
}
});
For sure,send an ajax call.
$.ajax({
url: 'video.html',
success: function(data) {
data=$(data).find('div#video');
//do something
}
});
Yep, this is a perfect use case for ajax. When you make the $.ajax() request to your video.html page, you can then treat the response similar to the way you'd treat the existing DOM.
For example, you'd start the request by specifying the URI in the the following way:
$.ajax({
url: 'video.html'
})
You want to make sure that request succeeds. Luckily jQuery will handle this for you with the .done callback:
$.ajax({
url: "video.html",
}).done(function ( data ) {});
Now it's just a matter of using your data object in a way similar to the way you'd use any other jQuery object. I'd recommend the .find() method.
$.ajax({
url: "video.html",
}).done(function ( data ) {
$(data).find('#video'));
}
});
Since you mentioned crawl, I assume there is the possibility of multiple pages. The following loads pages from an array of urls, and stores the successful loads into results. It decrements remainingUrls (which could be useful for updating a progressbar) on each load (complete is called after success or error), and can call a method after all pages have been processed (!remainingUrls).
If this is overkill, just use the $.ajax part and replace myUrls[i] with video.html. I sepecify the type only because I ran into a case where another script changed the default type of ajax to POST. If you're loading dynamic pages like php or aspx, then the cache property might also be helpful if you're going to call this multiple times per session.
var myUrls = ['video1.html', 'video2.html', 'fail.html'],
results = [],
remainingUrls;
$(document).ready(function () {
remainingUrls = myUrls.length;
for (var i = 0, il = myUrls.length; i < il; i++) {
$.ajax({
url: myUrls[i],
type: 'get', // somebody might override ajax defaults
cache: 'false', // only if you're getting dynamic pages
success: function (data) {
console.log('success');
results.push(data);
},
error: function () {
console.log('fail');
},
complete: function() {
remainingUrls--;
if (!remainingUrls) {
// handle completed crawl
console.log('done');
}
}
});
}
});
not tested, but should be something similair to this: https://stackoverflow.com/a/3535356/1059828
var xhr= new XMLHttpRequest();
xhr.open('GET', 'index.html', true);
xhr.onreadystatechange= function() {
if (this.readyState!==4) return;
if (this.status!==200) return; // or whatever error handling you want
document.getElementsByTagName('html').innerHTML= this.responseText;
};
xhr.send();

Data not getting saved using JQuery.ajax

I want to save data from Textbox on Button click. I am using JQuery AJAX for this task like below. Please note that I made this tags inside theme function.
function theme_user_post_block($vars)
{
$themeUserCommentInput ='';
$themeUserCommentInput .= '<textarea id="txt_1"rows="1" cols="50"></textarea>';
$themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center"
class="btnPostComment" id="btn_1" />'
return $themeUserCommentInput;
}
This able to show me Textbox and Button inside the page. Now here is my JS code:-
(function($)
{
Drupal.behaviors.PostComment= {
attach: function (context, settings) {
$('.btnPostComment', context).click(function (event) {
var post = "&newcomment=Comment1&logid=log1";
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
data: post,
success: function (data) { alert(data); },
error: function(jqXHR, textStatus, errorThrown){alert(textStatus +
errorThrown);}
});
});
}
}
})(jQuery);
Next I create a Menu Page with URL Name as follows:-
function postcomment_menu(){
$items=array();
$items['postcomment']=array(
'title'=>t(''),
'type'=> MENU_CALLBACK,
'page callback' => 'user_comment_post',
'access arguments' => array('access content'),
);
return $items;
}
function user_comment_post(){
global $user;
$cid = db_insert('user_comment')
->fields(array(
'comment_user_id' => $user->uid,
'reference_id' => $_POST['logid'],
'comment_desc'=>$_POST['newcomment'],
'createdon'=>REQUEST_TIME,
))
->execute();
if($cid!=0)
{
//GetUserComments($i);
drupal_json_output("success");
}
}
So I have done all things that is required for jQuery+Ajax Submit functionality. When I press "Post Comment" button it gives me error in alert says "errorundefined". The alert shows as a result of error inside the jQuery.AJAX function. Also the custom menu callback is also not getting called.
post the data as object...and make sure your post url is correct.. the url doesn't looks correct
var post = {newcomment: 'Comment1',logid:'log1'};
I came to end of this problem. I dont know what might be the resolution or root cause but I end up solving this problem. I meagre add one line(async: false) in my jQuery.ajax function and everything works perfectly. Please see the code below:
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
async: false,
data: post,
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + errorThrown);
}
});
If anyone have any knowledge as what this line will do then please share with us.

Firing a javascript function from a dynamically created button

Updated code and issue:
I am creating a test harness for my RPC server. Currently it consists of a page which immeadiately fires off an AJAX request to retrieve all functions on the server. Once that is returned it creates a list of buttons so I can click to test. Eventually I will add dialog boxes to test parameter passing to the functions but currently I want to just fire off the basic request when I click the button. The issue I am seeing is that the onclick function is always firing the last function in the list presumably because when the click is fired key is set to the last value in the array. I thought to pass button.innerHTML value but that too suffers that the last button.innerHTML is that of the final key.
What do I need to do to fire off the action correctly?
Here is the business end of the code:
$(document).ready(function() {
$.jsonRPC.setup({
endPoint: '//api.localhost/index.php'
});
$.jsonRPC.request('getExampleData', {
params: [],
success: function(result) {
for (var key in result.result) {
console.log(key+' => '+result.result[key]);
var button = document.createElement('button');
button.innerHTML = result.result[key];
button.onclick = function() { callRPCFunction(result.result[key]); return false; }
var foo = document.getElementById("page");
foo.appendChild(button);
}
},
error: function(result) {
console.log(result);
}
});
});
function callRPCFunction(target) {
$.jsonRPC.request(target, {
params: [],
success: function(result) {
console.log(result);
},
error: function(result) {
console.log(result);
}
});
}
Assignment to element.onClick will not work until the element is added to the DOM. You may call element.onClick(callRPCFunction(result.result[key])); after foo.appendChild(element);. That might work!
You may use jQuery's live() here, it was created for these purposes:
$(element).live('click', callRPCFunction(result.result[key])