I am creating one small program in which Ι use two tabs in single page and call one ajax call to do operations dynamic.
Below is my code:
HTML Code below
OffyApp Agents
ListHub Agents
<div id="Home" class="tabcontent">
// Some code
</div>
<div id="News" class="tabcontent">
// Some code
</div>
Script Code Below
function openPage(pageName,elmnt,color) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablink");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].style.backgroundColor = "";
}
document.getElementById(pageName).style.display = "block";
elmnt.style.backgroundColor = color;
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
AJax call Below
$.ajax({
url: "sendInvite.php",
type: "POST",
data: {list: inviteEmails},
dataType: "JSON",
beforeSend: function() {
$("#loading-image").show();
},
success: function (data) {
//alert(data);
if (data.status == 200) {
alert("Invite Sent Successfully.");
location.reload(true);
}
},
error: function (msg) {
alert(msg);
}
});
If ajax call give me success then i want to redirect to my second tab like #News
success: function (data) {
if (data.status == 200) {
alert("Invite Sent Successfully.");
location.reload(true);
}}
data.status only will give you an error bacause neither data is JSON nor data have key status
Hence, your if statement is always false. data is the actual response as the plain text from the requested file. Therefore data have no such key like status.(eg.data is the request.responseText)
jQuery Ajax function has three variables:
success: function (a,b,c){}
Where:
a is the actual responseText
b is the textStatus &
c is xhr
Hence, you have to write success function as:
success: function (data,stxt,xhr){
if(xhr.status==200){
alert("Invite sent successfully!");
window.location.reload();
}
}
You could write a function
function activateTab(tab){
$('.tab-pane a[href="#' + tab + '"]').tab('show');
};
Then upon success of your ajax call you can activateTab('news');
But as #Ritesh said, that function will not run because data does not contain a key called success on it, it will just contain the data you get from the server. You need to pass all the parameters into your success callback in order to access the response code.
Related
I have a page showing log files which I want to give the user the ability to select and delete. The deletion is done through an AJAX request where the ID of each log-for-deletion is sent via the parameters.
The problem is that there are instances where there are hundreds of logs and in these cases the AJAX request seems to fail. I assume because there is just too much data sent via the parameters. I have tried breaking the AJAX request into parts, but only the first request is sent, afterwards all other requests are shown in Chorme as "cancelled". Following is my code:
var logFiles = [];
function deleteLogBatch() {
if (logFiles.length == 0)
return false;
if (logFiles.length > 10)
var elements = 10;
else
var elements = logFiles.length;
var params = 'action=deletelog';
for (var i = 0; i < elements; i++) {
params += '&lf' + i + '=' + escape(logFiles.shift());
}
$.ajax({
type: "POST",
url: './ajax/logs.php',
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
}
$('body').on('click', '#confirm-log-delete', function(event) {
event.preventDefault();
$('.select-log').each(function() {
if ($(this).is(":checked")) {
logFiles.push($(this).attr('id'));
}
});
deleteLogBatch();
}
Any help as to why this is happening and what is the proper way of doing this would be appreciated.
You should use async ajax calls
$.ajax({
type: "POST",
url: './ajax/logs.php',
async: true,
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
It will not wait to previous ajax call
I have a bootbox dialog with a button named save in a view called table_data.php and I would like to determine whether the Ajax post to database will be done based on a result obtained from the database.
I want the data only to be saved when the database query in home_model.php does not return any rows. However, when I do it, it does not work. It is a cms and I am using codeigniter framework.
My page is blank. And nothing appears. Please help me. I am new to web and have very little experience with JavaScript and php and just started on ajax. Your help will be much appreciated.
table_data.php (view)
bootbox.dialog({
message: '<div class="row"> ' +
'<div class="col-md-12"> ' +
'<form class="form-horizontal"> ' +
'<div class="form-group"> ' +
'<label class="col-md-4 control-label" for="awesomeness">Table ID: </label> ' +
'<div class="col-md-4">' +
'<input id="idtable" type="text" value="'+table_column_15+'"/>' +
'</div><br>' +
'</div>'+
'</form> </div> </div>',
title: "Form",
buttons: {
success: {
label: "Save",
className: "btn-success",
callback: function() {
console.log('save');
console.log($('#re_confirm')[0].checked);
var valueid = document.getElementById('idtable').value
if(valueid == 0)
myFunction();
var valueid2 = document.getElementById('idtable').value
if(valueid2==0)
return;
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id" : valueid2
"session_id" : table_column_15
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
console.log(response);
var check = $(response);
}
});
if(check==0)
return;
$.ajax({
url : "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id" : $('#idtable').val(),
},
success: function(response){
...
}
});
}
},
...
,
...
}
});
home_model.php (model)
public function check_occupied($tableid,$sessionid)
{
$sql = "SELECT * FROM booking WHERE table_id=$tableid and session=$sessionid;
$query = $this->db->query($sql);
if ($query->num_rows() > 0)
$imp = 1;
else
$imp = 0;
return $imp;
}
home.php(controller)
public function check_occupied()
{
$tableid = $_POST['table_id'];
$sessionid = $_POST['session_id'];
$imp = $this->home_model->check_occupied($tableid,$sessionid);
$this->load->view('table_data', $imp);
}
I found a few syntax minor errors but the biggest problem is where you are attempting to use the var check as in if(check==0).
Your condition evaluation if(check==0) is outside the success function of the ajax call to check_occupied. Therefore, if(check==0) will execute before the success function runs and sets a value for check. If you console.log(check); just before the if statement you will find the value to be 'undefined'. This console result will also be logged before the output of `console.log(response);' which will confirm the order of execution.
In other words, you need to decide on whether to run the next ajax call inside of the success function of the check_occupied ajax call.
Here's my version. It's untested but I think the concept is sound. This shows only the callback: for the "Save" button.
callback: function () {
console.log('save');
console.log($('#re_confirm')[0].checked);
var valueid = document.getElementById('idtable').value;
if (valueid === 0) {
myFunction();
}
var valueid2 = document.getElementById('idtable').value;
if (valueid2 === 0) {
return;
}
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/check_occupied",
type: "post", // To protect sensitive data
data: {
"table_id": valueid2,
//??? where is table_column_15 declared and initialized? Some global var?
"session_id": table_column_15
//and any other variables you want to pass via POST
},
success: function (response) {
// Handle the response object
console.log('response='+response);
//if I read check_occupied() right, response should only be 1 or 0
//there is no need to assign it to another var, eg. var check = response
//there is no apparent need to turn it into a JQuery object with $(response) either
if (response > 0) {
$.ajax({
url: "<?php echo base_url(); ?>index.php/home/update_booking",
type: "post",
data: {
"table_id": $('#idtable').val()
},
success: function (response) {
}
});
}
}//end of success function callback for check_occupied() ajax
console.log('ajax to check_occupied is done.');
});
}
I'm trying to upload files through Ajax call and jQuery. Each input[type="file"] is handled dynamically as you will see on the code below and are created on the change event for the Select2 element.
var tipoRecaudo = $('#tipoRecaudo'),
tipo_recaudo = tipoRecaudo.val(),
selectedIdsTipoRecaudo = [];
tipoRecaudo.select2({
ajax: {
dataType: 'json',
url: function () {
return Routing.generate('obtenerRecaudosTramite');
},
data: function (tipo_recaudo) {
return {
filtro: tipo_recaudo
}
},
results: function (data) {
var myResults = [];
$.each(data.entities, function (index, item) {
if (selectedIdsTipoRecaudo.indexOf(item.id.toString()) === -1) {
myResults.push({
'id': item.id,
'text': item.nombre
});
}
});
return {
results: myResults
};
}
},
formatAjaxError: function () {
return Translator.trans('mensajes.msgNoConexionServidor', {}, 'AppBundle');
}
}).change(function () {
var id = $(this).val(),
selectedData = tipoRecaudo.select2("data"),
htmlTpl = '<table class="table"><caption>'+ selectedData.text + '</caption><tbody><tr><td>';
htmlTpl += '<input type="hidden" name="tipoRecaudos[]" id="tipoRecaudo ' + id + '" value="' + selectedData.id + '" /><div class="row"><div class="col-xs-6"><div class="form-group"><input type="file" id="recaudosNombreArchivo' + id + '" name="recaudos[nombre_archivo][]" multiple="multiple" class="form-control" /></div></div></div></div>';
htmlTpl += '</td></tr></tbody></table>';
selectedIdsTipoRecaudo.push(id);
$('#recaudoContainer').append(htmlTpl);
});
$('#recaudoContainer').on('change', 'input[type=file]', function (event) {
$("input:file").filestyle({
buttonText: "Seleccionar archivo",
iconName: "fa fa-upload",
buttonName: "btn-primary"
});
});
$('#btnGuardarPasoSieteAgregarProducto').on("click", function (event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// Create a formdata object and add the files
var formData = $('#formRecaudosTramites').serialize();
$.each($('#formRecaudosTramites')[0].files, function (key, value) {
formData = formData + '&recaudos[]=' + value;
});
$.ajax({
url: Routing.generate('rpniSubirRecaudos'),
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
contentType: 'multipart/form-data',
processData: false, // Don't process the files
//contentType: false // Set content type to false as jQuery will tell the server its a query string request
}).done(function (data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
console.log('SUCCESS: ' + data.success);
} else {
// do something with error
}
}).fail(function (jqXHR, textStatus, errorThrown) {
// do something with fail callback
// STOP LOADING SPINNER
});
});
What is happening is: no filenames exists on query string, no files are upload or send through the Ajax call, instead it's sending a [object Object], what I'm doing wrong? Can any give me some working code for this stuff?
EDIT:
After reads the post referenced by user I change my code as the one before and now the error turns on:
TypeError: a is undefined
...rCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e...
What is wrong there?
Note: Yes, I know there are tons of plugins for handle this like jQuery File Upload from Blueimp, Dropzone and some others but I leave them out since I start using jQuery File Uploader from inside OneupUploaderBundle on my Symfony2 project and spent 4 days without success so I move to the other side: made things by myself so I can learn something else and improve my knowledge
i think this will help you,
var fd = new FormData();
//name is the key on the page of php to access the file
fd.append('name', $('#aob_file')[0].files[0]);
pass this fd object to your data field in ajax,
How would I merge these two bits of code and can someone explain what the key and value would be.
I'm building a notifications system and I'm wanting to store the last new notification_id but not have it inserted into the div over and over again if its the same one, so then the ajax searches for anything else within my server that maybe new.
Ajax
<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(dataHandler){
}
});
}
setInterval(loadIt, 10000);
</script>
Localstrorage
window.localStorage.setItem('key', 'value');
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
You've confused oldschool Ajax by hand with jQuery. The parameter to the success function in jQuery is not a function name or handler. Its a variable name that will contain the response from the server. The success function itself is equivalent to the handler functions you would have created doing it the old way.
So not:
success: function(dataHandler){ }
...
...
var dataHandler = function (response){
But rather:
success: function(response) { doCallsToSaveToLocalStorage(response); }
i have some problems with collecting the data i fetch from database. Dont know how to continue.
What i did so far:
JQ:
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
data:{white:white}
});
});
});
PHP (requested page.php) so far:
$thing = mysql_real_escape_string($_POST["white"]);
..database connect stuff..
$query = "SELECT * FROM table1 WHERE parameter='$thing'";
if($row = mysql_query($query)) {
while (mysql_fetch_array($row)) {
$data[]=$row['data'];
}
}
What i dont know, is how to send out data and receive it with ajax.
What about errors when request is not succesful?
How secure is ajax call against database injection?
Thanks :)
You'll need a success parameter in $.ajax() to get a response once a call is made
$('#submit').click(function(){
var white = $('#white').val();
if(white == '')
{
// display validation message
}
else
{
$.ajax({
type:"POST",
url:"page.php",
data:{"white":white}
success:function(data){
$('#someID').html(data);
}
});
});
Whatever you echo (HTML tags or variables) in page.php will be shown in the element whose ID is someID, preferable to keep the element a <div>
In page.php, you can capture the value entered in the input element by using $_POST['white'] and use it to do whatever DB actions you want to
To send out data to you can write following line at the end :
echo json_encode($data);exit;
To receive response and errors when request is not successful in ajax :
jQuery.ajax({
type:"POST",
url:"page.php",
data:{white:white},
asyn: false,
success : function(msg){
var properties = eval('(' + msg + ')');
for (i=0; i < properties.length; i++) {
alert(properties[i]);
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
For Feeling more safety do the following things:
1. Open a Session.
2. Detect Referrer.
3. Use PDO Object instead mysql_real_escape_string
4. Detect Ajax call :
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !='xmlhttprequest') {
//Is Not Ajax Call!
}