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).
Related
I'm trying to display the result of a php function that I call in AJAX into a div 'TARGET'. I can't understand what I am doing wrong....
MY HTML
<div id="TARGET"></div>
MY AJAX
$(document).on('click', '.actualiser_btn', function(){
var id_contenu = $(this).attr("id");
$.ajax({
url:"/ajax-script.php",
method:"POST",
data:{id_contenu:id_contenu},
dataType:"json",
success:function(data)
{
$('#TARGET').html(<?php $return ?>);
}
})
});
MY AJAX SCRIPT
...
$return = wysiwyg( $_POST['id_contenu'],'basique') ;
echo $return ;
?>
When I click on the script in my network debugger I exactly see the script that I want so I conclude my function works well... What Am I doing wrong?
You have to use data to update the html like $('#TARGET').html(data.key);
$(document).on('click', '.actualiser_btn', function(){
var id_contenu = $(this).attr("id");
$.ajax({
url:"/ajax-script.php",
method:"POST",
data:{id_contenu:id_contenu},
dataType:"json",
success:function(data)
{
$('#TARGET').html(data.key); /*Since data is json, you might want to access the right key/value to set as html*/
}
})
});
http://api.jquery.com/jquery.ajax/
success function
Type: Function( Anything data, String textStatus, jqXHR jqXHR ) A
function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
The first parameter of the success function is the data received from the backend.
Replace $('#TARGET').html(<?php $return ?>); with $('#TARGET').html( data );
as shown below.
Also note that the dataType option in the ajax request expects a JSON response therefore, ensure that your response is in a JSON format. Alternatively, remove the option.
$(document).on('click', '.actualiser_btn', function(){
var id_contenu = $(this).attr("id");
$.ajax({
url:"/ajax-script.php",
method:"POST",
data:{id_contenu:id_contenu},
dataType:"json",
success:function(data, status){
$('#TARGET').html( data );
}
});
});
I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.
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
});
I'm using onload() and ajax to get the array from php, but it didnt work. The html page should be able to get the array from n1.php and alert("GOOD"), but it's not giving any response, not even alerting GOOD or BAD so i really dont know what's wrong with the code. How can I fix this??
n1.html:
<!DOCTYPE html>
<html>
<body onload="getArr();">
here
</body>
<script type="text/javascript">
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
}
</script></html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
The request must contains the type of request. Also the dataType refers on data you are going to send,as long as you don't send any data, it does not need here.
Try this:
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array = $.parseJSON(json_data);
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Try this
$.ajax({
url: "n1.php",
dataType: 'json',
success: function(json_data){
var data_array = json_data; // Do not parse json_data because dataType is 'json'
var rec = data_array[0];
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Now, two things to note here:
You have not passed HTTP Method in the ajax but by default it is GET as mentioned here in jQuery AJAX docs. Please pass appropriate method type if it is not GET.
Since you have sent dataType as 'json', you need not parse json received in the response in success handler.
I have the following code for requesting data from a mysql database:
jquery/javascript:
ajaxGet = function (url) {
var result = $.ajax({
url:url,
type:"POST",
data:{action:'call_this'},
dataType: 'json',
success:function(data) {
}
});
return result;
}
php:
<?php
if($_POST['action'] == 'call_this') {
// call waypoint search
include ('link.php');
$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);
$wptdata=array();
while($line = mysqli_fetch_assoc($result)){
$wptdata[] = $line;
};
mysqli_close($link);
echo json_encode($wptdata);
};
?>
To get the data as a javascript array, I would like to be able to say something like this:
wpdata=ajaxGet('datacall.php');
Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.
Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.
The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!
function ajaxGet(url) {
return $.ajax({
url: url,
type: "POST",
data: {
action: 'call_this'
},
dataType: 'json'
});
}
ajaxGet().done(function(wpdata) {
// use wpdata here
});