How would I send a POST Request via Ajax? - html

I have a php page, Post.php it recieves the POST's Action, and that has two functions. Insert, and Update.Now how would I go about posting INSERT with this Ajax code. The code posts update fine but is doesnt post insert at all.
$(document).ready(function(){
//global vars var inputUser =
$("#nick"); var inputMessage =
$("#message"); var loading =
$("#loading"); var messageList =
$(".content > ul"); //functions
function updateShoutbox(){ //just
for the fade effect
messageList.hide();
loading.fadeIn(); //send the post to shoutbox.php
$.ajax({ type:
"POST", url: "Shoutbox.php", data:
"action=update",complete:
function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000); } }); }
function checkForm(){
if(inputUser.attr("value") &&
inputMessage.attr("value"))return
true; else return false; }
//Load for the first time the
shoutbox data updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){ var nick =
inputUser.attr("value"); var
message = inputMessage.attr("value");
//we deactivate submit button while
sending $("#send").attr({
disabled:true, value:"Sending..." });
$("#send").blur(); //send the
post to shoutbox.php $.ajax({
type: "POST", url: "Shoutbox.php", data: "action=insert&nick=" + nick +
"&message=" + message,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Shout it!" });
}
}); } else alert("Please fill all fields!"); //we prevent the
refresh of the page after submitting
the form return false; }); });*emphasized text*
List item

Your second call to $.ajax uses type: "GET" whereas the first uses type: "POST". Try switching the second one to "POST".

Related

Data download Ajax in Ajax

I'm catching data from Database with Ajax.
In the second Ajax request I try to put the variables from first Ajax request to the new DOM elements from second request but there the variables have same value from last array possition.
I have no idea why .
unfortunately I didn't find the information about that.
a simple example:
//Firt ajax request
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "connect/get-fistinformations.php",
data: {
folder_type:folder_type
},
dataType: "json",
for(var first_key in json){
var info = json[first_key];
//If I put there some alert - alert('some_alert'); - the rest of the code works fine
//Catching Data with Json - working correctly
var folder_id = info[0];
var folder_name = info[1];
var folder_date = info[2];
folder_id;
//Second ajax request
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: 'connect/get-secondinformations.php',
data: {
folder_type:folder_type,
folder_id:folder_id
},
dataType: 'json',
success: function(json){
for(var s_key in json){
var second_info = json[s_key];
//Catching more data from other Data table - working correclty
var count = second_info[0];
var route = second_info[1];
var distance = second_info[2];
var price = second_info[3];
var price_per_km = +(price) / (+(route) + +(distance));
//Without the alert from the firt ajax request
//There inside new elements I try to put variable from first Ajax catching (folder_id, folder_name,folder_date)
//But every time when I add new elemets to DOM, these three variables have same value - from last arrray position
//For example folder_id = '50' | folder_name = 'Some folder name' | folder_date = '2020-07-04'
//New elements for DOM
if(count>0){
var full_line_folder = '<div class="full-line-folder folder">'+
'<i class="some-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono: '+folder_date+'<br />Pozycje: '+count+'<br />Dystans: '+route+'km<br />Stawka: '+price_per_km+' €/km<br />Puste kilometry: '+distance+'km</span>'+
'<input type="radio" name="folderid" value="'+folder_id+'" style="display:none;" checked/>'+
'</div>';
$(full_line_folder).appendTo(point);
}else{
var empty_line_folder = '<div class="empty-line-folder folder">'+
'<i class="empty-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono:'+folder_date+'<br />Pozycje: 0<br />Dystans: 0km<br />Stawka: 0 €/km<br />Puste kilometry: 0km</span>'+
'<input type="radio" name="folderid" value="'+folder_id +'" style="display:none;" checked/>'+
'</div>';
$(empty_line_folder).appendTo(point);
}
}
},
error: function(note){
alert('error');
}
});
}
},
error: function(note){
alert('error');
}
});
The problem is that your first loop proceeds to the next iteration before the data arrives for the ajax request it makes. Mostly, by the time your first ajax response arrives, the loop is already gone and any external variables you try access will have their last values.
There are many workarounds for this. I don't think discussion all that is the scope of this answer.
Your options:
Use closures correctly.
Serialize the requests by using async/await

How to update video playing current time using ajax in laravel

<script>
var vid = document.getElementById("player");
$(function() {
var timeout;
$("#player").on("playing pause", function(e) {
// Save reference
var v = this
// Clear previous timeout, if any
clearTimeout(timeout)
// Call immediately if paused or when started
performaction(v.currentTime, v.duration)
// Set up interval to fire every 5 seconds
if (e.type === "playing") {
timeout = setInterval(function() {
performaction(v.currentTime, v.duration)
}, 5000)
}
})
function performaction(currentTime, duration) {
console.log(currentTime);
console.log(' ajax action goes here');
var data = { pause_time : currentTime };
$.ajax({
type: "POST",
url: '/instructor/promo_video/84',
data: data,
success: function() {
console.log("Value added");
}
})
}
})
</script>
In my database I have a video table in which I have a column name as pause_time.
Now if I use this js code for video current playing time then I am getting the time after 5 seconds interval in the console.
I want to send this time to the database using ajax in laravel. And also how to take the currentTime value in the controller.
Thanks in Advance!!
If you created a video table, then you should make a video model:
php artisan make:model Video
When you're using POST methods in frontend, you need to pass a CSRF token too.
const data = {
_token: YOUR_TOKEN,
pause_time : currentTime,
};
To get data from database, you should use ORM, so:
$video = Video::where(SOME_CONDITIONS, value)->first();
$currentTime = $video->pause_time;
To get data from frontend, you should use $request:
public function yourController(Request $request)
{
$currentTime = $request->pause_time;
}

Trying to display ajax response in html

I am trying to display some ajax response that i receive from a controller each time i scroll at the bottom of the page.
if($(window).scrollTop() == $(document).height() - $(window).height()){
load++;
$.ajax({
type: 'POST',
url: 'get-response',
dataType: 'json',
data: {
"load" : load,
"key" : key
},
success: function(response){
var out = "";
var i;
for(i=0;i<response.length;i++){
out += response[i];
}
document.getElementById("response").innerHTML = out;
}
});
}
The response i get is in JSON format and looks like this :
I am not sure how to traverse the result and display it in html appending each time the results are returned. Can anyone help me with what else i can write in this section to get the results displayed ?
success: function(response){
var out = "";
var i;
for(i=0;i<response.length;i++){
out += response[i];
}
document.getElementById("response").innerHTML = out;
}
Try this, I have added table implementation, you can change into either div
var out = "<table>";
var i;
for(i=0;i<response.length;i++){
out +='<tr>';
out +='<td>'+response[i].brand_name+'</td>';
out +='<td>'+response[i].product_name+'</td>';
out +='<td>'+response[i].selling_price+'</td>';
out +='<td>'+response[i].mark_price+'</td>';
out +='</tr>';
out += response[i];
}
out += "</table>";
If you have no Problem by displaying the objects in json, you just have to write
JSON.stringify(response[i])
Or you could use another for loop
for(var x: response[i]){...}
This should 'pretty-print' it with the space indentation, suitable for viewing in HTML:
success: function(response){
$("#response").html(JSON.stringify(response, null, '&nbsp').replace(/\n/g, '<br>'));
$("#response").css('font-family', 'courier');
};

Parallel form submit and ajax call

I have a web page that invokes long request on the server. The request generates an excel file and stream it back to the client when it is ready.
The request is invoked by creating form element using jQuery and invoking the submit method.
I would like during the request is being processed to display the user with progress of the task.
I thought to do it using jQuery ajax call to service I have on the server that returns status messages.
My problem is that when I am calling this service (using $.ajax) The callback is being called only when the request intiated by the form submit ended.
Any suggestions ?
The code:
<script>
function dummyFunction(){
var notificationContextId = "someid";
var url = $fdbUI.config.baseUrl() + "/Promis/GenerateExcel.aspx";
var $form = $('<form action="' + url + '" method="POST" target="_blank"></form>');
var $hidden = $("<input type='hidden' name='viewModel'/>");
$hidden.val(self.toJSON());
$hidden.appendTo($form);
var $contextId = new $("<input type='hidden' name='notifyContextId'/>").val(notificationContextId);
$contextId.appendTo($form);
$('body').append($form);
self.progressMessages([]);
$fdbUI.notificationHelper.getNotifications(notificationContextId, function (message) {
var messageText = '';
if (message.IsEnded) {
messageText = "Excel is ready to download";
} else if (message.IsError) {
messageText = "An error occured while preparing excel file. Please try again...";
} else {
messageText = message.NotifyData;
}
self.progressMessages.push(messageText);
});
$form.submit();
}
<script>
The code is using utility library that invokes the $.ajax. Its code is:
(function () {
if (!window.flowdbUI) {
throw ("missing reference to flowdb.ui.core.");
}
function NotificationHelper() {
var self = this;
this.intervalId = null;
this.getNotifications = function (contextId, fnCallback) {
if ($.isFunction(fnCallback) == false)
return;
self.intervalId = setInterval(function() {
self._startNotificationPolling(contextId, fnCallback);
}, 500);
};
this._startNotificationPolling = function (contextId, fnCallback) {
if (self._processing)
return;
self._processing = true;
self._notificationPolling(contextId, function (result) {
if (result.success) {
var message = result.retVal;
if (message == null)
return;
if (message.IsEnded || message.IsError) {
clearInterval(self.intervalId);
}
fnCallback(message);
} else {
clearInterval(self.intervalId);
fnCallback({NotifyData:null, IsEnded:false, IsError:true});
}
self._processing = false;
});
};
this._notificationPolling = function (contextId, fnCallback) {
$fdbUI.core.executeAjax("NotificationProvider", { id: contextId }, function(result) {
fnCallback(result);
});
};
return this;
}
window.flowdbUI.notificationHelper = new NotificationHelper();
})();
By default, ASP.NET will only allow a single concurrent request per session, to avoid race conditions. So the server is not responding to your status requests until after the long-polling request is complete.
One possible approach would be to make your form post return immediately, and when the status request shows completion, start up a new request to get the data that it knows is waiting for it on the server.
Or you could try changing the EnableSessionState settings to allow multiple concurrent requests, as described here.

Stop a recursive AJAX call on a button click and start it again on a button click

I am calling ajax after each 5 secs to update my data and I need to stop that call when a button is clicked.
My ajax function is:
function get_text(){
var text = $.ajax({
type: "POST",
url: "getIt.php",
async: false
}).complete(function(){
setTimeout(function(){get_text();}, 5000);
}).responseText;
$('#editor_Content').html(text);
}
this function is called at
$(document).ready(function(){
new get_text();
}
I need to stop this call when a button is clicked and start this call again when the same button is clicked again. Any suggestions?
My button click code is
function editit(){
var myVar = document.getElementById("editor_Content").getAttribute("contenteditable");
if(myVar=='true'){
document.getElementById("editor_Content").setAttribute("contenteditable", "false");
document.getElementById("editbtn").setAttribute("value","Edit Text");
} else{
document.getElementById("editbtn").setAttribute("value","Done Editing");
document.getElementById("editor_Content").setAttribute("contenteditable", "true");
}
}
You need to save the result of setTimeout and use it in a call to the clearTimeout function like so:
function get_text(){
var text = $.ajax({
type: "POST",
url: "getIt.php",
async: false
}).complete(function(){
window.getTextTimeoutId = setTimeout(function(){get_text();}, 5000);
}).responseText;
$('#editor_Content').html(text);
}
$(document).ready(function(){
get_text();
}
function editit(){
var myVar = document.getElementById("editor_Content").getAttribute("contenteditable");
if(myVar=='true'){
if(window.getTextTimeoutId){
window.clearTimeout(window.getTextTimeoutId)
window.getTextTimeoutId = null;
}
document.getElementById("editor_Content").setAttribute("contenteditable", "false");
document.getElementById("editbtn").setAttribute("value","Edit Text");
} else{
document.getElementById("editbtn").setAttribute("value","Done Editing");
document.getElementById("editor_Content").setAttribute("contenteditable", "true");
if(!window.getTextIntervalId) //edited for not to create another call. fixed!
window.getTextTimeoutId = setTimeout(get_text, 0);
}
}
But for your purposes I think setInterval and clearInterval would work better. Here is what your new code would look like:
function get_text(){
var text = $.ajax({
type: "POST",
url: "getIt.php",
async: false
}).responseText;
$('#editor_Content').html(text);
}
$(document).ready(function(){
window.getTextIntervalId = window.setInterval(get_text, 5000);
}
function editit(){
var myVar = document.getElementById("editor_Content").getAttribute("contenteditable");
if(myVar=='true'){
if(window.getTextIntervalId){
window.clearInterval(window.getTextIntervalId)
window.getTextIntervalId = null;
}
document.getElementById("editor_Content").setAttribute("contenteditable", "false");
document.getElementById("editbtn").setAttribute("value","Edit Text");
} else{
document.getElementById("editbtn").setAttribute("value","Done Editing");
document.getElementById("editor_Content").setAttribute("contenteditable", "true");
if(!window.getTextIntervalId) //edited for not to create another call. fixed!
window.getTextIntervalId = setInterval(get_text, 5000);
}
}