Ajax and php Response doesn't work - php

I really like the help here and normally i figured out any Problem so far just by reading the existing Posts. However this time i can't quiet figure out whats wrong in my code.
I want to write dataildata values of a specific Tablerow in a form. The Data is stored in an mysql database and I access it with php.
The Probleme is that it seems that the Ajax request isn't working. neighter the success nor the error Event get triggered. Although the alter(id) works just fine.
Here is the Ajax call of the function:
$( "#table1 tbody tr" ).on( "click", function() {
var id = $(this).attr('id');
alert( id );
$.ajax({
type: 'POST',
url: 'getDetailData.php',
dataType: 'json',
data: {id : id },
success: function(data){
$("#inputWstId").val(data.WST-ID);
$("#inputSerialNumber").val(data.SERNO);
$("#inputName").val(data.NAME);
alert(data.NAME);
alert ("Test");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
and here is the .php File:
<?php
header('Content-Type: application/json');
$connect = include 'connect.php';
if (isset ($_POST['id'])){
$id= $_POST['id'];
}
$query = " select * FROM pci WHERE id= ". $id ;
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
"WST-ID" => $ligne["WST_ID"],
"SERNO" => $ligne["SERNO"],
"NAME" => $ligne["NAME"]
);
mysql_close($connect);
echo (json_encode($data));
?>
If you Need more sourcecode or anything else just let me know- Thank you so much for your help!!
WST_ID instead of WST-ID really worked - thank you so much !!
Why is it, that I can't use a "-" in my values ... guess there is a lot more to learn ;)

In the PHP part you need add two more headers :
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
Add the two line of coding with the:
header('Content-Type: application/json');
change the:
echo (json_encode($data));
to:
print $my_json = json_encode($data);
or:
print_r ($my_json);
Hope it will work.

I think you need to give absolute url. Only getDetailData.php will not work. Try http://xyzabc.com/getDetailData.php

Related

AJAX Call Return PHP Value Empty

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

AJAX SQL JSON Not Working

My AJAX seems like not working. It should load patient details into a dropwdown.
this is my ajax code:
function PopulatePatient()
{
$("#PatientDropDown").empty();
$("#PatientDropDown").append("<option>Loading.....</option>");
$.ajax({
type:"POST",
url:"../listener/populatePatientName.php",
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
$("#PatientDropDown").empty();
$("#PatientDropDown").append("<option value=''>-Select Patient-</option>");
$.each(data,function(i,item)
{
$("#PatientDropDown").append('<option value="'+ data[i].patientUserId +'">'+ data[i].patientFirstName +'</option>');
});
},
complete: function()
{
}
});
}
This is my PHP Code (populatePatientName.php):
<?php
include '../core/init.php';
$sql = mysql_query("SELECT patientUserId,patientFirstName FROM patientdetails");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[]=array
(
'patientUserId' => $row['patientUserId']
'patientFirstName' => $row['patientFirstName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
This is my HTML Code:
<select class="form-control" id="PatientDropDown">
</select>
This code works in my friend PC. My database and query are running well. Table contained data.
My code stop at this point :
$("#PatientDropDown").append("Loading.....");
It does not enter ajax. Any solution?
try this line before $.each() function in ajax success
data= JSON.parse(data);
Use "GET" instead of "POST" into your ajax type.
Your script is absolutely fine, but you do not have any event which will trigger PopulatePatient() function. Run the function to get data. Use console.log(data) to check whether your php is sending data or not.
Try to go to populatePatientName.php using web browser, it should return JSON data
I found the solution, I forgot the comma,
<?php
include '../core/init.php';
$sql = mysql_query("SELECT patientUserId,patientFirstName FROM patientdetails");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[]=array
(
'patientUserId' => $row['patientUserId'],
'patientFirstName' => $row['patientFirstName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
$data[]=array
(
'patientUserId' => $row['patientUserId'],
'patientFirstName' => $row['patientFirstName']
);
Two questions:
- It is included jquery in head tag like this?
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
- To populate try using a button like:
<input type="button" onClick="populatePatient()" />

Having trouble posting jquery onto php

I'm currently having some trouble posting a variable on jQuery for MySQLi SELECT on a PHP page.
Code of jQuery:
$("#carta1").click(function()
{
cartaId = document.getElementById("carta1").value;
console.log(cartaId);
ajaxGetResults = $.ajax({
context: this,
type: "POST",
url: "darResposta.php",
data: {'cartaId' : cartaId},
cache: false,
dataType: "json"
})
.done(function(data){
$('#3').html(data);
console.log("Avançou para a terceira parte");
$("#2").hide();
$("#3").show();
})
.fail(function(){
console.log('Erro ao buscar dados');
$("#2").hide();
$("#3").show();
$('#3').html("Deu erro");
});
});
Code of PHP:
if(!$conn)
{
echo "Falhou a ligação à base de dados";
}
else
{
if(isset($_POST['cartaId']))
{
$cartaId = $_POST['cartaId'];
$res = mysqli_query($conn,"
SELECT cartaNome, cartaDescricao
FROM tarot_cartas
WHERE cartaId = ".$cartaId
);
$data = array();
while($row = mysqli_fetch_assoc($res))
{
$data=$row;
}
echo json_encode($data);
}
}
Tried several approaches to this problem such as putting the $cartaId outside the if statement with a direct $_POST, and nothing happened.
Would appreciate if you could shed some light on this problem.
Thanks for taking the time to read and suggest a solution.
use below code
data: { 'cartaId' : cartaId },
instead of
data: {"data":JSON.stringify({'cartaId' : JSON.stringify(this)})},
Solution:
1.Remove this
data: {"data":JSON.stringify({'cartaId' : JSON.stringify(this)})},
2.Replace This one
data: { cartaId: cartaId }
Hope it works....
The jq you have will post a variable to the url.
To debug you should first check in a console (i use firebug) for mozilla) if the request is sent. Using firebug you can see the names of the POST variables you send.
Following this you should check what values get received on the server side by doing
var_dump($_POST);
Finally get the correct variable into your query. You can also debug the query by viewing the log file or, depending on whether you are using a framework, something like CI:
db->last_query();

Xml reply from PHP to post of jquery Ajax

i have a javascript code that requests a php page to provide it with list of names that are currently online and update a Table, but i have a problem sending it back in form of an array, someone told me that this is usually done using XML, but i dont know how to start.
javascript Post method:-
$.post( "updateTable.php", POSTdata,
function( data ) {
$("#mytable").last().append('<tr><td>'+data+'</td></tr>');
}
);
the php file:-
include("connect.php");
$query1 = "SELECT * FROM formtable";
$result_id = mysql_query($query1, $global_dbh)
or die ("display_db_query:" . mysql_error());
while ($table_array = mysql_fetch_object ($result_id))
{
$rows[] = $table_array;
}
foreach ($rows as $temp ) {
if ($temp->isOnline==1)
$newRow[] = $temp->name;
}
echo "$newRow";
mysql_close($global_dbh);
Please excuse any syntax or semantics in my code, i am a beginner.
How can i populate my table using ajax callback function, and in what form the data will arrive there, and how can i use xml to help me.
Many thanks in advance.
A quick example of json:
var table = $("#mytable").last();
$.ajax({
type: 'post',
url: "updateTable.php",
dataType: 'json',
data: POSTdata,
success: function(data){
jQuery.each(data, function(i, row){
//console.log(row);
table.append('<tr><td>'+row.name+'</td></tr>');
});
}
});
and in php file, instead of :
echo "$newRow";
replace with:
echo json_encode($newRow);
That's it!

Retrieve data using ajax from php

I have an ajax code which passes data to php and then retrieves data from php...
function updateDatabase(syncData){
$.ajax({
type : 'POST',
async: false,
url : 'php/syncData.php',
dataType : 'json',
data: {myData : syncData}, //i even used this "mydata"+syncData
success : function(result){
res = result;
},
error : function() {
res = false;
}
});
return res;
}
And here's my php code...
<?php
include("database.php");
if(isset($_GET['myData'])){
$data = $_GET['myData'];
$insert = "INSERT INTO `mydata` VALUES (NULL,'$data')";
mysql_query($insert);
$data = mysql_insert_id();
echo json_encode($data);
}
?>
Here's javascript function that pass/calls ajax...
<script>
var theData = "blahblah";
var alertData = updateDatabase(theData);
alert(alertData);
</script>
the problem is that when i use htmt/text as data type it alerts empty/blank output, but when i used json as data type it alerts false where i conclude it went to error function not to success... anyone knows what's the proper way to do this? or maybe i'm just missing something? Thanks!
Well, you're posting the data using jQuery, but you're looking for a $_GET value in the PHP. Fix that and see if it changes anything.
Edit: It should look like this:
...
if(isset($_POST['myData'])){
$data = $_POST['myData'];
...
Try to set content type in your PHP file:
header( 'Content-Type: application/json' );
Then echo your data:
echo json_encode( $data );
Then exit script:
exit;
Hope it helps!

Categories