I have a page from which I am trying to make an AJAX call, but it isn't working, and I'm stumped as to why. My call is:
$.ajax({
type: "GET",
url: "<relative URL>/index.php?action=x",
dataType: "JSON"
}).success(function(person) {
alert(person.name) //alerts naem
});
return false;
});
and the PHP is:
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
}
?>
I don't THINK the issue is a faulty URL, since it is a c/p of working calls. It seems to me (but I'm not sure) that it chooses to reuse the old 'action-values' from when the source page was loaded originally. For some reason it completely ignores my action-value…?
Any ideas?
Try moving the PHP into its own file rather than the index.php, which I assume is your main PHP file.
$.ajax({
type: "GET",
url: "/ajax.php?action=x",
dataType: "JSON",
success: function (person) {
console.log(person.name);
}
});
This should be a separate file. Call it ajax.php for an example.
<?
// ajax.php
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
die(json_encode($person));
}
?>
Just make sure ajax.php is in the route of your project and this should work. Check the console.log if it doesn't.
Try moving the variable into 'data':
$.ajax({
type: "GET",
url: "<relative URL>/index.php",
data: "action=x",
success: function (person) {
console.log(person.name);
}
});
Since you are calling index.php with a get parameter, you might be echoing the json_encode and then continuing to output everything else after the if statement.
Try this?
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
exit;
}
?>
I'm assuming you have more content in the index.php below that if statement. If so, the exit; statement would be needed so that you only echo the json and not anything after the if statement.
The ajax response can be viewed in Google Chrome's Dev Tools, under the Network tab.
Let's say you had no exit; statement:
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
}
?>
<html>
<head></head>
<body>
...etc, etc
The ajax response under Dev tools would look something like this:
{"name":"Jon Doe","Reputation":"Good"}<html><head></head><body>... and so on
which would then try to be parsed by the $.ajax into a JSON object.
But this is not possible because <html><head></head><body>... is not valid JSON.
Hope this helps!
Related
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
This is my html code
<td class="saltr" style=" border-color:#000; cursor:pointer;" id="<?php echo $grade["DEALID"];?>" onclick="dealid(this.id)" ><?php echo $grade["DEALINGS"];?></td>
on onclick() javascrip is written.
function dealid(psid)
{
var serow = psid;
//alert (serow)
$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+serow,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});
}
and in printdeal.php page the code is written as
if($_REQUEST["proc"]=='dealing')
{
$dealdatres1=$_REQUEST["dealdatres"];
include_once("../classes/dbqrs.php");
$obj=new qrys();
$qremp="select deals.PROSPECS ,deals.DEALINGS,deals.BUYER,deals.BENEFICIARY,deals.GUIDE,deals.REMARKS ,deals.DATES,salescal.DEALID from salescal left join deals on deals.ID=salescal.DEALID where salescal.DEALID='$dealdatres1'";
$empr=$obj->exeqry($qremp);
$empres=mysqli_fetch_array($empr);
?>
but when I run this code and when i click on it ,it shows a notice as undifined "proc" .
Please help me to solve this.
It looks like you have placed you function somewhere out of usual global scope. I don't know what should be changed as far as I cannot know your structure.
At first, move all function's content into onclick:
onclick='$.ajax({url:"../views/printdeal.php?proc=dealing",data:"dealdatres="+this.id,success:
function(z)
{
//alert("hiiiii")
alert(z);
//window.location="printdeal.php";
}
});'
and get a proof that there is something wrong with the name/placement only.
P.S. BTW read about addEventListener/attachEvent as strong and more convenient alternative to "onclick" usage.
We have kinds of ways to get the function,one of them like this:
You may write the code in view page :
$.ajax({
url: "<?php echo url('/soc/cnews/savetop') ?>",
type: 'post',
data: "sets=" + $("#top10").val(),
sync: false,
dataType: 'json',
success: function(data) {
if (data.status == 'success') {
window.location.reload();
} else {
alert(data.msg);
}
}
});
and the write the code in page which get data:
if($success){
echo "{status:'success',msg:'victory'}";
}else{
echo "{status:'failur',msg:'I am sorry to failure :('}";
}
And again: if you want get data via ajax,make sure print or echo the message on data page.
Try This
$.ajax({type: "POST",url: "../views/printdeal.php",data: { proc:"dealing",dealdatres=serow }});
if your problem in php, i think you can check values in global variables with
<pre>
<?php
var_dump($_REQUEST);
?>
</pre>
the result can be like this
array(2) {
["asd"]=>
string(3) "qwe"
["zxcv"]=>
string(5) "lkjsf"
}
that's result is from my localhost with url localhost/a.php?asd=qwe&zxcv=lkjsf
I am very new to PHP and Javascript.
Now I am running a PHP Script by using but it redirect to another page.
the code is
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
How do I execute this code without redirecting to another page and get a popup of success and fail alert message.
My script code is -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
Thanks in advance.
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple link, like you have in the question. However I'm going to modify the structure a bit to keep it a bit cleaner:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
I'm assuming here that this code is a double-quoted string with interpolated variables.
JavaScript
Since you tagged jQuery... I'll use jQuery :)
The browser will listen for a click event on the link and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
As you can see, I'm using .data() to get the GET parameters.
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
PHP
Looks like you know what you're doing here. The important thing is to output the appropriate data type.
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
Instead of <a href>, use ajax to pass the values to your php and get the result back-
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});
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
?>
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).