Sending one Jquery AJAX request, but receiving multiple requests on PHP side - php

I have researched dozens of answers but can't find the solution.
I have jQuery Ajax call on mouseover.
I see one log in a browser console.
But PHP side receives 2 requests.
My JS code:
$('.df_word').off("mouseover").on("mouseover", function(){
console.log("open translation_box"); //fires once on hover
get_translation($(this),$(this).html());
}
function get_translation(word_el,word_html){
console.log('get_translation'); //fires once on hover
var params = {}
params['api'] = "2.0";
params['page'] = "translate";
params['q'] = ""+word_html+"";
console.log(params); //fires once on hover
$.ajax({
type: "GET",
crossDomain: true,
contentType: 'application/json; charset=utf-8',
url: window.api_link,
data: params,
error: function( xhr, textStatus ) {
console.log(xhr.status);
},
success: function(data){
console.log(data); //fires once on hover
}
});
}
On PHP side I see 2 requests within the same second (I save every request to the database).
What am I missing?

Related

Prevent AJAX calls from firing twice everytime

I am building a web application using JQuery 3.3.1. It would seem that everytime I make ajax call, the request is sent twice. I can tell because I tried logging the requests on server side. I tried solutions from similar questions but they do not seem to help.
I separated the ajax call from click events, so it does not happen because of click event being registered twice.
$(function() {
console.log("hi");
var request = {};
request["user_id"] = 1;
request["date"] = new Date();
request["assignments"] = [{
"point_count" : 1,
"skill_mnemo" : "SKILL_FARM"
}];
$.ajax({
type: "POST",
dataType: "json",
mimeType: "application/json",
url: "./api/update_skill_point.php",
enctype: 'multipart/form-data',
data: request,
async: false,
cache: false,
success: function(result) {
console.log(result);
}
});
});
You have to debug this code by the following ways:
Check how many times hii is printing into console.
Add break point at start of $.ajax. Then check the call stack.
Check into network tab and analyse the call stack at initiator column for the corresponding ajax call.(for Chrome)
Hope it will help for you.
There is a chance that the submit button in your form is NOT set to type="button".
So, on-clicking the button, your ajax function runs and the browser also attempts to submit the form (default behavior of submit buttons) to your current URL. This might give the appearance that ajax is being called twice.
don't use
(function(){})
if we use (function(){}), it will call itself when DOM is getting ready and then again when required.
Try
function ajaxCall()
{
console.log("hi");
var request = {};
request["user_id"] = 1;
request["date"] = new Date();
request["assignments"] = [{
"point_count" : 1,
"skill_mnemo" : "SKILL_FARM"
}];
$.ajax({
type: "POST",
dataType: "json",
mimeType: "application/json",
url: "./api/update_skill_point.php",
enctype: 'multipart/form-data',
data: request,
async: false,
cache: false,
success: function(result) {
console.log(result);
}
});
}
$(document).ready(){
ajaxCall();
}
In this way you can control your ajax call,
Now you might have some idea how to deal, if not let me know, I'll try to explain more.

why jquery ajax prevent loading another url page

After $.ajax request, i cannot load other page on new tab in browser. what is the reason?
my javascript code in this url https://example.com/page1.php:
$('#myButton').on("click", function(event) {
event.preventDefault();
$.ajax({
url: "models/data.php",
type: "POST",
data: {...},
dataType: 'json',
context: this,
success: function(data) {
//...
},
error: function (asd, textStatus, errorThrown) {
//...
}
});
});
after click on myButton i cannot load another url in other tabs, As long as the ajax request ends. for example https://example.com/page2.php what is the reason?

Retrieving data from ajax call in controller

I have an ajax call that is sending some IDs to one of my controllers.
The jQuery that is running to do this is basically searching for elements that have an ID like notification-id- and then grabbing the IDs and storing them in a JavaScript variable.
When I alert() or console.log() this variable it prints out values like 1,2 for two notifications that I have on the page notification-id-1 and notification-id-2.
For my ajax call, I am simply doing the below:
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: notifications, // Let jQuery handle packing the data for you
success: function(response) {
// The data was sent successfully and the server has responded (may have failed server side)
alert(notifications);
},
error: function(xhr, textStatus, errorThrown) {
// AJAX (sending data) failed
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
I'm trying to test what my controller is receiving by doing dd($request->all()); however that is just returning:
array:1 [
"undefined" => ""
]
(The ajax call does run successfully)
How can I retrieve the ID values that are being sent in this ajax call inside my controller?
Edit: Full Script
<script type="text/javascript">
$(document).ready(function() {
var count = $('#notification-counter');
var new_notifications = $('#notification-new-counter');
$('#notification-drop-down').on('click', function() {
count.empty();
var notifications = $('[id^="notification-id-"]').map(function() {
return this.id.slice(16);
}).get();
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: notifications, // Let jQuery handle packing the data for you
success: function(response) {
// The data was sent successfully and the server has responded (may have failed server side)
alert(notifications);
},
error: function(xhr, textStatus, errorThrown) {
// AJAX (sending data) failed
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
});
});
</script>
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: {'notifications':notifications},
Can you please use the following line and tell me what you get in controller ?
data: {notifications:2}. If you get this value correctly, then in your original post you are not sending notifications correctly and not getting anything in controller.

Successive AJAX calls add an extra consecutive call

I have a pretty standard ajax call for a live update, however, say I call the the ajax, everything is good, but say I want to call it again, this time, I will get 2 calls, and if I try again then I'll have 3, I can verify this by invoking and alert and with the Network DevCon of Chrome, any idea why this is happening?
P.S: I'm using Laravel 5.1
$('button[name=act]').click(function() {
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function() {
icon.show();
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
$(icon).fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
});
The problem is that every time you click on the act button you call $("form").submit(), which adds anothersubmithandler to the form. So if you click on theact` button 3 times, and then click on the form's submit button, it will send 3 AJAX requests.
It's almost always wrong to bind one event handler inside another event handler, you should bind all the event handlers at top level.
var icon;
$(document).ajaxStart(function() {
if (icon) {
icon.show();
}
});
$('button[name=act]').click(function() {
icon = $(this).closest('div.thumbnail').find('i');
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
if (icon) {
icon.fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
The reason this is happening is because you are rebinding the submit event function every time the button is clicked which results in multiple copies of the function. Just move it out of the click even, and if you want to force a submit on a click, you can call the submit() function with no parameters to fire the event.
Try the following:
$(function(){
$('button[name=act]').click(function(){
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function()
{
icon.show();
});
$("form").submit(); //This submits the form on click
});
//This binds the function, so it should only be called once.
$("form").submit(function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr)
{
//BLAH
}
});
});
});
I noticed two other things you might want to address. You want to somehow update the icon after it is loaded. You will need to have some other way to find the icon inside of the success function (possibly looking at the data that came back could yield some information that could be useful. Since it is json, it should be easy to update.)
Also, the way you currently have it will bind to all forms on the page. In the event that you have multiple forms on the page, you will probably want to change the selector to use an id.
Hope this helps!
Based in incremental calls and my guessings, I have to say that you're printing this code each time you make the (ajax) call, leading to bind your form element again in each call..
Am I right?
JO.

How to show Loading message instantly while using jquery ajax?

Below is my Ajax code I have made using jQuery Ajax method.
$(".loading_msg").show();
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
success: function(result){
if(result=='Success'){
$("#msgContainer").html('<div style="color:#3CA322;font-weight:bold;font-size:14px;padding:10px;">Thank you.</div>');
$("#msgContainer").fadeIn();
}
else{
$("#msgContainer").html('<div style="color:red;font-size:12px;padding:10px;">' + result + '</div>');
$("#msgContainer").fadeIn();
}
},
error: function(){
//console.log('error');
},
complete: function(){
//console.log('complete');
$(".loading_msg").hide();
$("#submit").attr("disabled", false);
}
});
So the logic is, whenever the Ajax request is about to made,
the .login_msg container is displayed first
then ajax call made
and when it is completed, again the .loading_msg is hidden.
Now the problem, it is not working smoothly as it should be. So when the ajax call is made, the browser hangs for a seconds but it doesn't show the loading message. But when the request is completed, the login message appears like for half a second and then it goes away as I have set it hidden on request completion.
So I want that the .login_msg should be shown before the request is made.
Any suggestions for this? Thanks in advance.
try using beforeSend and complete settings of $.ajax:
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
beforeSend:function(){
$(".loading_msg").show();
}
complete:function(){
$(".loading_msg").hide();
}
....
....
});

Categories