I was wondering if its possible to send a query to the database on the beforeunload event.
$(window).on('beforeunload',function() {
console.log('beforeunload called. run query');
});
If so, how would I do it? I need to run a query to insert dynamic values into the database.
You could try this, but beware that the onbeforeunload event is limited for certain browsers..
window.onbeforeunload = mySession;
function mySession(){
$.ajax({
url: "/../../myPHP.php",
async: false,
type: "GET"
});
return "WhatEverMessageYouFeelLike";
}
and your PHP executing query from AJAX handling..
$delete = "DELETE FROM MyTable WHERE id=" .$_SESSION['mySessionVariable'];
// your query..
Use a jQuery AJAX call. Assuming you're POSTing your data, try this:
$.post(
'your/url',
{
your : "Post Vars"
},
function(data) {
// not sure if you'll need to do anything here actually.
},
'json' // or 'html', or whatever you want your return format to be
);
I thinks the best way to use post by jQuery is $.post() method.but u can also use $.ajax
Sample way to use is
jQuery
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
jQuery Ajax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Related
What I want to do is pretty simple. I want to make an AJAX call to a specific html class, so that whenever the html page is loaded, jquery will make an AJAX call to that specific html div class.
For example:
<div class="targeted"></div>
In jquery:
$('.targeted')
I know that the syntax to make an AJAX call is:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
console.log(data);
}
});
But how do I implement this AJAX call to the $('.targeted') whenever the page is loaded?
Thanks
If you mean you want to display the result of the ajax call in the element, you update the element from within the success callback:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
That example assumes
You want to replace the content of the element (rather than adding to it); more options in the jQuery API.
data will be HTML. If it's plain text, use .text(data), not .html(data). If it's structured data, then of course you'll need to do more work to put the information in the desired form.
window.onload = function() {
yourFunction();
};
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
OR Drectly you can pass that method in document ready it will execute automatically
$(document).ready(function(){
//This will execute onload oof your web page what you required
yourFunction();
})
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
For when the page is loaded, you use:
$( document ).ready(function() {
console.log( "ready!" );
});
Inside the document ready, you put your AJAX call. If the result you get is in JSON format, you need to include the dataType as well like this:
$.ajax({
method: "GET",
url: "/api/something",
dataType: "json"
})
.done(function( data ) {
$('.targeted').append(JSON.stringify(data));
});
If the result is not JSON, then you can just append the data.
Also note:
The jqXHR.success(), jqXHR.error() and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail() and jqXHR.always() instead.
Please look at the jQuery documentation.
you can use jquery load like this:
$(".targeted").load('/api/something');
if you want to wait untill after the page is loaded, wrap it with window load like so:
$(window).load(function () {
$(".targeted").load('/api/something');
});
P.S. $(window).load(..) and $(".class").load(url) are two different functions
You can do:
$(function() {
$.ajax({
type: "GET",
url: "/api/something",
})
.done(function(data) {
$('.targeted').text(data);
});
});
I have this working:
jQuery( "input" ).on("blur", function(){
jQuery.ajax({
type: "POST",
url: jQuery(this).closest("form").attr("action"),
data: jQuery(this).closest("form").serialize()
});
});
Unfortunately, the above serializes the entire form, which I don't want. I only want to pass the field that was changed. By the way, I don't have access to the form, just the html. Any help? Could the form.php REQUIRE that all parameters are sent? It is a framework I'm sending this to that processes all the database injections. Any idea why the following won't work?
jQuery( "input" ).on("blur", function(){
jQuery.ajax({
type: "POST",
url: jQuery(this).closest("form").attr("action"),
data: jQuery(this).serialize()
});
});
Use:
jQuery( "input" ).on("blur", function(){
var obj = {};
obj[this.name] = this.value;
jQuery.ajax({
type: "POST",
url: jQuery(this).closest("form").attr("action"),
data: obj
});
});
serialize() function is used for form submit, not just input. Then if you want to pass just current edited input, pass name and value as object to data parameter. jQuery will serialize data in object for you.
Everytime a page loads I need to load text into the CK Editor using JQuery, in order to get data from CK Editor I use
var editor_data = CKEDITOR.instances['editor1'].getData();
now is there a similar function I could use to put the data back into the editor?
I'm using ajax to set the data like this
$.ajax({
type: "POST",
url: "/inc/ajax/basic.php?menu_id="+menu_id+"&info=3",
success: function(msg){
CKEDITOR.instances['editor1'].setData(msg);
}
});
What am I doing wrong
Try this:
CKEDITOR.instances['editor1'].setData(html)
Where 'html' is a string containing content to edit.
Because its not an array then
just replace the instance like this
CKEDITOR.instances.editor1.setData(html)
var editor = CKEDITOR.instances.help_ldesc;
editor.setData('');
$.ajax({
url: urlstr, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{action:"ex_form"}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache:false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
//alert(data);
var data1=data.split("~`");
$('#help_id').val(data1[0]);
$('#help_title').val(data1[1]);
$('#help_sdesc').val(data1[2]);
editor.setData(''+data1[3]);
var edata = editor.getData();
alert(edata);
}
});
Use this code its works for me and (help_ldesc) is my textarea name.
you should use data, and method for sending query string like this:
$(document).ready(function()
{
var querystring="menu_id="+menu_id+"&info=3";
$.ajax({
method: "POST",
url: "/inc/ajax/basic.php",
data:querystring,
success: function(msg)
{
CKEDITOR.instances['editor1'].setData(msg);
}
});
});
var jqxhr = $.get( "file.php", function(data) {
CKEDITOR.instances.idOftextAreaName.setData( data );
alert( "success" );
})
.done(function() {
//alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
// alert( "finished" );
});
CKEDITOR.instances['<%=ckEditor.ClientID%>'].setData(value);
From my experience using inside a function sometimes doesn't work properly. I'll suggest to use in:
$(document).ready(function () {
...
// instance, using default configuration.
CKEDITOR.replace('editor1');
//set data
CKEDITOR.instances['editor1'].setData(data);
...
});
For my script I want to send few data in multiple url's by ajax for multiple php query. So I tried as below which not call ajax waitForRep(). How to do it please?
my Javascript:
var url = ['/server/server2','/server/server'];
var tutid = '<?php echo $tutid; ?>';
var CID = '<?php echo $id; ?>';
function waitForRep(){
$.each(url, function(i,u){
$.ajax({
type: "GET",
cache: false,
data: {
tutid : tutid,
CID : CID
},
timeout:15000,
success: function(data){
// do something with result
setTimeout(waitForRep, 15000 );
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(waitForRep, 15000);
}
});
}
}
$(document).ready(function(){
waitForRep();
});
Your problem is with setTimeOut. It looks like you're trying to call the ajax twice.
If you want to call the second ajax on success, there's no need to iterate through the array. Simply call another ajax on the first ajax success.
Get rid of $.each and do it like this:
$.ajax ({
url: link1
success: function (data){
$.ajax ({
url: link2
});
});
)};
If you're going to send multiple requests to multiple URLs: just send each by the same request, params...
But if you want to handle responses after sending all requests, the first idea in my mind to solve this is Promise, I tried with native Promise and it worked, but if you prefer jQuery, I suggest you have a look on jQuery.when(), this one maybe what you're looking for ( check the deferred part).
Can you please let me know how I can use two Ajax call in one script and avoid conflicts? For example, I have a script like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'POST',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
</script>
Can you please let me know how I can use both methods in the script? Thanks.
Just close DOM ready with }); at the bottom of your script block and you're all set:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'nearest.php',
success: function( resp1 ){
$("#div1").html(resp1);
}
});
$.ajax({
type: 'GET',
url: 'closettime.php',
success: function( resp2 ){
$("#div2").html(resp2);
}
});
});// <------ YOU'RE MISSING THIS
The requests should work fine. And since you're not posting any data to the URLs I might suggest that you use type:'GET'.
Maybe you want to use the $.when method http://api.jquery.com/jquery.when/
jQuery.when understanding
possibly put one in the callback of the other, I don't understand the problem off the top my head. But if div2 is inside div 1 or something you can control the order in that fashion