I am performing an ajax request cross domain. I have been trying to use functions that return the headers in an array only to find that I get Undefined Index even though I can return their values in my ajax request and print them the screen.
I have found some posts on SO that said I should be using $_SERVER globals. So I switched to that method only to get the same results.
Here is my jQuery:
setTimeout(function() {
jQuery.ajax({
url: 'http://something.com',
type:"POST",
dataType:"json",
crossDomain:true,
contentType:"application/json",
data: jsonData,
processData:false,
cache:false,
beforeSend: function( xhr ) {
xhr.setRequestHeader("Authorization",api_key[index]);
xhr.setRequestHeader("Action","PUSH");
},
success: function(data) {
alert(data.action);
alert(data.platform + ' : ' + data.message + ' : ' + data.app_name );
if(data.message == 'success')
{
jQuery('#hollmanPNs_send_push div#hollmanPNs_progressbar' + index).progressbar("value",100);
//add message to the paragraph for app name
jQuery('#hollmanPNs_send_push p#hollmanPNs_paragraph' + index).append(': Complete');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert( 'We had an error: ' + textStatus + errorThrown );
}
}).fail(function() {
alert( 'We had a failed AJAX call.');
});//end ajax
}, index * 5000);//end timeout function
And here is what I am using for PHP:
if($_SERVER['HTTP_ACTION'] != '')
{
//Do Something
}
I have tried switching to:
xhr.setRequestHeader("X-Action","PUSH");
and
$_SERVER['HTTP_X_ACTION']
with the same results. Only I was not able to return them to my ajax request.
I am using PHP 5.3.3.
I am also using this function which I change depending on the different headers I am trying at the time:
header('Access-Control-Allow-Headers: Action, Authorization, Content-Type');
You'll want to get the headers a different way like so:
$headers = getallheaders();
if(array_key_exists('Action', $headers) && $headers['Action'] != '')
{
//Do Something
}
Related
Some reason I can return data fine from a POST in Chrome. The data returned looks like this when using Chrome:
{"email":"account#bytestand.com","customer_id":20413,"credit_amount":50.0,"currency_symbol":"$"}
But then when the same POST is completed on FireFox I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Somehow the data isn't being handled the same and I don't know why.
Here is the code that generates the ajax request
function getCustomerAndCredit() {
console.log("getCustomerAndCredit");
$(function() {
$("form[action='" + shopAddress + "/account/login']").submit(function(event){
console.log("this is past the submit event in Firefox");
var custEmail = $("form[action='" + shopAddress + "/account/login'] input[type=email]").val();
var pass = $("form[action='" + shopAddress + "/account/login'] input[type=password]").val();
sessionStorage.setItem('custEmail', custEmail);
sessionStorage.setItem('pass', pass);
sessionStorage.setItem('loggedIn', true);
debugger;
$.ajax({
url: "/apps/proxy/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "js",
complete: function(data) {
debugger;
if(noCustomerInDB(data)){
if(data.responseJSON == undefined){
sessionStorage.setItem('customer_id', JSON.parse(data.responseText).customer_id);
sessionStorage.setItem('creditAmount', JSON.parse(data.responseText).credit_amount);
sessionStorage.setItem('currency', JSON.parse(data.responseText).currency_symbol);
}
else {
sessionStorage.setItem('customer_id', data.responseJSON.customer_id);
sessionStorage.setItem('creditAmount', data.responseJSON.credit_amount);
sessionStorage.setItem('currency', data.responseJSON.currency_symbol);
}
}
// console.log("What is the credit_amount here in getCustomerAndCredit " + sessionStorage.getItem('creditAmount'));
},
});
});
});
}
And then this is where the data is going:
function noCustomerInDB(data){
console.log("this is the todd variable " + data);
console.log("stringify data " + JSON.stringify(data));
console.log("what about just data?? " + JSON.parse(data));
console.log("this is the response down here in the no customer function" + data.responseText);
if(data.responseText == ""){
return false;
}
else{
if (JSON.parse(data.responseText).customer_id == "no_customer"){
sessionStorage.setItem('creditAmount', "null");
return false;
}
else{
return true;
}
}
}
I did some more digging and now its looking like the ajax isn't being called on FireFox. Because the data returned from the POST looks like this:
{"readyState":0,"status":0,"statusText":"error"}
This cannot be - dataType: "js"
Use dataType: "json" instead. Also make sure that "/apps/proxy/return_customer" has the proper header configured to deploy JSON:
"Content-Type: application/json"
I have a Javascript that is called from a button which makes an HTTP GET request. At the moment when it encounters an error it shows a hidden div with the request error, which is all working well. Here's the script:
$("#callContact1").click(function() {
console.log('starting event');
$.ajax({
url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
data: {},
type: "GET"
})
.then(function(data, status, xhr) {
$('#ajaxResponse1').html(data).show();
var httpStatus = status;
var httpResponseCode = (xhr.status);
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var httpResponseCode = (xhr.getAllResponseHeaders);
var ajaxError = 'There was an requesting the event. HTTP Status: ' + httpStatus;
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
//make alert visible
$('#ajaxResponse1').html(ajaxError).show();
})
})
I now need to extend this slightly to, when it is successful, show a different hidden div with a success message, e.g.:
$('#ajaxResponseSuccess1').html('Event Update in Progress').show();
I'm just not sure how to extend this script - fairly new to JS and jQuery at this point.
There is a success function in JQuery AJAX:
Use it like so:
.success(function(response) {
//DO stuff here.
})
A better simpler code can be like:
$.ajax({
url: 'http://example.com',
method: 'GET',
success: function (response) {
},
error: function (e) {
}
});
View the full documentation of JQuery ajax functions is at
http://api.jquery.com/jquery.ajax/
OR at
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({
url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
data: {},
type: "GET",
success : function(data)
{
$('#ajaxResponseSuccess1').html('Event Update in Progress').show();
},
error:function(xhr,status)
{
alert(xhr.statusText);
}
});
Using short form of ajax:
$.get("www.xyz.com/abc",{eventId: eventId},callbackFunction);
You are registering two callbacks with the Ajax call. You seem to know that fail is executed on error. That leaves that the .then callback is executed on success. Just add the call there:
.then(function(data, status, xhr) {
$('#ajaxResponse1').html(data).show();
$('#ajaxResponseSuccess1').html('Event Update in Progress').show(); // <--
// ...
})
I have a website where I rely on a lot of custom API call. My API return always an XML.
Currently, at the start of each and every $.get or $.post I call, I have this snippet :
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
However, I feel this code to be much redundant on one of my page, it's used 15 times.
I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here
Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?
I assume that you have something like this in many places in your code
$.ajax({
method: "GET",
url: "someurl.html",
dataType: "xml",
success : function() {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
// ...
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
});
you could create a generic custom ajax function tha you can re-use
function baseAjaxCall(option, sCb) {
var ajaxOptions = {
method: option.method || "GET",
url: option.url,
dataType: option.dataType || "xml",
success : function(data) {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
else {
sCb(root);
}
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
};
//you can check for optional settings
if(option.contentType !== undefined){
ajaxOptions.contentType = option.contentType;
}
$.ajax(ajaxOptions);
}
everywhere in your code you can re-use the baseAjaxCall function
baseAjaxCall({ url: "someurl.html" }, function(root){
// no need to chek for errors here!
});
Hope it's helps!
$usrname = $this->session->userdata('username');
$password = $this->session->userdata('password');
$data = array('userName'=>urlencode($usrname),'password'=>urlencode($password));
$data_string = json_encode($data);
$datanew = "loginemployee=". $data_string;
$method = 'post';
$format = 'application/json';
$this->rest->format($format);
$login_url = $this->login_url;
//print_r($login_url);
//exit;
$result = $this->rest->{$method}($login_url, $datanew);
Can anybody please assist me with this. This is actually a PHP script to login into a website, I need to achieve the same on my Cordova app which uses only HTML and JQuery, so please provide me info on how to do this.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').attr('value'); // get username
var password = $('#password').attr('value'); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee=". $jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
$.ajax({
type: "POST",
url: "http:// i know URL", // URL
contentType: "application/json; charset=utf-8",
dataType: "json",
// send username and password as parameters
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
alert(data);
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});
You have done some mistakes in code and I listed those thing below.
Don't use $('#username').attr('value'). Instead of use $('#username').val(). Because $('#username').attr('value') return the value of the element while the html created. But $('#username').val() will return the current value. Same as change $('#password').attr('value') to $('#password').val(). For more information check this post.
Concatenation operator in javascript is + not .. And also u added a variable like $jsonString.
In your Server php code, if your using $_POST['loginemployee'] to retrieve the post values means don't use contentType: "application/json; charset=utf-8",. Because it will use the entire content including key as invalid json like loginemployee={"userName":"cloud","password":"cloudnine"}. If you need like that means u need to use file_get_contents('php://input') to retrieve the post content. But better don't use contentType in ajax. So you can able to easily get the post content using $_POST['loginemployee'].
And also if the reply is json means use dataType in ajax, else dont use that. For more information about contentType and dataType check this post.
So, I updated the code. Check and reply back if there is any issues. Hope it will work as your wish.
$(document).ready(function(){
$('form#loginForm').submit(function() { // loginForm is submitted
var username = $('#username').val(); // get username
var password = $('#password').val(); // get password
alert(username);
var UserData= {"userName":username , "password":password};
var jsonString=JSON.stringify(UserData);
var datanew = "loginemployee="+ jsonString;
if(jsonString)
{
alert("encoded"+jsonString);
}
if (username && password) { // values are not empty
console.log(datanew);
$.ajax({
type: "POST",
url: "http://url_to_post", // URL
// contentType: "application/json; charset=utf-8",
// If reply is json means uncomment the below line.
// dataType: "json",
// send username and password as parameters
crossDomain : true,
data: datanew, // script call was *not* successful
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('div#loginResult').text("responseText: " + XMLHttpRequest.responseText + ", textStatus: " + textStatus + ", `enter code here`errorThrown: " + errorThrown);
$('div#loginResult').addClass("error");
}, // error
// script call was successful
// data contains the JSON values returned by the Perl script
success: function (data) {
alert("success");
if (data.error) { // script returned error
$('div#loginResult').text("data.error: " + data.error);
$('div#loginResult').addClass("error");
} // if
else { // login was successful
console.log(data);
$('form#loginForm').hide();
$("#loginResult").append('all good');
} //else
} // success
}); // ajax/ if
} // if
else {
$('div#loginResult').text("enter username and password");
$('div#loginResult').addClass("error");
} // else
$('div#loginResult').fadeIn();
return false;
});
});
I have 2 files time.html and time.php. I am trying to show server date and users date(I use JS for this) in time.html. In php I create random number from 1 to 5 and if number is equal or greater than 3, php should wait 5s then show error 404.
NOTE: if random is smaller than 3 everything works perfectly
PHP:
<?php
$rnd = rand(1, 5);
if ($rnd >= 3) {
sleep(5);
header("HTTP/1.0 404 Not Found");
}
if ($rnd < 3) {
sleep(3);
$tz = date_default_timezone_get();
date_default_timezone_set($tz);
$time = date('d.m.Y H:i:s');
echo "Timezone: " . $tz . ". On date: " . $time;
}
?>
jQuery:
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
$("span").text(data);
}
});
document.getElementById("jsTime").innerHTML += Date();
});
});
That is because when server responds with an error, jquery.ajax runs the error function, which means your success function does not run. See error on api.jquery.com/jquery.ajax/#jQuery-ajax-settings
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
$("span").text(data);
},
error: function(jqxhr){
//redirect to 404 page on 404 error
if(jqxhr.status == 404){
window.location.href="HTTP/1.0 404 Not Found";
}
}
});
document.getElementById("jsTime").innerHTML += Date();
});
});
As said, when the server returns an error and the request fails, Jquery Ajax let you handle this error with the error function;
Try to add a couple of options more in the settings:
add the error function.
add the statusCode object and play with it; This lets you have more structured control over the error handling.
So:
$("button").click(function () {
$.ajax({
type: 'POST',
url: 'time.php',
success: function (data) {
console.info('success');
$("span").text(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.info(jqXHR.responseText);
console.info(jqXHR.status);
console.info(textStatus);
console.info(errorThrown);
$("span").text(jqXHR.responseText);
},
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
document.getElementById("jsTime").innerHTML += Date();
});
and modify the if inside the php file:
if ($rnd >= 3) {
sleep(1);
echo "my response text";
header("HTTP/1.0 404 Damn, Not Found"); //just for playing, then keep with HTTP standard description
}
Quoting the jQuery.ajax documentation:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn.
Note: This handler
is not called for cross-domain script and cross-domain JSONP requests.
Try to return the data to jquery in array like
$str[0]=true/false;
$str[1]="HTTP/1.0 404 Not Found"/"Timezone: " .$tz . ". On date: ".$time
In success check the condition
success: function (data) {
if(data[0]==true){
$("span").text(data[1]);
}else{
window.location.href="HTTP/1.0 404 Not Found";
}
i think so ajax call must be completed to redirect, above code works in my machine