Sometime Error Using Session With HTML AJAX - javascript

here's my html code
js at index.html
<script>
function get_session() {
$.ajax({
url: 'http://mydomain/getsession.php',
cache: false,
type: 'POST',
success: function (data) {
if (data == "1") {
window.location.href = "home.html";
} else {
window.location.href = "login.html";
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Code: " + jqXHR.status + ", Type:" + textStatus + ", Message: " + errorThrown);
}
});
};
</script>
and getsession.php at server-side
<?php session_start();
if(isset($_SESSION['username']))
echo "1";
else
echo "0";?>
but sometimes isnt working for getsession ..
*im using vps at digital ocean, maybe wrong at my php.ini ??

Put your website ip address there and try it
http://domain_ip/getsession.php

Try like this....
Script
<script>
function get_session() {
$.ajax({
dataType:'JSON',
type: 'POST',
url: 'http://mydomain/getsession.php',
success: function (data) {
var result=eval(data);
if (result.status == true) {
window.location.href = "home.html";
} else
{
window.location.href = "login.html";
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Code: " + jqXHR.status + ", Type:" + textStatus + ", Message: " + errorThrown);
}
});
};
</script>
PHP
<?php session_start();
if(isset($_SESSION['username']))
{
$status = TRUE;
}
else
{
$status = FALSE;
}
echo json_encode(array('status'=>$status));
?>

PHP code can be -
<?php session_start();
if(isset($_SESSION['username']))
{
$status = TRUE;
}
else
{
$status = FALSE;
}
echo json_encode(array('status'=>$status));
?>
and ajax code -
<script>
function get_session()
{
$.get('http://mydomain/getsession.ph', function(data) {
//access data variable here for responce
});
}
</script>

Related

disable fields if query is true

I need to disable fields of a modal if the result of a query is true, I have an idea of ​​how to do it, but I have not been able to specify it, I would appreciate any help or correction within my code:
controller
function evaluarTrabajador(){
$this->load->model("Prwtrabajadores_model");
$idTrabajador = $this->input->post('idEdit');
$this->Prwtrabajadores_model->revisaCertificados($idTrabajador);
}
model
function revisaCertificados($idTrabajador){
return $this->db
->select("a.idprw_estadocertificado")
->from("prw_estadocertificado as a")
->join($this->schemaEmpresas."wom_trabajadores as b")
->where("b.idwom_trabajadores", $idTrabajador)
->where("a.idprw_estadocertificado = 1 || 4 || 5")
->get()->result();
$query = result();
if ($query->num_rows() > 0){
return true;
}else{
return false;
}
}
and the JS from view, now the JS show the data from database, but need block the text fields if the query is true
$(".editarT").on("click", function(id){
var id = $(this).data("idtra");
$.ajax({
url : "<?php echo site_url('/contratista/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('input[name="idEdit"]').val(data[0].idwom_trabajadores);
$('input[name="rutEdit"]').val(data[0].rut);
$('input[name="nombresEdit"]').val(data[0].nombres);
$('input[name="appEdit"]').val(data[0].apellido_paterno);
$('input[name="apmEdit"]').val(data[0].apellido_materno);
$('input[name="cargoEdit"]').val(data[0].cargo);
$('input[name="telefonoEdit"]').val(data[0].telefono);
$('input[name="mutualEdit"]').val(data[0].mutual);
$('#form-modal-editar-trabajador').modal({show:true});
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error obteniendo datos');
}
});
});
Is this what you want?
$(".editarT").on("click", function(id){
var id = $(this).data("idtra");
$.ajax({
url : "<?php echo site_url('/contratista/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('#form-modal-editar-trabajador').modal({show:true});
if(data.length > 0){
$('input[name="idEdit"]').val(data[0].idwom_trabajadores).prop('disabled', true);
$('input[name="rutEdit"]').val(data[0].rut).prop('disabled', true);
$('input[name="nombresEdit"]').val(data[0].nombres).prop('disabled', true);
$('input[name="appEdit"]').val(data[0].apellido_paterno).prop('disabled', true);
$('input[name="apmEdit"]').val(data[0].apellido_materno).prop('disabled', true);
$('input[name="cargoEdit"]').val(data[0].cargo).prop('disabled', true);
$('input[name="telefonoEdit"]').val(data[0].telefono).prop('disabled', true);
$('input[name="mutualEdit"]').val(data[0].mutual).prop('disabled', true);
}
else{
$('input[name="idEdit"]').val('').prop('disabled', false);
$('input[name="rutEdit"]').val('').prop('disabled', false);
$('input[name="nombresEdit"]').val('').prop('disabled', false);
$('input[name="appEdit"]').val('').prop('disabled', false);
$('input[name="apmEdit"]').val('').prop('disabled', false);
$('input[name="cargoEdit"]').val('').prop('disabled', false);
$('input[name="telefonoEdit"]').val('').prop('disabled', false);
$('input[name="mutualEdit"]').val('').prop('disabled', false);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error obteniendo datos');
}
});
});

If and else condition inside success in ajax

As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement" and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you
<script>
function renderAttendees(id)
{
///$("#attendeesContent").empty();
var dataString = { "id": id };
$.ajax({
type: 'POST',
url: server+'webservice/crm/viewAttendeesDetails',
data: dataString,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: true,
success: function(data)
{
if($.trim(data) === 'error')
{
alert('yes');
}
else
{
alert('no');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);
}
</script>
//My Controller Code
public function viewAttendeesDetails()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$data = array();
$id = $_POST['id'];
$AttendeesDetails = $this->model->GetAttendeesDetail($id);
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
}
echo json_encode($data);
exit;
}
?>
//My Model Code
db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");
$stmt->bindParam(":AttendId", $id);
$stmt->execute();
return $stmt;
}
catch (Exception $e)
{
return $e->getMessage();
return $stmt;
}
return;
}
?>
//Here is the result of console.log(data);
Object
email:"kyle#localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"
I would return from your controller something like
{status: 'success', data: myArrayWithFoundData}
so when you receive the ajax response you could do a json_decode, and check the status.
So in you controller you would have
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
$rsp_data = {status: 'success', data: $data};
}else{
$rsp_data = {status: 'error', data: null};
}
echo json_encode($resp_data);
Something like that, so in the ajax response you would do a
var a = JSON.parse(data);
and check the a.status for error

ajax inside an ajax success

i made an ajax website that call php pages from a /pages folder inside my index.php, inside my page painting.php i have a link that call painting-slider.php page.
so how can i open this painting-slider.php in ajax when i already called my painting.php page?
this is my index.php request page:
<div id="ajax-container">
<?php
$d = "pages/";
if (isset($_GET['p'])) {
$p = strtolower($_GET['p']);
if (preg_match("/^[a-z0-9\-]+$/", $p) && file_exists($d . $p . ".php")) {
include $d . $p . ".php";
} else {
include $d . "404.php";
}
} else {
include $d . "home.php";
}
?>
</div>
and this is my ajax function:
var afficher = function(data, page) {
$('#ajax-container').fadeOut(250, function() {
$('#ajax-container').empty();
$('#ajax-container').append(data);
$('#ajax-container').fadeIn(100, function() {});
});
};
var lastRequest = null;
if (lastRequest !== null) {
lastRequest.abort();
}
var loadPage = function(page, storeHistory) {
if (typeof storeHistory === 'undefined') {
storeHistory = true;
}
lastRequest = $.ajax({
url: "pages/" + page,
cache: false,
success: function(html) {
afficher(html, page);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
return false;
};
window.addEventListener('load', function() {
setTimeout(function() {
window.addEventListener('popstate', function(e) {
if (e.state === null) {
loadPage('home.php');
} else {
loadPage(e['state']['url'], false);
}
});
}, 0);
});
$('.link').bind('click', function(e) {
e.preventDefault();
var page = $(this).attr('href');
loadPage(page);
return false;
});
a simple example of "ajax after ajax":
$.ajax({
url: "pages/" + page,
cache: false,
success: function(html) {
afficher(html, page);
if (storeHistory === true) {
history.pushState({
'key': 'value',
'url': page
}, '', page);
}
$.ajax({
url: otherUrl,
cache: false,
success: function(result) {
alert("i am the second result");
alert(result);
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
afficher('erreur lors du chagement de la page');
}
});
On the serverside (your PHP files) it is not important to do anything. Your ajax will just get the return value of the script found at the given Urls. I hope it helps

Make $ .ajax consider Response code 40x as success

jQuery executes the function "success" if the HTTP status code is in the range of 200 and 299 or is equal to 304.
However, for example, for the code 401 I need jQuery considers that the Ajax call is successful, and it evaluates the response as JSON and executes the function "success".
The problem is that this behavior is hard-coded in the method "done":
// Determine if successful
isSuccess = status> = 200 && status <300 || === status 304;
I do not really see how to do that.
EDIT:
This is what I have for the moment:
var options = {
url: '',
type: 'POST',
data: {},
success: function(response, status){},
error: function(res, status, error){
notify("Une erreur s'est produite !", "danger");
},
complete: function(res, status){}
};
$.extend(options, opts);
var dataString = '';
$.each(options.data, function(key, value){
dataString += ((dataString.length > 0) ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value)
});
$.ajax({
url: site_url + options.url,
type: options.type,
data: dataString,
dataType: 'json',
statusCode: {
401: function() {
setTimeout(function(){
location.reload();
}, 2000);
}
},
success: function(response, status){
if (response.response.result.status == 'ok'){
options.success(response, status);
} else {
if ('message' in response.response.result){
notify(response.response.result.message, "danger");
} else if (response.response.errors.length > 0) {
notify(response.response.errors[0], "danger");
}
}
},
error: options.error,
complete: options.complete
});
I want the answer to be parsed according to the dataType provided (which is only for the "success" method), and, in the case of a code 401, processing is the same as for the other responses containing the correct JSON code, except for a further instruction.
I think it is a mistake for jQuery not be able to change the codes indicating a request as having failed. The content of the response may be important anyway and require special processing.
For a complete web page, the browser still displays the content returned by the server in case of error.
Instead of trying to override the "success" callback why not just make the function call inside the "error" callback,ofcourse before checking the specific error occurred.
error: function(a, b, c){
if(a.status == 401){
// Your custom function call / code.
}
}
Do you have to handle the status code in the success or error block? How about the complete block? It follows both outcomes..
complete
Type: Function( jqXHR jqXHR, String textStatus )
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
Source: http://api.jquery.com/jquery.ajax/
Example:
$.ajax({
url: "http://www.google.com"
}).success(function(){ //--> use .done() instead
//things to do on success
}).error(function(){ //--> use .fail() instead
//things to do on error
}).complete(function( data ) { //--> use .always() instead
switch(data.status){
//your logic here
}
});
Finally, given the need for that to go through the "complete" method, it is necessary to recode the entire automation of jQuery.
So there is no interest in using $ .ajax in this case.
That's why I had to code this replacement function that uses the jQuery syntax:
var altAjax = function(opts){
var options = {
url: '',
type: 'GET',
data: {},
dataType: 'text',
successCodes: [304, 401, 403, 404, 500],
statusCode: {},
success: [],
error: [],
complete: []
};
$.extend(options, opts);
var success = function(data, textStatus, xhr){
if ($.isArray(options.success)){
$.each(options.success, function(index, callback){
callback(data, textStatus, xhr);
});
} else if ($.isFunction(options.success)){
options.success(data, textStatus, xhr);
}
if ($.isFunction(options.statusCode[xhr.status])){
options.statusCode[xhr.status](data, textStatus, xhr);
}
}
var error = function(xhr, textStatus, errorThrown){
if ($.isArray(options.error)){
$.each(options.error, function(index, callback){
callback(xhr, textStatus, errorThrown);
});
} else if ($.isFunction(options.error)){
options.error(xhr, textStatus, errorThrown);
}
if ($.isFunction(options.statusCode[xhr.status])){
options.statusCode[xhr.status](xhr, textStatus, errorThrown);
}
}
var complete = function(xhr, textStatus){
if ($.isArray(options.complete)){
$.each(options.complete, function(index, callback){
callback(xhr, textStatus);
});
} else if ($.isFunction(options.complete)){
options.complete(xhr, textStatus);
}
}
var dataString = '';
$.each(options.data, function(key, value){
dataString += ((dataString.length > 0) ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(($.isArray(value) || $.isPlainObject(value)) ? JSON.stringify(value) : value);
});
var req = new XMLHttpRequest();
var url = options.url;
if (options.type.toUpperCase() != 'POST'){
url += ((url.indexOf('?') > -1) ? '&' : '?') + dataString;
}
req.onload = function(){
var textStatus = 'error';
if ((this.status >= 200 && this.status <= 299) || $.inArray(this.status, options.successCodes) > -1) {
var data;
switch (options.dataType.toLowerCase()) {
case 'json':
try {
data = JSON.parse(this.responseText);
} catch (ex){
error(this, textStatus, ex.name + ': ' + ex.message);
break;
}
textStatus = 'success';
success(data, textStatus, this);
break;
case 'xml':
try {
data = $.parseXML(this.responseText);
} catch (ex){
error(this, textStatus, ex.name + ': ' + ex.message);
break;
}
textStatus = 'success';
success(data, textStatus);
break;
default:
textStatus = 'success';
success(this.responseText, textStatus);
}
} else {
error(this, textStatus, null);
}
complete(this, textStatus);
};
req.open(options.type, url, true);
if (options.type.toUpperCase() == 'POST'){
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(dataString);
} else {
req.send();
}
req = null;
};
Instead of success use the complete function and check the xhr.statusText value
$.ajax('url.json', {
complete:function(result) {
if(/^(2\d\d|304|401)$/.test(result.statusText)) {
success();
} else {
error();
}
}
});
You need to handle the conditions at client side checking the status code. You can fetch the status as below:
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},

Sending PHP values with AJAX

I am trying to delete images with Ajax and all the php seems to work except when I try to send variables to another php document.
Php that shows and grabs neccessary values.
// show images
$image_display = "";
foreach(glob($pathimages.'*') as $filename){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$name_only = basename($filename, ".".$ext);
$image_display .= "<img src=\"images/" .$targetID."/" .$name_only.".".$ext. "\" width=\"30\" />
<a onclick=\"DeleteImage('".$name_only."','".$ext."','".$targetID"'); return false;\" href=\"javascript:;\">X</a>
<br />";
}
.JS document, I get the sent and the success messages when pressing the X
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
delete_imgs.php document
include('session_check.php');
$name_only = $_POST['name_only'];
$ext = $_POST['ext'];
$targetID = $_POST['targetID'];
$pathimages = "images/$targetID/";
unlink($pathimages . $name_only .".". $ext);
echo "Deleted";
Any thoughts are more than welcome since I have banged my brain out of my head by now ...!
Cheers!
Try with async:false
function DeleteImage(name_only, ext, targetID){
$.ajax({
url: 'delete_imgs.php',
type: "POST",
async : false,
data:{name_only:name_only,ext:ext,targetID:targetID},
beforeSend: function() {
alert("sent");
},
success: function(html) {
alert("Success")
},
error: function( x, status, error ) {
alert(x.status + status + error);
}
});
}
Maybe that can help

Categories

Resources