AJAX function returns status 0 - php

$.ajax({
type: "POST",
url: "check-email",
data: {email: "name#example.com"},
success: function(data)
{
// success part here
},
error: function(xhr)
{
alert(xhr.status);
}
});
This will call another PHP file. But the sad thing is the error part is executed always with xhr.status printing as 0. What would be the problem?
Note:
1. This works perfectly in the local.
2. Both the script, check-email page is located in the same server.
3. The server is secured with https and it is in WWW version.
Update:
error: function(jqXHR, textStatus, errorThrown)
{
alert(textStatus, errorThrown);
}
This prints simply as "error".

I would have done this as a comment but the code would be a nightmare.
In your PHP page write this somewhere:
<?php
echo '<pre>'.print_r($_POST, true).'</pre>';
echo '<pre>'.print_r($_GET, true).'</pre>';
?>
Now:
Open up your Developer tools (Chrome) or Firebug (FireFox) and visit the Network tab.
Refresh your page that makes the AJAX call
Find the AJAX call to "check-email" in the Network tab and click it
What do you see?
Also there is a sub-tab called "Headers" in the developer tools, take a look at it

Related

PHP exec() command works flawlessly in code, but not when called by AJAX

This command works great if I call it during page execution
exec('run.exe -something', $response, $status);
But I have a button on the page that executes the same command via AJAX:
// Attempt a call to change the password
$.ajax({
url: 'actions/runcommand.php',
type: 'POST',
data: {
cid: cid,
},
dataType: 'json',
success: function(msg)
{
if (ajaxErr(msg) return;
// Show success message
showMsg('success!');
},
error: function(jqXHR, textStatus, errorThrown){ajaxFail(jqXHR, textStatus, errorThrown)}
});
I've verified the two are executing literally the same string whether I do it in my code or via the AJAX, but the AJAX initiated one is returning an error code instead of functioning. The value of status is 1 which is a generic error so I have little to go on.
I looked around and found one similar post, but they solved it by removing https from the ajax command. If I do that the browser blocks it with scary messages.
This is running on a local machine which attempts HTTPS but fails because it's a self-signed cert or something. I turned off https redirection for the site, but that made zero difference. Not sure what it's unhappy about... please help!
if (ajaxErr(msg) return;
Error handling shouldn't be done in the success callback function. You can remove this or modify what this function is doing.
If you're requesting the URL from a different directory, make sure your URL parameter uses a leading slash for the root directory:
url: '/actions/runcommand.php',
Try this and see if there's still a generic error:
$.ajax({
url: '/actions/runcommand.php',
type: 'POST',
data: {
cid: cid,
},
dataType: 'json',
success: function(data, status) {
console.log(data);
console.log(status);
showMsg('success!');
},
error: function(jqXHR, textStatus, errorThrown) {
ajaxFail(jqXHR, textStatus, errorThrown)
}
});
Ok folks, this had all the signs of a boneheaded mistake and that's what it was. I'm leaving it here for posterity because it's an easy mistake to make and I saw other people ask similar questions with no good answer.
The SOLUTION was that my AJAX files were in a SUBDIRECTORY and that means when they executed the command the output which was trying to export to a subdir of the root was trying to find that subdir in ANOTHER SUBDIR. Sheesh!

How do i verify that my ajax code is communicating with my php script [duplicate]

I have been working on trying to get AJAX to work with Jquery. My big issue so far has been that I don't really know how to figure out where I'm making a mistake. I don't really have a good way to debug AJAX calls.
I'm trying to set up an admin page where one of the functions I want to make is to change the permission set in my SQL database. I know that the .click function is being triggered, so I've narrowed that down, but I'm not sure where in the chain from AJAX call to SQL query its going wrong.
My .js code:
$('#ChangePermission').click(function(){
$.ajax({
url: 'change_permission.php',
type: 'POST',
data: {
'user': document.GetElementById("user").value,
'perm': document.GetElementById("perm").value
}
})
})
my .php handler:
<?php
require_once(functions.php);
echo $_POST["user"];
try{
$DBH = mysql_start();
$STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");
$STH->bindParam(1, $_POST["user"]);
$STH->bindParam(2, $_POST["perm"]);
$STH->execute();
}
catch(PDOException $e){
echo $e->getMessage;
}?>
Where the mysql_start is setup for the PDO function that I use successfully in my other SQL calls.
I have been researching and looking up tutorials for a few days now and I can't for the life of me figure out what's going wrong. Are there tools I can use to figure out where the error is occuring? I'm obviously interested in the answer to this specific issue, but I think my bigger issue here is that I have no idea where to start with debugging. Thanks for your help!
Make your JQuery call more robust by adding success and error callbacks like this:
$('#ChangePermission').click(function() {
$.ajax({
url: 'change_permission.php',
type: 'POST',
data: {
'user': document.GetElementById("user").value,
'perm': document.GetElementById("perm").value
},
success: function(result) { //we got the response
alert('Successfully called');
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
})
Using pretty much any modern browser you need to learn the Network tab.
See this SO post about How to debug AJAX calls.
You can use the "Network" tab in the browser (shift+ctrl+i) or Firebug.
But an even better solution - in my opinion - is in addition to use an external program such as Fiddler to monitor/catch the traffic between browser and server.
if you are using mozilla firefox than just install an add-on called firebug.
In your page press f12 in mozilla and firebug will open.
go for the net tab in firebug and in this tab go in the xhr tab.
and reload your page.
you will get 5 options in xhr Params Headers Response HTML and Cookies
so by going in response and html you can see which response you are getting after your ajax call.
Please let me know if you have any issue.
Firebug as Firefox (FF) extension is currently (as per 01/2017) the only way to debug direct javascript responses from AJAX calls. Unfortunately, it's development is discontinued. And since Firefox 50, the Firebug also cannot be installed anymore due to compatability issues :-( They kind of emulated FF developer tools UI to recall Firebug UI in some way.
Unfortunatelly, FF native developer tools are not able to debug javascript returned directly by AJAX calls. Same applies to Chrome devel. tools.
I must have disabled upgrades of FF due to this issue, since I badly need to debug JS from XHR calls on current project. So not good news here - let's hope the feature to debug direct JS responses will be incorporated into FF/Chrome developer tools soon.
2020 answer with Chrome dev tools
To debug any XHR request:
Open Chrome DEV tools (F12)
Right-click your Ajax url in the console
for a GET request:
click Open in new tab
for a POST request:
click Reveal in Network panel
In the Network panel:
click on your request
click on the response tab to see the details
you can use success function, once see this jquery.ajax settings
$('#ChangePermission').click(function(){
$.ajax({
url: 'change_permission.php',
type: 'POST',
data: {
'user': document.GetElementById("user").value,
'perm': document.GetElementById("perm").value
}
success:function(result)//we got the response
{
//you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
}
})
})
we can also have error() function
hope this helps you
Install Firebig to see where your error is happening. You could also set up a callback in your ajax call to return your error messages from your PHP. Eg.
error: function(e){
alert(e);
}
Just add this after jQuery loads and before your code.
$(window).ajaxComplete(function () {console.log('Ajax Complete'); });
$(window).ajaxError(function (data, textStatus, jqXHR) {console.log('Ajax Error');
console.log('data: ' + data);
console.log('textStatus: ' + textStatus);
console.log('jqXHR: ' + jqXHR); });
$(window).ajaxSend(function () {console.log('Ajax Send'); });
$(window).ajaxStart(function () {console.log('Ajax Start'); });
$(window).ajaxStop(function () {console.log('Ajax Stop'); });
$(window).ajaxSuccess(function () {console.log('Ajax Success'); });
here is what I would do in order to debug and get the php errors into javascript console.log after an ajax call:
$('#ChangePermission').click(function () {
$.ajax({
url: 'change_permission.php',
type: 'POST',
data: {
'user': document.GetElementById("user").value,
'perm': document.GetElementById("perm").value
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
on the php side I would start by asking for all error returned to string concat and echo as a json encoded response that will includes php error messages as well if any.
<?php
error_reporting(E_ALL);
require_once(functions . php);
$result = "true";
$DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");
if (isset($_POST["user"]) && isset($_POST["perm"])) {
$STH->bindParam(1, $_POST["user"], PDO::PARAM_STR);
$STH->bindParam(2, $_POST["perm"], PDO::PARAM_STR);
}
try {
$STH->execute();
} catch (PDOException $e) {
$result .= $e->getMessage;
}
echo json_encode($result);
?>

AJAX Call Not Sending Success Response

//MAKE AJAX CALL TO REPOPULATE TABLE
var newData = 'page_number=1&type=2';
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'http://www.myurl.net/form_validate.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
//REFORMAT UPON SUCCESSFUL AJAX CALL
alert(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
All I've put in my PHP file is:
<?php echo "test"; ?>
When I go straight to that file, it echoes 'test.' When I try to run the AJAX function on the click of a button it gives me the error:
[object Object] error
in an alert window. I've put the absolute URL to the file because I was thinking that the relative linking I was using was wrong but it now seems like it's some other issue. Am I overlooking a simple syntax error? Sorry if this is super basic but I can't seem to figure this out after working on it for a really long time. Thanks for your help.
The problem is your absolute url . Some browsers have problems dealing with absolute urls, consider it as a cross-domain request and block it even if it's not a cross-domain request. You should try with relative url instead
The problem might be in the url, try with relative path instead of absolute.
You named the file was in the same folder as the .js file, so try
url: '/directory_path_to_the_same_folder_as_the_JS_file/form_validate.php',
Try using done with jQuery.post instead.
For example:
jQuery.post('form_validate.php', data).done(
function(data, textStatus, jqXHR) {
alert(jqXHR.responseText);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}).complete(function() {
// Common code when request completes
});
If your error is [object Object] error NOT FOUND then the reason is
the specified url in AJAX is not correct.
If your error is [object Object] error INTERNAL SERVER ERROR , its
because of the error in your server file ie the php file ,error like variables not defined correctly etc..
Some times error may occur due to cross domain, if you have not
specified headers when in case your php file is not in the same
domain
Hope this helps
Thank you
function abc(){
var ret=true;
$.ajax({
type: 'POST',
url: 'send_password.php',
data: 'mail_to=mymail&new_password=pwd',
async:false,
success: function(response){
},
error: function(r){
ret=false;
}
});
return ret;
}
alert(abc());
Have a look at this testfiddle

PhoneGap jQuery POST not working

Good evening,
I was trying a long time with different syntaxes but haven't got it working:
Everything is running on PhoneGap. I get the console_log before $.ajax.., but not any error or output after it.
After click on "Submit" this JS code is executed:
console.log(in_mail + " " + in_text);
$.ajax({
type: 'POST',
data: "mail="+in_mail+'&text='+in_text,
url: 'http://example.com/comment.php',
success: function(data){
console.log(data);
alert('Your comment was successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding your comment');
}
});
console.log("POST done");
Two things:
If you are executing this script via submit button you should consider returning true on success and false on error.
Your "POST DONE" would execute before the success or error functions would be invoked because post is asynchronous.
I have reproduced the example with jsFiddle you can find it here http://jsfiddle.net/jUBMN/

jQuery ajax is not working on Mozilla only

I have following script
$.ajax({
type:"GET",
url:"views/jquery/js/private/visual_constructor/proxy.php",
data:null,
timeout:55000,
dataType:"xml",
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("error="+XMLHttpRequest+" error2="+textStatus+" error3="+errorThrown);
},
success:function(response){
alert('sucess');
}
});
and the content of the proxy.php is following.
<?php
header('Content-type: application/xml');
echo file_get_contents('http://server.name/somefile.php');
?>
It connects to another server where somefile.php generates some xml content and prints it.
It works perfectly in Chrome, but in Mozilla it shows me my error alert.
What is wrong here?
update 1
I am using firebug and it says that everything is just OK. Even it shows the response from the server. And here is what my error alert prints:
error=[object XMLHttpRequest] error2=parsererror error3=parsererror
update 2
When I open http://server.name/somefile.php from the Mozilla it shows me this message:
XML Parsing Error: not well-formed
Location: http://authoringtool/views/jquery/js/private/visual_constructor/proxy.php
Line Number 8, Column 94: <xs:annotation><xs:documentation xml:lang="en">Network Type</xs:documentation></xs:annotatin>
But again when I open it from Chrome it doesn't show me the error but prints the content of the somefile.php
I think you're doing a cross-server request (more importantly, a cross-domain request ), and as such, you need to do extra security stuff.
https://developer.mozilla.org/En/HTTP_access_control
https://developer.mozilla.org/En/Server-Side_Access_Control
http://www.w3.org/TR/cors/
http://arunranga.com/examples/access-control/
Firebug
Also, with Firebug, debugging is better as objects, then you can inspect the returned objects.
console.log({ "error": XMLHttpRequest, "error2": textStatus, "error3": errorThrown });
Try setting the content type from the query itself:
$.ajax({
type:"GET",
url:"views/jquery/js/private/visual_constructor/proxy.php",
data:null,
timeout:55000,
contentType: "application/xml;charset=UTF-8",
dataType:"xml",
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("error="+XMLHttpRequest+" error2="+textStatus+" error3="+errorThrown);
},
success:function(response){
alert('sucess');
}
});
You open with:
<xs:annotation>
And close with:
</xs:annotatin>
Fix the spelling error and the problem should go away.

Categories