AJAX Call Return PHP Value Empty - php

i have a problem about ajax call, i dont get what exactly why i still getting this empty success call. i tried the past solution to solve this but i don't know what the cause of this.
as you can see this my table then when i click the action of update, delete, or, add, even print_r($_POST) it's still empty.
then when i go to console i got this error.
the value of selected attr still send to the php file
heres my code :
$(document).on('click', '.update', function(){
var user_ID = $(this).attr('id');
$.ajax({
url:"datatable/account/fetch_single.php",
method:"POST",
data:{user_ID:user_ID},
dataType:"json",
success:function(data)
{
console.log(data);
$('#account_modal').modal('show');
$('#username').prop("disabled", true);
$('#username').val(data.user_Name);
$('#email').val(data.user_Email);
$('#pass').val(data.user_Pass);
$('#con_pass').val(data.user_Pass);
$('#level').val(data.level_ID).change();
$('#status').val(data.user_status).change();
$('#action').val('Edit');
$('#operation').val('Edit');
$('.modal-title').text('Edit Account Info');
$('#user_ID').val(user_ID);
}
})
});
fetch_single.php
include('db.php');
include('function.php');
if(isset($_POST["user_ID"]))
{
$output = array();
$statement = $conn->prepare(
"SELECT * FROM `user_accounts`
WHERE user_ID = '".$_POST["user_ID"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["level_ID"] = $row["level_ID"];
$output["user_Name"] = $row["user_Name"];
$output["user_Pass"] = decryptIt($row["user_Pass"]);
$output["user_Email"] = $row["user_Email"];
$output["user_status"] = $row["user_status"];
}
echo json_encode($output);
}
or it's might be the cause of problem is the design template?

i solve this issue, in my requested php file i change my $_POST to $_REQUEST if your data in ajax look like
data:{user_ID:user_ID}
or
data: "fname="+fname+"&lname="+lname
this might work for you, then if your data look like this data:new FormData(this) maybe you should use this type
data:{user_ID:user_ID}
to work the request and execute your sql.
but the best solution i got is change your
method:"POST"
to
type:"POST"
to solve this problem.
if your data.success_variable is undefined add
header('Content-type: application/json.');
to your requested php file.
Related topic:
ppumkin5 answer to
JQuery Ajax is sending GET instead of POST

Related

Pass value from JQUERY to PHP ,and return a JSON

When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.

Catch Ajax data variables in PHP?

I'm trying to get the data used below to be caught in my alives.php page.
Essentially, alives.php requires a variable $passcode.
How do I pass the content of data below as the variable $passcode through a POST request?
<script>
$(document).ready(function() {
$('#alive').click(function () {
var data = '<?php $row['code']; ?>';
$.ajax({
type:"GET",
cache:false,
url:"alives.php",
data:data, // multiple data sent using ajax
success: function (html) {
}
});
return false;
});
});
</script>
alives.php
<?php
require("database.php");
$checkvote = "SELECT code FROM votes WHERE code = '$passcode'";
$updatealive = "UPDATE votes SET alive = +1 WHERE code = '$passcode'";
$addvote = "INSERT INTO votes (code, alive) VALUES ('$passcode',+1 )";
$checkvoterlt = mysqli_query($con, $checkvote);
if(mysqli_num_rows($checkvoterlt) > 0) {
$result = mysqli_query($con, $updatealive) or die(mysqli_error());
} else {
$result = mysqli_query($con, $addvote) or die(mysqli_error());
}
mysqli_close($con);
?>
So much is wrong.
Problem 1: You are specifying a GET request: $.ajax({ type:"GET",. If you want it to be POST:
$.ajax({
type:"POST",
Problem 2: Your javascript data variable should be key: value pairs like:
var data = { 'passcode' : code };
Then in PHP get the data with $_POST['passcode']
This sort of passcode should NOT be passed to the client side, as it can be easily manipulated.
Instead, store such information in a $_SESSION variable (assumes you've started your PHP with session_start), as this will keep the value safe, pass it to all pageloads where it may be needed, and be impossible to manipulate (while it is possible to hijack someone else's session, a malicious user still won't be able to actively change the value)

jQuery ajax returning 'Object Object'

I am trying to send data to a PHP script using jQuery Ajax. For some reason the Ajax request is throwing up an error and returning the following data from the PHP script - [object Object]
I've copied my code in below. I've also copied code using the exact same method elsewhere on the page which seems to work fine!
Can anyone explain why this is happening?
Firstly, the code that is working fine
jQuery
$("#reqtable a").click(function(){
var cells = [];
var name;
var account;
var module;
var email;
$(this).parent().parent().find("td").each(function(){
cells.push($(this).html());
});
$(this).parent().parent().find("input").each(function(){
email = $(this).val();
});
$(this).parent().parent().prop('id', 'die');
name = cells[0];
account = cells[1];
module = cells [2];
$.ajax({
url: "release.php",
type: "POST",
data: {name: name, account: account, module: module, email: email},
success: function(){
$("#die").remove();
}
});
});
PHP
<?php
include('../../dbconnect.php');
$name = $_POST['name'];
$account = $_POST['account'];
$email = $_POST['email'];
$module = $_POST['module'];
$releasequery = "INSERT INTO release_assignment(name, account, email, module) VALUES ('$name', '$account', '$email', '$module')";
$release = $conn->query($releasequery);
$erasequery = "DELETE FROM request_assignment WHERE email='$email' AND module = $module";
$erase = $conn->query($erasequery);
?>
And now the code that IS NOT working.
jQuery
$("#downloadtable a").click(function(){
var dlcells = [];
var dlname;
var dlaccount;
var dlmodule;
var dlemail;
var dlsub;
var dlpath;
$(this).parent().parent().find("td").each(function(){
dlcells.push($(this).html());
});
$(this).parent().parent().find("input.dlemail").each(function(){
dlemail = $(this).val();
});
$(this).parent().parent().find("input.dlsub").each(function(){
dlsub = $(this).val();
});
$(this).parent().parent().find("input.dlpath").each(function(){
dlpath = $(this).val();
});
$(this).parent().parent().prop('id', 'die2');
dlname = dlcells[0];
dlaccount = dlcells[1];
dlmodule = dlcells [2];
$.ajax({
url: "download.php",
type: "POST",
data: {dlname: dlname, dlaccount: dlaccount, dlmodule: dlmodule, dlemail: dlemail, dlsub: dlsub, dlpath: dlpath},
success: function(data){
$("#die2").remove();
},
error: function(data){
$('#downloaddiv').html('<p>' + data + '</p>');
}
});
});
PHP
<?php
include('../../dbconnect.php');
$name = $_POST['dlname'];
$email = $_POST['dlemail'];
$account = $_POST['dlaccount'];
$module = $_POST['dlmodule'];
$path = $_POST['dlpath'];
$submission = $_POST['dlsub'];
$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
$feedback = $conn->query($feedbackquery);
$erasequery = "DELETE FROM uploaded_assignments WHERE email='$email' AND unit = $module";
$erase = $conn->query($erasequery);
?>
When I comment out all the PHP code and simply put echo ($_POST['dlname']); it returns the data [object Object]
Can anyone explain what is going on and why it seems to work with one block of code but not the other?
Thanks!
Chris
Update: It might be worth mentioning that the initial link ('#downloadtable a') actually instigates a file download as well as the ajax call, whereas in the code that is working it simply makes the ajax call and nothing else. I don't know if this is throwing a spanner in the works but thought it worth mentioning.
Update 2: Using the jQuery Ajax error callback as described below I'm getting the following response:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
AJAX error: error :
The code I've used in the error callback is as follows:
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
Unfortunately I don't understand what this means. Can anyone shed any light on this?
Update 3 OK, I've found the reason for Ajax blowing up on me, and it relates to update number 1 (above). Basically because the link is to a file download (a .docx file) it seems to be causing the problem with ajax. When I change the link to href='#' instead of href="document.docx", the ajax and PHP script works.
This throws up a new question, of course - how can I get the link to download the file whilst simultaneously updating the database?
Specify a dataType and use console to debug your data response.
Also, notice that the error callback contains the following arguments and not any "data";
error Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
Update
The target file download.php might be throwing an exception. Possibly because of some missing quotes around $email on the line;
$feedbackquery = "INSERT INTO feedback_assignments(name, email, level, unit, assignmentpath, submission) VALUES ('$name', $email, '$account', '$module', '$path', '$submission')";
Debug download.php and make sure it generates the expected output/response.
I advice you to escape the values you are using to build your SQL query with to prevent SQL injection.

jQuery JSON PHP Request

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).

jquery.ajax with php

I have just started working on php. It's a very good lang as I'm feeling but some point I get stuck as I'm new to this.
My javascript code
var pv = $("#txtStart").val();
var av = $("#txtStartNextLevel").val();
var au = $("#fileStartPlay").val();
alert(pv+" "+av+" "+au);
var myau = au.split('\\');
$.ajax({
type:"POST",
url:php_url,
data:"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}",
contentType:"application/json",
dataType:"json",
success:function(){
alert("done");
},
error:function(){
alert(response);
}
});
My PHP code.
<?php
if(file_exists("Text.txt"))
{
$fileName = "Text.txt";
$fh = fopen($fileName,"a")
$Starts = $_POST["startPoint"];
$NextLevel = $_POST["nextLevelPoint"];
$AudioFileName = $_POST["audioFile"];
$code .=$Starts."*".$NextLevel."_1*".$AudioFileName."\"";
fwrite($fh,$code);
fclose($fh);
}
?>
When I run this it executes but doesn't write the values in the variable
$Starts,$NextLevel,$AudioFileName**.
And further if I write the same ajax procedure in
$.post(php_url,{startPoint:pv,nextLevelPoint:av,audioFile:myau[myau.length-1]},function(data){});
this works fine and write the content in the file.
Also As I'm using post method it should not display the values in Address bar what I'm passing to write. But it's showing those values in both the method.
localhost://myphp.php?txtStart=Start&fileStartPlay=aceduos.jpg&txtStartNextLevel=adfd
Please guide me where I'm lacking...
Replace the value bellow (with quotas)
"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}"
to
{startPoint:pv, nextLevelPoint: av, audioFile: myau[myau.length-1]}
Do what Burak TAMTURK said, and also get rid of
contentType:"application/json",
$_POST data should be in content-type application/x-www-form-urlencoded, which is the default.

Categories