I'm trying to test an ajax call on post by doing the following just for testing purposes, but for some reason the call is never successful. I've been searching around and there isn't much that I could find that would explain why this isn't working.
$.ajax({
type: "POST",
url: "file.php",
success: function(data) {
if(data == 'true'){
alert("success!");
}
},
error: function(data) {
alert("Error!");
}});
file.php contains the following:
<?php
return true;
?>
Can someone please point me in the right direction. I realize that this may seem simple but I am stumped. Thank.
return true will make the script exit. You need:
echo 'true';
Firstly check your paths. Is file.php residing in the same folder as the file that your javascript is contained in?
If your path is incorrect, you will get a 404 error printed to your javascript console if you are using chrome.
Also you should change your php to:
<?php
echo 'true';
Once your path is correct and your php is amended you should be good to go.
Have you tried by accessing to the file directly and see if it outputs something?
return true shouldn't be use in that case (or any other, it's better to use exit or die), everything get by a AJAX call is hypertext generated by server side, you should use (as they pointed you before echo 'true';)
You could also try a traditional AJAX call XMLHttpRequest (without JQuery) if problem persists, and then check if there is any problem between the request and server..
EDIT: also, do not check by comparison, just make an alert to 'data' to see what it gets.
In addition to the echo 'true' suggestion, you can also try to alert the actual data that's returned to ajax. That way you can see if you have the proper value/type for your if statement.
success: function(data) {
alert(data);
}
try this, the new ajax syntax
$.ajax({ type: "POST", url: "file.php" }).done(function(resp){
alert(resp);
});
Here is correct way:
$.ajax({
type : "POST",
url : "file.php",
success : function (data) {
/* first thing, check your response length. If you are matching string
if you are using echo 'true'; then it will return 6 length,
Because '' or "" also considering as response. Always use trim function
before using string match.
*/
alert(data.length);
// trim white space from response
if ($.trim(data) == 'true') {
// now it's working :)
alert("success!");
}
},
error : function (data) {
alert("Error!");
}
});
PHP Code:
<?php
echo 'true';
// Not return true, Because ajax return visible things.
// if you will try to echo true; then it will convert client side as '1'
// then you have to match data == 1
?>
Related
I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.
I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST
So, I am using jquery to make an ajax call to a php script on my server.
For some reason I cannot figure out, however, there is no querystring sent. Using var_dump() on the $_GET object shows that it is an empty string, and Chrome's network activity developer tool indicates no string is sent.
$.ajax({
"url":"../script/content.php",
"settings": {
"dataType":"html",
"type":"GET",
"data":{
"id":$(this).prop('id')
}
}
}).done( function(msg) {
//$('#debug').html(msg);
$('#dialog').html(msg);
$('#dialog').load(function() {
$('#close').click(function() {
$('#over').fadeOut(fadeTime);
});
if ($('#unique') > 0) {
$('#unique').load(function(){
$('#over').fadeIn(fadeTime);
});
}
else {
$('#over').fadeIn(fadeTime);
}
});
});
I had tried the ajax call without the quotes where they weren't necessary before hand, and the result was the same... I just put those in because I thought it might be the problem... though I think that in such notation the quotes don't make a difference unless one of the field values is supposed to be a string.
Is there anything clear in that code which might cause a querystring not to be sent? I guess there is a problem with my syntax... I just can't see it.
The #dialog load callback seems to never be called, either... but I guess that is another question.
Try this
$.ajax({
//The link we are accessing with params
url:'http://example.com/script/content.php'
+ '?id='
+ $(this).prop('id'),
// The type of request.
type: "get",
//The type of data that is getting returned.
dataType: "html",
error: function(){
//something here
},
success: function( strData ){
//something here
}
});
i know this question was probably asked 1 million times, but for the 1.000.001 time :)
i need to call a php function from JavaScript. And i am having a bit of an argument on if ajax will do it.
i don't want to send any data just a ajax call that will call and run that function.
here is what i have so far:
$.post('functions/test.php', function() {
console.log("Hooray, it worked!");
});
is this gonna run the test.php ?
thanks
It definitely runs the test.php, to check it you may do sth. on succes
$.ajax({
type: "POST",
url: "ajax/test.php",
success: function(data) {
alert(data);
}
});
But what's the purpose of sending if no data is send?
Most likely, yes. I can't guarantee it because I don't do jQuery.
This, however, will definitely run it no problems (except versions of IE so old you shouldn't care about them):
var a = new XMLHttpRequest();
a.open("GET","functions/test.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
console.log("Hooray, it worked!");
// optionally, do stuff with a.responseText here
// a.responseText is the content the PHP file outputs, if any
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
Yes the test.php script will run, and you can grab the output from the test.php script like this (if you want to):
$.post('functions/test.php', function(data) {
//the `data` variable now stores the server response (whatever you output in `test.php`)
console.log("Hooray, it worked!");
});
In JQuery you can do:
$.post('functions/test.php', function(data) {
alert(data);
});
Whatever is returned in test.php will be put into the variable "data"
So you can do any php functions you need to in test.php and send the output back.
I always use
jQuery.ajax("url.php");
I have a simple checkbox, on click it sends XHR to PHP page , php processes correctly and I use json_encode($response) to return. But instead of a simple true or false I get the source code for the page and it is causing a "parsererror" of course.
ajax call as follows
$.ajax({
type: "post",
url: "myprocessor.php",
dataType: 'json',
data: { "id" : idnumber, "action": "makeLive", "isLive" : "1" },
beforeSend: function(data) {
$("#ajaxInProgress").addClass('progress');
},
success: function(data) {
$("#status").removeClass().addClass((data.error === true) ? 'error' : 'success').text('Success! Appraiser is NO LONGER Live ').slideDown('slow');
},
error: function(data) {
$("#status").removeClass().addClass('error').text(' - Changing the Live status for this appraiser to "Not Live" has failed - APPRAISER IS STILL LIVE IN SYSTEM, please try again').slideDown('slow');
},
complete: function(data) {
$("#ajaxInProgress").removeClass('progress');
setTimeout(function() {
$("#status").slideUp('slow').removeClass();
},2000);
}
});
The php I post to is as follows:
if (isset($_POST['action'])) {
if($_POST['action']=='makeLive') {
$checkappraiser=mysql_query("SELECT * FROM table WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if (mysql_numrows($checkappraiser)>0) {
$livesetting=mysql_result($checkappraiser,0,"live");
$livesetting=!$livesetting;
$runSql = mysql_query("UPDATE table SET live='$livesetting' WHERE id='".mysql_real_escape_string($_POST['id'])."'");
if(!$runSql) {
$return['error'] = true;
} else {
$return['error'] = false;
}
}
}
echo json_encode($return);
}
Any suggestions would be great.
I am getting the proper data passed
I am getting the correct data updated in DB
My response is coming back as a parser error because it is trying to parse the source code as a json array.
Just a quick check, do you put <?php at the beginning of your php file?
That, or you're doing something wrong in your webserver, not passing files through to php correctly. Does hitting the php file directly load the source or the result?
If you hit page.php, does it load the same thing as if you hit page.phP or pHP, etc? It matters to web server filters, depending on the web server...
If you use tomcat for java, for example... you can turn off case sensitivity for finding files, but it does not turn off case sensitivity for mapping files to filters or servlets, so .jsp would load the jsp servlet, but .jsP would not.