Ajax post not working on localhost using xampp - php

I'm using XAMPP as my server. I am able to make queries using PHP and I have tried other Ajax code and it does work but when I try posting to a different php file using ajax I keep getting the error returning 0 or null.
if (!e.isDefaultPrevented()) {
e.preventDefault();
$.ajax({
type: "POST",
url: "https://localhost/validate.php",
data: {'email': $('#email').val(), 'username': $('#username').val()},
dataType: "json",
success : function(text){
$('#signup_form').unbind('submit').submit();
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
}
This is my error "Not connect. Verify Network." I have tried passing the following urls and they all give me a 404 file not found error:
validate.php, ../validate.php, localhost/validate.php, MusicApp/validate, localhost/MusicApp/validate, and etc. The only things that seem to work is https://localhost/MusicApp/validate.php, https://localhost:63342/localhost/MusicApp/validate.php but I keep getting the Not connect. Verify Network error.
I also can't do a post within a form without getting a 404 page not found error so I believe it might have something to do with the path?

Related

Ajax Error status giving error 0 while I using Laravel API in Localhost

I'm doing this totally in localhost. And Creating Laravel API and called them via AJAX. This is my AJAX code:
function checkLogin() {
var objectData = {
caller_id: document.getElementById('caller_id').value,
password: document.getElementById('password').value
};
var objectDataString = JSON.stringify(objectData);
console.log(objectDataString);
$.ajax({
type: "POST",
url: "http://localhost:8000/api/caller/check",
dataType: "json",
data: objectDataString,
success: function (data) {
console.log(data);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
}
And CORS job which is also caused for this Error. But I figured it out. Here is the code in Laravel Framework.
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
}
This is located at Middleware folder. I cleared the cache as well. Does anyone know how this is caused?

Ajax success function cant returns value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am using jQuery ajax function to get database values code and subcode.Whenever I get the code and subcode I have to get the name stored in another table corresponding to code and subcode.
First function i am using is
function loadSecretaries()
{
var items = "";
$.getJSON("Tac_members_GetTacSecretaries.php", function(data) {
$.each(data, function(index, item) {
var name = getSecretariesName(item.ECODE, item.ECODE_S);
items += "<option value='" + item.ECODE + "'>" + item.ECODE_S + </option>";
});
$("#select_reviewer_secretary").html(items);
});
}
The second function is
function getSecretariesName(code, subcode)
{
var items = "";
$.ajax({
async: false,
url: '../PhpProject1/Tac_Members_GetReviewerNames.php',
dataType: 'json',
type: 'POST',
data: {"code": code, "subcode": subcode},
success: function(response) {
alert(response.ename) ;
var name =response.ename;
//here i want to return ename to first function
},
error: function(x, e) {
if (x.status === 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status === 404) {
alert('Requested URL not found.');
} else if (x.status === 500) {
alert('Internel Server Error - Please try after relogin to the application');
} else if (e === 'parsererror') {
alert('Parsing JSON Request failed.');
} else if (e === 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
return name;
}
I am getting undefined when alert 'name' in first function. How to solve this. Thanks in advance.
try this
function getSecretariesName(code, subcode)
{
var items = "";
var name = "";
$.ajax({
async: false,
url: '../PhpProject1/Tac_Members_GetReviewerNames.php',
dataType: 'json',
type: 'POST',
data: {"code": code, "subcode": subcode},
success: function(response) {
alert(response.ename) ;
name = response.ename;
//here i want to return ename to first function
},
error: function(x, e) {
if (x.status === 0) {
alert('You are offline!!\n Please Check Your Network.');
} else if (x.status === 404) {
alert('Requested URL not found.');
} else if (x.status === 500) {
alert('Internel Server Error - Please try after relogin to the application');
} else if (e === 'parsererror') {
alert('Parsing JSON Request failed.');
} else if (e === 'timeout') {
alert('Request Time out.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
}
});
return name;
}

jQuery AJAX request does not return (no HTTP status code) and stays pending

I have several requests like this:
$('#some-button').on('click', function(e) {
e.preventDefault();
$this = $(this);
$.ajax({
url: 'some_request.php/?q='+$some_id,
dataType: 'json',
success: function(data) {
alert('success!')
}
});
});
I.e. lots of AJAX requests that get initiated on button clicks. This request stays 'pending' according to Chrome - no JS alert. No HTTP response code comes back. I think it's just sat there waiting on a response and not getting it.
Question is similar to: jquery $.ajax request remains pending but the answer doesn't help. Nowhere in my PHP or HTML code am I using the session.
Any ideas? Many thanks.
I think you need a jQuery Ajax Error Handling Function. Here it is:
// jQuery Ajax Error Handling Function
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
Now call your ajax function:
$.ajax({
url: 'some_request.php/?q=' + $some_id,
dataType: 'json',
success: function(data) {
alert('success!')
}
});
And check what error you are getting.
Are you sure that the Php file you're requesting is on the same domain? Usually this happens when doing cross domain Ajax calls which is not allowed by most web browsers. You'll have to try jsonp instead if that's the case. Here is a nice practical explanation with examples: http://www.jquery4u.com/json/jsonp-examples/

AJAX function on permanent error

Something is wrong with this AJAX function but I do not see what.
AJAX
$('.review').click(function() {
var idatas = $(this).attr('rel');
var idata = 'idata=' + idatas;
$.ajax({
type: 'POST',
url: '<?php echo $thisposturl;?>?review',
data: idata,
beforeSend: function() {
$(this).addClass('ractive');
},
dataType:'json',
success: function(data) {
$('#dbody').html(data.ioutput);
$('.cright').height($('#dropout').height());
$('#dropout').addClass('dropopen');
},
error: function(data) {
$('#dbody').html('arse biscuity');
$('.cright').height($('#dropout').height());
$('#dropout').addClass('dropopen');
}
});
PHP
<?php
$rid = $_POST['idata'];
$ireviews = get_posts('post_type=reviews&p='.$rid.'&numberposts=-1');
foreach ($ireviews as $ireview) :
setup_postdata($post);
$ioutput = '<div class="iavatar"></div>
<div class="ititle">'.get_the_title($ireview).'<br />
<div class="iauthor">'.get_the_author($ireview).'</div></div>
<div class="icontent">'.get_the_content($ireview).'</div>';
endforeach;
echo json_encode(array('ioutput'=> $ioutput));
?>
According to Firebug the response is this
{"ioutput":"<div class=\"iavatar\"><\/div>\n<div class=\"ititle\">What a lovely course<br \/>\n<div class=\"iauthor\">pm master<\/div><\/div>\n<div class=\"icontent\">This intimate layout, with its undulating and springy fairways that zigzag in amongst the woodland setting, calls for accurate driving and precision shot-making into the well-bunkered greens; another classic Colt trademark. Position, not power, is the name of the game here.<\/div>"}
But it is going to error function and not putting the content in #dbody
Any ideas?
Try using the $.ajaxSetup() to get the correct error like this:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
In case of any error in the Ajax call, you will get proper alert.

JavaScript/jQuery and PHP Ajax force an error

Is it possible to force an error state to return to an ajax request from a PHP script?
I am handling the success and error states in an ajax request and I want a way to force the error. The error only seems to be triggered by xhttp error and I want to trigger this when a condition is not met at the server. Its seems confusing to have to return success and have to actually put a flag in the response for an error
You could approach this from two angles:
Force an error to be thrown by outputting an HTTP header such as a 404 or 503.
Force an error to be thrown based on certain condition of the resulting data.
Force an error to be thrown by outputting an HTTP header such as a 404 or 503:
PHP
<?php
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
print 'Login successful!';
} else {
header("HTTP/1.0 403 Forbidden");
print 'Bad user name / password';
}
jQuery
$.ajax({
'url': '/some/url',
'type': 'POST',
'data': {
'username': 'someone#example.com',
'password': 'rhd34h3h'
},
'success': function(data) {
alert(data);
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});
Force an error to be thrown based on certain condition of the resulting data:
PHP
<?php
$return = array();
if(User::Login($_POST['username'], $_POST['password'])) { // Your logic here
$return['success'] = True;
$return['message'] = 'Login successful!';
} else {
$return['success'] = False;
$return['message'] = 'Bad user name / password';
}
print json_encode($return);
jQuery
$.ajax({
'url': '/some/url',
'type': 'POST',
'dataType': 'json',
'data': {
'username': 'someone#example.com',
'password': 'rhd34h3h'
},
'success': function(data) {
if(data['success']) { // Successful login
alert(data['message']);
} else { // Login failed, call error()
this.error(this.xhr, data['message']);
}
},
'error': function(jqXHR, textStatus, errorThrown) {
alert('ERROR: ' + textStatus);
}
});
You can use header to do this, for example:
header('HTTP/1.1 503 Service Unavailable');

Categories