Div contents flickers between ajax calls - php

I have an ajax call that passes a parameter to a request for data. The data is based on a view from a web service that provides me with XML. The web service sometimes lags in returning the view and during that time the contents of the div flickers with the current and new data.
I've tried emptying/hiding the div and setting headers to not cache the php page but still the same.
Here is my code:
$('#getCourses').change(function() {
var courseGroup = $('#courseGroup:selected').val();
$('#showGroupCourses').html('<img src="images/loading.gif">Processing');
$.ajax({
cache: false,
type: 'POST',
url: 'getGroupCourses.php',
data: { passCourseGroup:courseGroup },
success: function(groupCourses) {
$('#showGroupCourses').html(groupCourses).show('fast').css({'height':'auto'});
}
})
});
Any thoughts on how to prevent this?
Thanks!

Try this:
$('#getCourses').change(function() {
var courseGroup = $('#courseGroup:selected').val();
$.ajax({
cache: false,
type: 'POST',
url: 'getGroupCourses.php',
data: { passCourseGroup:courseGroup },
beforeSend: function( xhr ) {
$('#showGroupCourses').html('');
$('#showGroupCourses').html('<img src="images/loading.gif">Processing');
}
})
.done(function(groupCourses) {
$('#showGroupCourses').html(groupCourses).show('fast').css({'height':'auto'});
});
});

Related

Dynamic URL for ajax request

I'm trying to create a search field on the top navbar with ajax. Since it's on the navbar, it has to be present on all pages, therefore the URL is constantly changing.
$.ajax({
type: 'GET',
url: CURRENT_URL,
dataType: 'json',
data: {
search: userSearch
},
success: function (){...
I'm working with Laravel, so i tried this on the navbar page:
<script>
var CURRENT_URL = "{{url()->current()}}"
</script>
The CURRENT_URL is displayed fine if i try to console log it, but ajax gives an error "Source map error: Error: request failed with status 404".
How can i insert the current URL into the ajax request?
You can use location.href instead of CURRENT_URL
$.ajax({
type: 'GET',
url: location.href,
dataType: 'json',
data: {
search: userSearch
},
success: function (){...
or
<script>
var CURRENT_URL = location.href;
</script>
Hopefully, this can help. Here's my approach to make my url dynamically I get the URL in every forms var URL = $('#example_form').prop('action'); then the URL variable must append or set via Js/Jquery. check my example below.
<script type="text/javascript">
var URL = $('#example_form').prop('action');
$.ajax({
type:'GET',
url: URL+'/clearContent',
beforeSend: function (xhr) {
var TOKEN = $('meta[name="csrf-token"]').attr('content');
if (TOKEN) {
return xhr.setRequestHeader('X-CSRF-TOKEN', TOKEN);
}
},
data:{
get_category_id : $('.parent-id').val(),
},
success:function(data){
if (data.response.status == true) {
// your codes here
}
},
dataType: 'json',
complete: function () {}
});

Ajax post not appending data to URL

I am trying to get my search bar working, however I am having issues with an ajax post.
For whatever reason, none of the data is being appended to the URL. I have tried various things with no success. I am attempting to send the data to the same page (index.php).
Here is my jquery:
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ searchTerm: text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: postData,
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
});
And here is the php which I have with index.php:
<?php
require('course.php');
if(isset($_POST['searchTerm'])) {
echo $_POST['searchTerm'];
}
?>
No matter what I try, I am unable to get anything to post. I have checked the network tab in chrome, and I'm not seeing anything that indicates it's working correctly.
Any ideas?
EDIT:
I've changed my code to this, and it seems I'm getting closer:
$(document).on({
click: function () {
$("TABLE").remove()
var text = $('#searchBar').val();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'text',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
}
}, "#searchButton");
And:
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo $_GET['searchTerm'];
}
?>
Now I am getting ?searchTerm=theTextIEnter as expected, however it's still not being echoed in index.php.
Do not use JSON.stringify() to convert object to string. data passed to $.ajax must be an object and not JSON.
For whatever reason, none of the data is being appended to the URL.
You are making a POST request. POST data is sent in the request body, not in the query string component of the URL.
If you change it to a GET request (and inspect it in the correct place, i.e. the Network tab of your browser's developer tools and not the address bar for the browser) then you would see the data in the query string.
This will work for you use data: { postData } on place of data:postData and you will receive your data in $_POST['postData']
$(function(){
$(document).on({
click: function () {
var tables = document.getElementsByTagName("TABLE");
for (var i = tables.length-1; i >= 0; i-= 1) {
if (tables[i]) tables[i].parentNode.removeChild(tables[i]);
}
var text = $('#searchBar').val();
var postData = JSON.stringify({ 'searchTerm' : text });
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { postData },
success: function(data) {
alert(data.searchTerm);
}
});
}
}, "#searchButton");
});
In index.php
<?php
if(isset($_POST['postData'])) {
echo $_POST['postData'];
die;
}
?>
If you want to send data via the URL you have to use a GET request. To do this, change the type of the request to GET and give the object directly to the data parameter in your jQuery, and use $_GET instead of $_POST in your PHP.
Finally note that you're not returning JSON - you're returning text. If you want to return JSON, use json_encode and get the value in the parameter of the success handler function.
Try this:
$(document).on({
click: function () {
$('table').remove();
$.ajax({
type: 'GET',
url: 'index.php',
dataType: 'json',
data: { searchTerm: $('#searchBar').val() },
success: function(response) {
console.log(response.searchTerm);
}
});
}
}, "#searchButton");
<?php
require('course.php');
if(isset($_GET['searchTerm'])) {
echo json_encode(array('searchTerm' => $_GET['searchTerm']));
}
?>
Remove dataType: 'json', from your AJAX. That is all.
Your response type is not JSON, yet by setting dataType: 'json' you're implying that it is. So when no JSON is detected in the response, nothing gets sent back to the method handler. By removing dataType it allows the API to make an educated decision on what the response type is going to be, based on the data you're returning in the response. Otherwise, you can set dataType to 'text' or 'html' and it will work.
From the manual:
dataType: The type of data that you're expecting back from the server.
This is NOT the type of data you're sending/posting, it's what you're expecting back. And in your index.php file you're not sending back any JSON. This is why the success() method is not satisfying. Always set the dataType to the type of data you're expecting back in the response.
With POST Request:
Please comment below line in your code:
//var postData = JSON.stringify({ searchTerm: text });
And use below ajax code to get the post-data:
$.ajax({
type: 'POST',
url: 'index.php',
dataType: 'json',
data: { searchTerm: text },
success: function() {
alert("Test");
}
});
With GET Request:
You can convert your data to query string parameters and pass them along to the server that way.
$.ajax({
type: 'GET',
url: 'index.php?searchTerm='+text,
dataType: 'json',
success: function(response) {
alert(response);
}
});
In response, You can get the data with alert, so you may get idea about the same.

submit forum (post) delete my ajax get

I am using ajax for sending to the server that a checkbox is checked and now other inputs fields need to be required:
EDIT: ok i will change the question to be more clarified.
i have this code:
$(document).ready(function() {
$('#button_ajax').click(function() {
var request = jQuery.ajax({
type: 'get',
url: 'http://orenmizrah.git/nir1.php',
data: {'id1': $('#input_text').val()},
async: true,
success: function(){
console.log("sent");
}
});
});
and now i check that i got the info in $_GET['id1'] with php code and if $_GET['id1'] is set, echo something to the browser.
the problem is that $_GET['id1'] is set but there is no output to the browser.
what i should do?
No output is shown in the browser because nothing is done to show it.
$(document).ready(function() {
$('#button_ajax').click(function() {
var request = jQuery.ajax({
type: 'get',
url: 'http://orenmizrah.git/nir1.php',
data: {'id1': $('#input_text').val()},
async: true,
success: function(data){
console.log(data); // outputs the returned data to the console
}
});
});

Ajax async inside loop

I use dbase.dll in PHP to transfer information from dbase files to MySQL.
I have 150 files to transfer. Each file as a name between 1000 and 5000.
I use PHP to transfer the files. But the request is made in jquery:
var Files = [1544,1548,1548,..];
$.each(Files, function(i,val){
$.ajax({
async: false,
url: '../JC/Reaction.php?type=pes',
type: 'POST',
data: {SCADA: val},
success: function(data){
$('#Result').append(data);
}
});
});
});
I had to set async to false for this action to be done properly.
The url '../JC/Reaction.php' is gets the val and perform the transfer for each file and echoes:
echo $val.' - Done';
The problem is that my brower crashes or nothing happens. I need to show in the browser on the 'Result' div the 'data' from the php like:
:
1544 - Done
1548 - Done
...
Any help would be nice!
RESOLVED
var ajaxQueue = $({});
$.ajaxQueue = function(ajaxOpts) {
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
next();
};
$.ajax(ajaxOpts);
});
};
$.each(Files, function(i,val){
$.ajaxQueue({
async: true,
url: '../JC/Reaction.php?type=pes',
type: 'POST',
data: {SCADA: val},
success: function(data){
$('#Result').append(data);
}
});
});

How can I get my div id to reload via ajax and jquery

I'm creating a CMS using jQuery and AJAX. When I click, my "Add Campaign" buttom, it creates a unique client ID in the DB and on a hard reload, the new client shows up in its container. I am trying to use ajax to reload the container on the fly and I'm not having the exact luck i am hoping for. I can get it to reload, but it's like it's pulling in descriptions of each of the clients as well!
function AddNewClient() {
dataToLoad = 'clientID=' + clientID + '&addClient=yes';
$.ajax({
type: 'post',
url: '/clients/controller.php',
datatype: 'html',
data: dataToLoad,
target: ('#clientssidebar'),
async: false,
success: function(html){
$('#clientssidebar').html(html);
},
error: function() {
alert('An error occured!');
}
});
};
Try:
function AddNewClient()
{
dataToLoad = 'clientID=' + clientID + '&addClient=yes';
$.ajax({
type: 'post',
url: '/clients/controller.php',
data: dataToLoad,
success: function(html){
$('#clientssidebar').html(html); },
error: function() {
alert('An error occured!'); }
});
}

Categories