Validate if website exists with AJAX - php

I'm trying to check if a website exists with an ajax call, but I'm not sure I am getting it right. On my page I grab a URL on click
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(){
$("#start").remove();
},
error: function(){
alert("Bad URL");
}
});
});
a=And then check on ajax.php
$url = $_POST['url'];
ini_set("default_socket_timeout","05");
set_time_limit(5);
$f=fopen($url,"r");
$r=fread($f,1000);
fclose($f);
if(strlen($r)>1) {
return true;
} else {
return false;
}
It seems I am getting SUCCESS no matter what... What am I missing?

It seems I am getting SUCCESS no matter what... What am I missing?
This is extremely pretty straightforward.
Because of this reasons:
// You have no idea what server respond is.
// that is you can't parse that respond
success: function(){
$("#start").remove();
}
Which should be
success: function(respond){
//you don't have to return TRUE in your php
//you have to echo this one instead
if ( respond == '1'){
$("#start").remove();
} else {
//handle non-true if you need so
}
}
In php replace this:
if(strlen($r)>1) {
return true;
} else {
return false;
}
to
if(strlen($r)>1) {
print true; //by the way, TRUE is a constant and it equals to == 1 (not ===)
}
Oh yeah, also don't forget to fix this as well:
data: "url="+url,
to data : {"url" : url}

As Nemoden said, you get a success message even if it returns false.
You need to check the data returned and then remove the element.
for example
$("#go").click(function() {
var url = $("#url").val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "url="+url,
success: function(response){
if (response == 'whatever you are returning') {
$("#start").remove();
}
},
error: function(){
alert("Bad URL");
}
});
});

Success callback is called whenever server-side script returned an answer (there were no connectivity errors or server-side errors). Is this answering your question?
See the difference:
$("#go").click(function() {
var url = $("#url").val(),
ajax_data = {url: url};
$.post({
"/ajax.php?cb=?",
ajax_data,
function(response){
if (response.status) {
// URL exists
}
else {
// URL not exists
}
$("#start").remove();
},
'json'
});
});
php back-end:
printf('%s(%s)', $_GET['cb'], json_encode(array('status' => (bool)$url_exists)));

Related

Ajax query, php file is getting read but can't enter success function

so I have the following code that is calling a CheckEmail2.php. I know what I want to do in CheckEmail2.php but because my Ajax success is not working, I have minded the scope to just return a Json. below is my java script. When I launch my console, I see my string coming through that I am echoing in my CheckEmail2.php. so I know my php file is getting read but why won't my success function hit if my string is getting read? I can't get my success function to get called. It always goes to error.
<script type="text/javascript">
function validateForm(){
var email = document.forms["signupform"]["email"].value;
var result = false;
if (email != ""){
$.ajax({
type: "POST",
url: "/CheckEmail2.php",
data: { "User_Email": email },
dataType: "json",
success: function(resp){
console.log(resp);
if(resp == "Not Found"){
result = true;
}
else
{
result = false;
}
},
error: function(data, status){
console.log(data, status);
}
}); //end Ajax
}
return result;
}
</script>
here is my PHP
<?php
header("Content-type:application/json");
echo json_encode("Not Found");
?>
why is error always getting called?

how to get ajax "success" and "error" response using php-crud-api

I am having issues validating a response from API.
I am using php-crud-api and I am passing the values from my login form to the url filter[], the server responds with a 200 OK and returns the json data from the table. However I don't need the json data just a "success" or "error" response. Any help would be amazing. Thank you in advance for any feedback.
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
crossDomain: true,
data: "filter[]=email,eq,email=" + log_email + "&filter[]=password,eq,password=" + log_password,
dataType: 'json',
success: function(data) {
if (data == "null") {
console.log("Email and Password DIDN'T match");
$( "#invalid-login" ).popup( "open" );
}
else if (data == "true") {
console.log("it's a !!MATCH!!");
window.location = "content.html";
}
}
});
return false;
});
});
I've read the documentation of https://github.com/mevdschee/php-crud-api and its written that it will return the output in json format only "Condensed JSON ouput: first row contains field names", so you need to change your code accordingly or you can use some other option.
Luckily the API developer got back to me and he offered the following solution:
in the ajax call add the following line to limit the output:
+"&columns=email"
Replase:
if (data == "null") {
With:
if (data.users.records.length==0) {
In the else clause, just replace:
else if (data == "true") {
with:
else {
RESULT:
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
data: "filter[]=email,eq,"+log_email+"&filter[]=password,eq,"+log_password+"&columns=email",
crossDomain: true,
dataType: 'json',
cache: false,
success: function(data) {
if (data.itouchyou.records.length == 0) {
//FAIL
$( "#invalid-login" ).popup( "open" );
console.log("Email and Password DIDN'T match");
}
else {
// SUCCESS
window.location = "content.html";
console.log("it's a !!MATCH!!");
}
}
});
return false;
});
});

ajax response error not working as expected

My success/error handling is not working as expected. In this example my php runs as intended, however, the intent of the processing failed. Let's say I was looking up a username in the database... if I found the username I would return $ajax_result['success'] = 'success';, but if I did not find the username I would return nothing. The success call works fine, but the error call is not firing.
The error in firebug I am getting is TypeError: response is null and therefore the error alert I have set does not fire.
What is the best way to solve this without actually returning $ajax_result['success'] = 'whatever';
example return from php would be something like this when processing went as expected:
$ajax_result['success'] = 'success'; // add success info
echo json_encode($ajax_result); // return result array to ajax
for 'errors' I am simply returning :
echo json_encode($ajax_result); // which is null in this case
the ajax:
var showInfo = function() {
$('#show-user').on('click', function () {
var $form = $(this).closest('form');
$.ajax({
type: 'post',
url: '/spc_admin/process/p_delete_user_show.php',
data: $form.serialize(),
dataType : 'json'
}).done(function (response) {
if (response.success == 'success') {
alert('success');
}
else
{
alert('error');
}
});
});
}
You can not json_encode a null value, easiest and cleanest way to make this work would probably be to make success a bool and set it to either true or false depending on if it succeeded or not (This is ususaly what most user expects a 'success' or 'result' parameter in response to be, not a string).
//PHP:
header('Content-Type: application/json'); // To let the client know that its json-data.
$ajax_result['success'] = $wasSuccessfull; // true or false
die(json_encode($ajax_result)); // Exit the script with the json response.
//JavaScript:
if (response.success) {
alert('success');
} else {
alert('error');
}
try this one:
if (!response.success) {
alert('error');
}
else
{
alert('success');
}

$.ajax call PHP include file return 500 error internal

here is it my code i call ajax by jquery $.ajax
js
$("#form-login").submit(function(){
var email = $("#menu_username");
$.ajax({
type: "post",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.c == "ok"){
window.location.reload();
} else {
alert(data);
}
return false;
}
})
});
register_cmd.php
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email = $main->checkEmail($email);
?>
main.php
function checkEmail($email){
$result = "function here";
return $result;
}
then it return 500 internal server error i don't know why
I just had this problem myself, even though i couldn't find the reason for it in my case, when changing from POST to GET, the problem 500 error disappeared!
because GET method sends the encoded user information appended to the page request.
type:'POST'
to
type:'GET'
I doing little changes in your codes. Just try this
var email = $("#menu_username").val(); // if you want to take the value from email field
$.ajax({
type: "POST",
url: "register_cmd.php",
data: {email:email},
dataType: "json",
cache:false,
success:function(data){
if(data.result == "ok"){
window.location.reload();
} else {
alert(data.result);
}
return false;
}
});
AND change the codes in register_cmd.php as follows
<?PHP
include 'system/library/main.php';
$main = new mainQuery();
$chk_email['result'] = $main->checkEmail($email);
print_r(json_encode($chk_email)); // if you are using json, you should use json_encode before it returns.
?>
the function in main.php need's a class arround it
class mainQuery {
public function checkEmail($email){
$result = "function here";
return $result;
}
}
otherwise you cannot instance new mainQUery;
also on top of everything to debug set
error_reporting(E_ALL);
ini_set('display_errors', true);
500 are serverside errors and have nothing to do with ajax.
probably this line:
var email = $("#menu_username");
might have to be
var email = $("#menu_username").text();
//or
var email = $("#menu_username").val();
It doesn't matter if it's a POST or GET request.

ajax not properly parsing the value returned by php

I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});

Categories