Running an javascript function before an ajax call - javascript

I want to run the first ajax call when it has completed run the function "saveToFile()" and after that has been completed run the second ajax call. Doesn't seem to work as coded. I'm fairly new to ajax so am struggling a little with this one.
// save composition to database
$.ajax({
type: "POST",
url: "_inc/save_to_db.php",
data: {jsonStr: canvasStr},
success: function(data) {
// this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
saveToFile();
$.ajax({
type: "POST".
url: "_inc/generate_thumbnail.php",
data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
});
}
});

Works for me: http://jsbin.com/upujur/2/edit
The problem might be with the dot instead of comma in this line:
type: "POST".
Are you using a JavaScript console like FireBug or Developer Tools to debug your program?

You could make the saveToFile function take as parameter a callback which will be executed once the AJAX call it performs is finished. For example:
$.ajax({
type: "POST",
url: "_inc/save_to_db.php",
data: {jsonStr: canvasStr},
success: function(data) {
// this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
saveToFile(function(result) {
$.ajax({
type: "POST",
url: "_inc/generate_thumbnail.php",
data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
});
});
}
});
and your saveToFile function may now look like that:
function saveToFile(successCallback) {
$.ajax({
url: ...,
type: ...,
data: ...,
success: successCallback
});
}

Related

How to get return text from php file with ajax?

I am making a call with ajax to a php file. All I want to do is get a value back from the php file to test it with javascript. I have tried many many things, but can only get undefined (from the below code).
How can I get "hello" returned from the php file to my javascript?
jQuery.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = jQuery(data).html();
alert(the_returned_string)
}
});
The PHP file:
<?php
echo '<div id="id-query-result>"';
echo "hello";
echo "</div>";
You can change the code inside PHP like this
<?php
$queryResult = '<div id="id-query-result">hello</div>';
echo json_encode(['html' => $queryResult]);
Then, change your ajax call
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
dataType: 'json',
success: function(data) {
var the_returned_string = data.html;
alert(the_returned_string);
}
});
$.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
$('body').append(data);
var text = $('#id-query-result').text();
alert(text);
$('#id-query-result').remove()
}
});
Why not just append the HTML response of your php file then get the text accordingly. You can then remove it after.
There are two changes to be done:
Change the type to "GET" since you directly call the PHP File.
remove the wrapped jQuery method inside the success function and add .html as an attribute
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = data.html
alert(the_returned_string)
}
});

Ajax Successfully Receive Data From Server, But Failed Sending It

I have this ajax works fine :
$.ajax({
url: "../../../controller/ctrl.test.php",
success:function(expirytime){
alert(expirytime);
}
});
but when I need to send data to server and add this lines, then it won't alert the expirytime again :
$.ajax({
url: "../../../controller/ctrl.test.php",
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json',
success:function(expirytime){
alert(expirytime);
}
});
please note that data is json data. and I have it on above those codes. so, it's not empty. I just wondering why by adding POST mechanism into my first ajax cause alert(expirytime); stop working?
what's wrong with my code? thank you
update : for this test purpose, there's nothing in PHP file, but just echo-ing date and time
<?php
$date = '2016/04/30 00:00:00';
echo $date;
?>
Since you have dataType: 'json', jQuery expects the response from PHP to be valid JSON. But
echo $date;
is not returning valid JSON. When jQuery calls JSON.parse() on that response it gets an error, so the success function is not called.
Change that line to:
echo json_encode($date);
and it should work. Or change dataType: 'json' to dataType: 'text'.
Try This
$.ajax({
url: "../../../controller/ctrl.test.php",
type: 'POST',
data: { JSON.stringify(data) },
dataType: 'json',
success:function(expirytime){
alert(expirytime);
}
});

How to run another JS method from longPolling?

How in method with longPolling:
function getNewMessagesLong() {
pollingFishingStarts();
$request = $.ajax({
type: 'POST',
url: "listenMessageLong",
data: lastIncomingMessageLongJson,
dataType: 'json',
success: function(data) {
}, complete: getNewMessagesLong})
}
on complete to run another method?:
function pollingFishingEnds() {
document.getElementById("fishing-end").src = "resources/img/fishing-end.png";
document.getElementById("fishing-start").src = "resources/img/fishing-start-empty.png";
}
With the example you posted, you could simply do something like this, adding an anonymous function that calls your "ends" method AND restarts your polling method:
function getNewMessagesLong() {
pollingFishingStarts();
$request = $.ajax({
type: 'POST',
url: "listenMessageLong",
data: lastIncomingMessageLongJson,
dataType: 'json',
success: function(data) {
},
complete: function() {
getNewMessagesLong();
pollingFishingEnds();
}
});
}
You could also change up to a window.setInterval() long-polling paradigm that would allow you to use your complete option to set your actual end method, rather than hijacking it for long-polling.
I'm assuming here that you want to call the "end" state code after the first round completion. Otherwise, there's literally no end to your polling, unless you have some server message to terminate, in which case you need to post that code for additional information.

universal jquery ajax call function

wondering is there any kind of global (universal) one function for calling ajax function..
for example i have lots of similar call like this:
$.ajax({
url: some_url_address,
type: 'post',
data: $('#form').serialize(),
dataType: 'html',
success: function(data){
alert('success');
}
});
and i would like to make it something like
callAjax('my_url', 'post', {some_data}, 'alert("success")');
and in javascript file:
function callAjax(url, type, data, successFunction, errorFunction, beforeFunction){
$.ajax({
url: url,
type: type,
data: data,
dataType: 'html',
beforeSend: function(){
beforeFunction;
},
success: function(){
successFunction;
}
error: function(){
errorFunction;
}
});
}
that in my page from where i'm calling that function it would return results from before, error, success, etc.. :)
Just install webpack by npm install.
And in the input field write data-ajaxify='true'
Also include the npm js and css file.
<input type='test' data-ajaxify='true' data-url='/someurl' data-method='post'>

PHP -Ajax : send response data to php to convert jsonp to php array

$.ajax({
type: "GET",
url:"http://localhost:8080/privateTraining/getTrainingsJson",
data: { ListID: '1'},
dataType: "jsonp",
success: function(data)
{
anotherFunction(data);
}
});
function anotherFunction(data){
$.ajax({
type:"POST",
data:data,
url:"anotherFile.php,
success: function(data)
{
//do something elese;
}
});
}
here first one is cross domain ajax call.
here i want to send the result (jasonp response) of first ajax call to second ajax call to a php file .. where i need to convert jsonp data to php array .
is it possible to do like this?

Categories