How to use “response” from any XMLHTTPREQUEST in CakePHP (2.5) - ajax

I got the action "pega" in controller Posts:
public function pega($id = null)
{
$posts = $this->Post->findById($id);
foreach($posts as $pok)
{
$foda = $pok['love'];
}
$this->set('foda', $foda);
$this->set('_serialize', array('foda'));
}
In my layout I try to do a requestto catch the data from function "pega" and put inside tag html:
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:81/booklandia/posts/pega/<?php echo $post['Post']['id'];? >.json";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var out = JSON.parse(xmlhttp.responseText);
function loap (){
var arr = out[0];
document.getElementById("id01").innerHTML = arr;
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

Related

AJAX POST request not working with XMLHttpRequest in Laravel

I'm using XMLHttpRequest to avoid using JQuery and I wanna make an Ajax request to delete an object but I keep getting redirected back and getting FOUND (302) HTTP errors.
This is my code:
function deleteGuia(urlToSend) {
var borra = confirm('¿Está seguro de borrar la guía?');
if (!borra) {
return;
}
var req = new XMLHttpRequest();
var csrfToken = document.querySelector('meta[name="csrf-token"]').content;
req.open("POST", urlToSend, true);
req.setRequestHeader('X-CSRF-TOKEN', csrfToken);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (this.readyState === this.DONE) {
console.log(this.responseURL);
}
if (req.status != 200) {
var msg = JSON.parse(req.response);
alert(msg.error);
} else {
alert('Exitoso');
}
}
}
var data = new FormData();
var guia = "{{$guia ?? ''}}";
var estado = "{{$tipo ?? ''}}";
data.append("guia", guia);
data.append("tipo", estado);
req.send(data);
}
</script>
This one's the controller function:
public function eliminarGuia(Request $request) {
$request->validate([
'guia' => 'required|numeric',
'tipo' => 'required'
]);
$guia = (int)$request->input('guia');
$tipo = $request->input('tipo');
\Log::info('Guia' . $guia . ' Tipo: '. $tipo);
if (strtoupper($tipo) === 'ENTREGA'){
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$borra_ciclos = Device::where('guia_recepcion', $guia)->delete();
if(!$borra_guia) {
return response(400)->json(['error', 'La guía no se encontró.']);
}
} else if (strtoupper($tipo) === 'REVERSA') {
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$devices = Device::where('guia_reversa', $guia)->get();
if (!$borra_guia){
return response(400)->json(['error', 'La guía no se encontró.']);
}
foreach($devices as $device)
{
if (!$device->fecha_recepcion) {
$device->delete();
} else {
$device->guia_reversa = 0;
$device->fecha_reversa = null;
$device->save();
}
}
} else {
return response(400)->json(['error', 'La guía no se encontró.']);
}
return response(200);
}
web.php
Route::post('borrar_guia', 'VistasController#eliminarGuia')->name('borrar_guia');
There's no redirection at all. Why might that be happening? I don't know what else to add. The controller should return a 200 code when it delets an existing object in the database but it's getting a 200 from the redirection.

How to apply diffForHumans() in laravel using ajax?

I'm working with laravel and native ajax. I am wondering where do I put diffForhHumans() when using ajax. In my Controller. I just return the object fetch.
Here's my Controller
public function getDownlines($id) {
$upline = Upline::find($id);
return $upline->downlines;
}
Model
public function downlines() {
return $this->hasMany('App\Downline');
}
HTML Code in View
<div id="downlines">
<div class="downlines-title-container">
<p class="title"></p>
</div>
<div id="downlines-holder">
<div class="p_parent_header">
<p>ID</p>
<p>Account Code</p>
<p>Created By</p>
<p>Created At</p>
</div>
</div>
</div>
Script in Ajax
var downlines = document.getElementById('downlines'),
downlines_holder = document.getElementById('downlines-holder');
function getPromise(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if(xhr.status == 200) {
resolve(xhr.response);
} else {
reject(Error(xhr.statusText))
}
}
xhr.onerror = function() {
reject(Error('Network Error'));
};
xhr.send();
})
}
function getDownlines(e, id) {
getPromise('upline/getdownlines/' + id).then(function(response) {
var resp = JSON.parse(response),
p_parent = document.getElementsByClassName('p_parent'),
p = p_parent.length;
while(p--) p_parent[p].remove();
if(resp.length > 0) {
downlines.style.display = 'initial'
downlines.children[0].children[0].innerHTML = e.innerHTML;
for(var i = 0; i < resp.length; i++) {
var p_parent = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p'),
p3 = document.createElement('p'),
p4 = document.createElement('p');
p_parent.classList.add('p_parent');
p1.innerHTML = resp[i].id;
p2.innerHTML = resp[i].account_code;
p3.innerHTML = resp[i].created_by;
p4.innerHTML = resp[i].updated_at;
p_parent.appendChild(p1);
p_parent.appendChild(p2);
p_parent.appendChild(p3);
p_parent.appendChild(p4);
downlines_holder.appendChild(p_parent);
}
} else {
downlines.style.display = 'none'
}
}, function(error) {
console.log(error);
})
}
I'm searching for the same problem and doesn't find one.
Any help would be appreciated. Thanks!!!
Please do this before returning the downlines
public function getDownlines($id)
{
$upline = Upline::find($id);
return $upline->downlines->map(function($downline) {
return [
'id' => $downline->id,
'account_code' => $downline->account_code,
'created_by' => $downline->created_by,
'created_at' => $downline->created_at->diffForHumans(),
'updated_at' => $downline->updated_at->diffForHumans(),
];
});
}
I am unsure if you want to use created_at or updated_at, because in the html you have written <p>Created At</p> but in the AJAX request, you have written p4.innerHTML = resp[i].updated_at;. So I added both in the return array :)

Check customer email is already exist in magento using ajax prototype

I want to check customer email is already exist or not using ajax prototype. I tried lots of things but it is not working. I write my code like this.
<script type="text/javascript">
//<![CDATA[
var dataForm = new VarienForm('form-validate', true);
Validation.add('validate-emaila', 'Email already exist', function(v) {
var url = '/customer/account/checkEmail/email?email=' + encodeURIComponent(v);
var ok = false;
new Ajax.Request(url, {
method: 'get',
asynchronous: false,
onSuccess: function(transport) {
alert(transport.responseText);
var obj = response = eval('(' + transport.responseText + ')');
validateTrueEmailMsg = obj.status_desc;
if (obj.ok === false) {
Validation.get('validate-email').error = validateTrueEmailMsg;
ok = false;
} else {
ok = true; /* return true or false */
}
},
onFailure: function(){ alert('something wrong') },
onComplete: function() {
if ($('advice-validate-email-email')) {
$('advice-validate-email-email').remove();
}
if ($('advice-validate-email-email_address')) {
$('advice-validate-email-email_address').remove();
}
if ($('advice-validate-email-billing:email')) {
$('advice-validate-email-billing:email').remove();
}
if ($('advice-validate-email-shipping:email')) {
$('advice-validate-email-shipping:email').remove();
}
if ($('advice-validate-email-_accountemail')) {
$('advice-validate-email-_accountemail').remove();
}
}
});
return ok;
});
//]]>
</script>
I called a function In customer/accountcontroller
public function checkEmailAction()
{
$bool = 0;
$email = $this->getRequest()->getParam('email');
$customer = Mage::getModel('customer/customer');
$customer->loadByEmail($email);
if ($customer->getId()) {
$bool = 1;
}
$jsonStatus = 200;
$info = array( "status" => $bool);
$this->getResponse()->setBody(json_encode($info))->setHttpResponseCode($jsonStatus)->setHeader('Content-type', 'application/json', true);
return $this;
}
I am getting wrong response from php function. it is returning full page html. instead of 0 or 1.
I have tried lots of thing but giving same response. Can any one tell me what is wrong in this?
it is wrong code for checking customer.You need to add website id to customer load
First need to change customer check url move from customer accountcontroller.php to checkout onepagecontroller.php. Because magento cannot easly add to accountcontroller.php
url ='<?php echo $this->getUrl('checkout/onepage/checkEmail', array('_secure'=>true)); ?>'
var request = new Ajax.Request(
url,
{
method:'get',
parameters: {email:encodeURIComponent(v)}
onSuccess: function(transport)
{
if(transport.status == 200)
{
var data = transport.responseText.evalJSON();
if(data.success==true){
}
}
}
}
);
In checkout onepagecontroller.phpadd the below code
public function forcecheckAction()
{
$response=array();
$email = $this->getRequest()->getParam('email');
try{
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email); //load customer by email i 
/* if customer has ,then login */
if($customer->getId()>0){
$response['success'] = true;
}else{
$response['success'] = false;
}
}catch(Exception $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
}
$this->getResponse()->setBody(Zend_Json::encode($response));
}

Ajax crashes IE 7

this is my ajax code
function sendAjax(send_data,id)
{
var ajaxobj;
alert("After this alert problem occurs!");
if (window.XMLHttpRequest) ajaxobj = new XMLHttpRequest();
else ajaxobj = new ActiveXObject("Microsoft.XMLHTTP");
ajaxobj.onreadystatechange=function()
{
if(ajaxobj.readyState==4)
{
if(ajaxobj.responseText.match("confirmPage") != null) document.getElementById(id).innerHTML = ajaxobj.responseText;
else
{
if(id == "FreshContent")
document.getElementById(id).innerHTML = "<a id=\"refreshpage\" onClick=\"siteSelection('select')\">Failed.Click here to Reload!</a>";
else
document.getElementById(id).innerHTML = "<a id=\"refreshpage\" onClick=\"sendAjax(0,'latest_gossip_marquee');\">Failed.Click here to Reload!</a>";
}
}
else document.getElementById(id).innerHTML="Loading....";
}
if(id == "FreshContent") ajaxobj.open("GET","sitexyz.php?"+send_data,true);
else ajaxobj.open("GET","html/xyz.html",true);
ajaxobj.send();
}
Here the FreshContent is a div tag id.it works in opera & firefox but it crashes in my IE7.
to see if the page returned by the server is valid the code checks if the returned page has confirmPage string in it.
Try this function out - it's a little more robust than what you're using.
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xhr = false;
}
}
}
return xhr;
}

Problem with XMLHttpRequest conditional XMLHttp.status==200

My Ajax works just fine until I add a conditional status property.
Here's the snippet
if (XMLHttp.readyState==4 && XMLHttp.status==200){
// do something
}
and here's the complete code
function getXMLHttp()
{
try
{
var xmlhttp = new XMLHttpRequest();
// document.getElementById("Content").innerHTML="<h1>Using XMLHttpRequest Object</h1>";
//alert('Mozilla XMLHttpRequest Obeject Created Successfully');
}
catch(err1)
{
var ieXmlHttpVersions = new Array();
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.7.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.6.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.5.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.4.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp.3.0";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "MSXML2.XMLHttp";
ieXmlHttpVersions[ieXmlHttpVersions.length] = "Microsoft.XMLHttp";
var i;
for (i=0; i < ieXmlHttpVersions.length; i++)
{
try
{
var xmlhttp = new ActiveXObject(ieXmlHttpVersions[i]);
// var catatan = "<h1>Using " + ieXmlHttpVersions[i] + "</h1>";
break;
}
catch (err2)
{
var xmlhttp = null;
//alert(ieXmlHttpVersions[i] + " not supported.");
}
}
}
if (typeof xmlhttp == "undefined" || xmlhttp == null){
//document.getElementById("Content").innerHTML="<h1>XMLHttp cannot be created!</h1>";
alert('XMLHttp Request Object Is not Supported Somehow');
}
return xmlhttp;
}
var XMLHttp = getXMLHttp();
function loadData(url, targetID){
if(!url) {var url="data.txt";}
if(!targetID){var targetID='ajaxID';}
XMLHttp.onreadystatechange = function (){getResponse(targetID)};
XMLHttp.open('GET', url, true);
XMLHttp.send(null);
}
function getResponse(targetID){
var data = XMLHttp.responseText;
var ajaxContent=document.getElementById('ajax_content');
if(XMLHttp.readyState == 4){
// This works Just fine, data from data.txt actually fetched
// BUT When i Add this if statement with " && XMLHttp.status==200" It's not returning data from data.txt
if(data.length > 0){
fill(targetID,data);
}
}
}
function fill(ID,data){
hideLoading();
document.getElementById(ID).innerHTML = data;
}
function showLoading(){
document.getElementById('loading').style.visibility='';
document.getElementById('loading_text').innerHTML = '....Loading Please Wait....';
}
function hideLoading(){
document.getElementById('loading').style.visibility = 'hidden';
document.getElementById('loading_text').innerHTML = '';
}
My question is why I can't get the data from data.txt when I add && XMLHttp.status==200 statement ?
Could your web-server be returning one of the other 'success' status codes from the HTTP specification?
Try testing if (XMLHttp.status >= 200 && XMLHttp.status < 300).
Can you tell us whether you know or don't know if execution-flow is getting to the fill(targetID,data) line? It would be very unusual if the XMLHttp.status check were interfering in the actual data retrieval step.
From what you've told us, it seems that XMLHttp.readyState must be reaching 4 without XMLHttp.status == 200. Have I misinterpreted your question?
I think its the problem in creating the XMLHTTP object. try use the basic syntax that has been provided by w3schools.
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
its work for me or use jquery or prototype.

Resources