I can't get each data from PHP file, i'm always having AJAX failure, i tried many things, and looked for some pages for this problem but i can't find any solution, this is where i came last.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="someclass"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
e.preventDefault();
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$jsondata1 = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
echo json_encode($jsondata1);
}
mysqli_close($con);
I think there is no need to share HTML file, but if you want i can share with you.
Thank You!
You are overriding the array value in the loop and echo $jsondata1, so you are sending many different arrays with the echo inside the loop, try this code:
$jsondata1 = array();
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
echo json_encode($jsondata1);
e.preventDefault(); is a problem. e is not defined and if it was the default action would have already occurred by the time the success function was called. Try
$('a[class="someclass"]').click(function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
You need to encode the complete response.
when you echo each encoded it will not work.
Do something like
$jsonArray = array();
while(){
array_push($jsonArray, array($row['data1'], $row['data2']);
}
echo json_encode($jsonArray);
You're calling json_encode multiple times when what you need to be doing is assigning those intermediate variables to an array and encode that array using json encode for the return.
PHP:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
$jsondata1 = [];
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
mysqli_close($con);
die(json_encode($jsondata1));
JavaScript:
$(document).ready(function () {
var doc = $(document);
doc.on('click', 'a.someclass', function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
Related
I'm sending an ajax "POST" in my php file. But the problem is the index of the POST is undefined.
This is my sample code in ajax.
$(".add-percentage").click(function(){
var percentage_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
data: { percentage_id : percentage_id },
success: function(data) {
alert(data);
},
error: function(request, status, error){
alert("Error!! "+error);
}
});
});
My php code having an undefined index POST..
if(isset($_POST['percentage_id'])){
$percentage_id = $_POST['percentage_id'];
$query = mysqli_query($conn, "SELECT * FROM percentage WHERE percentage.percentage_id = '$percentage_id'");
}else{
echo "Index is not properly set!";
}
I hope someone can help me. Thanks in advance.
if($_SERVER['REQUEST_METHOD']=="POST"){
$data = file_get_contents('php://input');
print_r($data); // for testing purpose.
/*
$query = mysqli_query($conn, "SELECT * FROM percentage WHERE percentage.percentage_id = $data[0]['pecentage_id']");
*/
}else{
echo "Index is not properly set!";
}
Please use this code for ajax
$(".add-percentage").click(function(){
var percentage_id = $(this).data('landing_id-percentage');
$.ajax({
url: 'ajax/readPercentage.php',
type: 'POST',
dataType: 'json',
data: { percentage_id : percentage_id },
success: function(data) {
alert(data.status);
},
error: function(request, status, error){
alert("Error!! "+error);
}
});
});
<?php
$result_array= array();
if(isset($_POST['percentage_id'])){
$percentage_id = $_POST['percentage_id'];
$select_query = "SELECT * FROM percentage WHERE percentage.percentage_id =".$percentage_id;
$query = mysqli_query($conn,$select_query);
$result_array['status'] = 'success';
$result_array['success_msg'] = 'Data get successfully';
}else{
//echo "Index is not properly set!";
$result_array['status'] = 'failure';
$result_array['error_msg'] = 'Index is not properly set!';
}
echo json_encode($result_array);
die();
?>
I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm trying to check if a field is just present into db before submit a form.
So I add the keyup event to that field to get data from db with ajax.
So where I have the form I add this code:
$(document).ready(function (){
$("#matricola").keyup(function () {
$.ajax({
type:"get",
url: "getMatricolaAjax.php",
data: {'type':'user', 'matricola':$("#matricola").val()},
dataType: "text",
success: function(result){
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ result +" già presente!!");
},
error: function(){
console.log("KO");
}
});
});
});
And this is my getMatricolaAjax.php:
<script src='js/jquery-2.1.4.js' type="text/javascript"></script>
<?php
require_once 'config.php';
require_once FUNCTION_PATH.'/dbFunction.php';
if($_GET['type'] == "user"){
$queryMatricolaMatch = 'select * from user where matricola = "'.$_GET['matricola'].'"';
}else{
$queryMatricolaMatch = 'select * from 150ore where matricola = "'.$_GET['matricola'].'"';
}
echo $queryMatricolaMatch;
$conn = dbConnect($USERDB, $PASSWORDDB, $NAMEDB);
$matricola = dbQueryGetResult($queryMatricolaMatch);
dbDisconnect($conn);
echo $matricola;
It works for half, beacause in result I obtain all html code from getMatricolaAjax.php..
Why??
How can I get only matricola??
Comment or remove dataType: "text" and try again.
$.ajax({
type:"get",
url: "getMatricolaAjax.php",
data: {'type':'user', 'matricola':$("#matricola").val()},
// dataType: "text",
success: function(result){
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ result +" già presente!!");
},
or else you can use json_encode() in PHP to get data as JSON object array.
You should use POST to check for value in database before submitting a form.
$(document).ready(function (){
$("#matricola").keyup(function (e) {
var thevalue = $(this).val();
$.post('getMatricolaAjax.php',{'type':'user','matricola':thevalue},
function(data) {
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ data +" già presente!!");
});
});
});
And the php file
<?php
require_once 'config.php';
require_once FUNCTION_PATH.'/dbFunction.php';
$conn = dbConnect($USERDB, $PASSWORDDB, $NAMEDB);
if($conn->real_escape_string($_POST['type']) == "user"){
$queryMatricolaMatch = 'select * from user where matricola = "'.$conn->real_escape_string($_POST['matricola']).'"';
}else{
$queryMatricolaMatch = 'select * from 150ore where matricola = "'.$conn->real_escape_string($_POST['matricola']).'"';
}
$matricola = dbQueryGetResult($queryMatricolaMatch);
dbDisconnect($conn);
echo $matricola;
This should work, but I have no idea what dbQueryGetResult is supposed to do so you should post it too.
Note:If you use PDO edit remove 'real_escape_string' function and use other methods of sanitization
I'm making an AJAX call to a fairly simple PHP function. The response should be a JSON object to be manipulated, but my response is always an empty object.
Relevant Code:
index.html's AJAX Call:
$( function() {
$('#dates').on('submit', function (e) {
var start_time = new Date().getTime();
e.preventDefault();
var submitData = $('#dates').serialize();
console.log(submitData);
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
dataType: 'json',
beforeSend: function(){
$('#loading').show();
},
success: function(data) {
console.log(data);
$('#loading').hide();
},
error:function(xhr, desc, err){
alert('You tried to send an AJAX request, but something went wrong.\n Please Contact the NASR WebDev Team');
console.log(xhr);
console.log("Details: " + desc +"\nError: "+ err);
}
});
});
});
inflow.php's array creation and echo:
<?php
$msqlStart = $_POST['start_date'];
$msqlEnd = $_POST['end_date'];
$inflowQuery=
"SELECT
COUNT,
QUEUE_ID,
QUEUE_GROUP,
INFLOW_DATE,
LINE_OF_BUSINESS
FROM
ticket_inflow.inflow
WHERE
ROUTE_STATUS = 'Inflow'
AND inflow_date between ? and ?";
$connect = new mysqli($host, $user, $password, $database);
if ($connect->connect_error){
die("Failed to Connect:.".$connect->connect_errno.": ".$connect->connect_error);
}
if(!($statment = $connect->prepare($inflowQuery))){
die('Error in Preparation Error Number:%d Error: %s');
}
if(!$statment->bind_param('ss', $msqlStart, $msqlEnd)){
die ('Error in Binding');
}
if(!$statment->execute()){
die('Error In Execution');
}
$statment->bind_result($inflowCount, $inflowQueue, $inflowQG, $inflowDate, $inflowLOB);
$a_json = array();
$jsonRow = array();
While($statment->fetch()){
$UID = 0;
$jsonRow['UID'] = $UID++;
$jsonRow['count'] = utf8_encode($inflowCount);
$jsonRow['inflow_date'] = utf8_encode($inflowDate);
$jsonRow['queue'] = utf8_encode($inflowQueue);
$jsonRow['queue_group'] = utf8_encode($inflowQG);
$jsonRow['lob'] = utf8_encode($inflowLOB);
array_push($a_json, $jsonRow);
}
$jsonReturn = json_encode($a_json);
echo $jsonReturn;
?>
If I go directly to inflow.php and pass it parameter's identical to what the page passes it, I get what appears to be a nice JSON object, however when I look at the response Chrome Developer's Tools I get:
[]
And nothing more.
You are sending form data, not json;
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
//contentType: "application/json",<-- remove this
dataType: 'json',
I used tje following code to populate a combobox with data. It works in Firefox and Google Chrome but not in IE8.
$.ajax({
type: "POST", url:"reg/data/data.php",
data: {
cat:"Y",
//toUser: "4",
// ignoreMessages:"1
},
success: function(data){
$.each(data, function (i, elem) {
$('#catogery').append( new Option(elem.id) );
//console.log(elem);
});
}
});
PHP:
$result = mysql_query("SELECT DISTINCT CATCODE from subjectmaster");
$messages;
header('Content-type: application/json');
$return_arr = array();
while($row = mysql_fetch_array($result)) {
$row_array['id']=$row[0];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
Remove the comma from after the cat:
$.ajax({
type: "POST", url:"reg/data/data.php",
data: {
cat:"Y"
},
success: function(data){
$.each(data, function (i, elem) {
$('#catogery').append( new Option(elem.id) );
//console.log(elem);
});
}
});
You have mentioned "," in data array and there is no element after that. Remove "," and it should work.
data: {
cat:"Y", //<------Remove this comma
//toUser: "4",
// ignoreMessages:"1
}