My problem is that I can't retrieve the result of the mysql result via ajax, please help
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd')
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name'];
//array_push($final,$result);
//print_r($result);
echo json_encode($result);
Change PHP Code as below
$final = array();
$sql_courses = mysql_query("SELECT course_id, course_name FROM course") or die(mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
echo json_encode($row_courses);
change php code as below:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data: {
user_id: user_id
},
dataType: 'json',
success: function (msg) {
$('p').html(msg.course_name);
}
});
Its better to send it with a key value like this:
And its better to use console.log(variable); to check variable's content
ajax code:
$.ajax({
type: "POST",
url: "do_find_courses.php",
//data:{question_id:question_id,answer:answer},
data:{user_id:user_id}, dataType:'json',
success:function(msg) {
alert ('asdasd');
console.log(msg);//You should check output of this in browser console
// $("#quiz_form,#demo1").addClass("hide");
// $('#result').show();
$('p').html(msg.cname);
}
});
PHP code:
$final=array();
$sql_courses=mysql_query("SELECT course_id, course_name FROM course") or die (mysql_error());
$row_courses = mysql_fetch_array($sql_courses);
$result=$row_courses['course_name']; // this will have first_coures_name (an string)
$final['cname']=$result;
//print_r($result);
echo json_encode($final); //the output should be this {'cname':'first_course_name'}
Related
I am running a query to database which fetch a row and i want to return it as array which can accessed as array['min'], array['max'] etc. if i echo it with specific index, it shows the value correctly in ajax but i am unable to pass complete row through it to the ajax file.
PHP file:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
WHILE($row=mysqli_fetch_array($sql))
{
echo $row['min']; break;
}
mysqli_close($con);
?>
JS file:
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
success: function(res)
{
// alert( res );
alert(res);
}
});
}
This code get right value from mysql but i want to pass full row to ajax and then use each index in ajax itself to put into textboxes.
You can pass array by:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
$result = array();
WHILE($row=mysqli_fetch_array($sql))
{
$result[] = array( "min" => $row['min'], "max" => $row['max'] );
}
mysqli_close($con);
echo json_encode( $result );
?>
On your js, make sure to specify dataType:"json",
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
dataType:"json",
success: function(res)
{
// alert( res );
console.log(res);
}
});
}
Note: It is advisable to use console.log(res); instead of alert() on debugging.
I am trying to perform the below SQL query on page load via JQuery/AJAX. It will not post when I write dataType: 'json', and does not provide an error in the console log.
I have tested the SQL is executing by placing a echo statement. Without the line it echos, with the line it does not.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//Load Questions
var getQuestions= true;
$.ajax({
type: "POST",
url: "comment.php",
context: document.body,
data:{getQuestions:getQuestions},
dataType: 'json', //<--This line here
success: function(data){
$("#updateDisplay").html(data);
}
});
});
SQL (comment.php)
<?php
//connect to db
include 'connect.php';
$getQuestions = $_POST['getQuestions'];;
if($getQuestions==TRUE){
$sqlQuery = "SELECT *
FROM Questions
ORDER BY QuestionID DESC";
$runQuery = mysql_query($sqlQuery) or die(mysql_error());
echo 'Test echo';
echo json_encode($runQuery);
}
After the I have a DIV to place the results:
<div id="updateDisplay">
//PHP loop will go here
I wasn't correctly handling the SQL output to match JSON.
Fixed SQL
$runQueryArray=array();
$sqlQuery = "SELECT *
FROM Questions
ORDER BY QuestionID DESC";
$runQuery = mysql_query($sqlQuery) or die(mysql_error());
while (($row = mysql_fetch_array($runQuery, MYSQL_ASSOC)) !== false){
$runQueryArray[] = $row;
}
echo json_encode($runQueryArray);
}
Also needed to fix my JSON call:
$(document).ready(function() {
var getQuestions= true;
$.ajax({
type: "POST",
url: "comment.php",
context: document.body,
data:{getQuestions:getQuestions},
dataType: 'JSON',
success: function(JSON){
$.each(JSON,function(i,val){
$('#updateDisplay').append('<p>QuestionID: '+ val.QuestionID + ' Title: '+ val.Title+ ' Description: '+ val.Description+' Date Created: '+val.DateCreated+'</p><p><button type="submit" class="postReply" value='+val.QuestionID+'>Reply</button></p>');
});
}
});
});
Hi I have a select box that when it is changed I want the value in a database to be updated via Ajax. Using the console I can see that my saveedit2.php file is not being called.
Select Box
<form><select id="workingpattern">
<?php
if(isset($workingpatterns) && !empty($workingpatterns)){
foreach($workingpatterns as $k4=>$v4) {
?>
<option value="<?php echo $workingpatterns[$k4]["workingpatternid"]; ?>">
<?php echo $workingpatterns[$k4]["text"]; ?></option>
<?php }}?>
</select></form>
Ajax:
<script>
$(document).ready(function(){
$('#workingpattern').change(function(){
var e = document.getElementById("workingpattern");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "saveedit2.php",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>
SaveEdit2.php
<?php
require_once("connect_db.php");
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
?>
There are a few issues that I see. First, I would use 'this' to get the element and use jQuery to get the value since you are using it already. Secondly, you need a name for the value in the data set:
$('#workingpattern').change(function(){
var value = $(this).val();
$.ajax({
url: "saveedit2.php",
type: "post",
data: 'value='+value,
success: function(data) {
console.log(data);
}
});
});
Try
Ajax
$('#workingpattern').change(function(){
var value = $("#workingpattern").val();
$.ajax({
dataType: "json",
url: "./saveedit2.php",
data: {'value':value},
success: function(data){
if(data['result']=="ok")
alert("Done");
else
alert("Error");
}
});
SaveEdit2.php
<?php
require_once("connect_db.php");
$ajax_result = "error";
$value=$_POST['value'];
$sql = "UPDATE employmenthistory SET workingpatternid = '$value' WHERE employmenthistoryid=1";
$result = mysqli_query ($dbc, $sql) or die(mysqli_error ($dbc));
if($result)
$ajax_result = "ok";
echo json_encode(array('result'=>$ajax_result));
?>
I am trying to insert data into a MySQL database using jQuery and AJAX. I have written the query parameters in my add.php file. I would like to show the form data immediatly beneath the form.
jQuery:
jQuery("#addStockInForm").submit(function(e){
e.preventDefault();
dataString = jQuery("#addStockInForm").serialize();
jQuery.ajax({
type: "POST",
url: "add.php",
data: dataString,
dataType: "json",
success: function(data) {
//$("div#showinstant").html(data);
alert(data);
}
});
});
add.php file
require 'foo.config.php';
if(isset($_POST['addStockIn'])) {
$query = "INSERT INTO stockin ( serialno, project_id, ...... etc. ) VALUES
(`:serialno, :project_id, ....... etc. )";
add-stockin.php file
<form class="form-horizontal" id="addStockInForm" method="post">
.....
</form>
you should return the data from your php code back to your frontend
require 'foo.config.php';
if(isset($_POST['addStockIn'])) {
$query = "INSERT INTO stockin ( serialno, project_id, ...... etc. ) VALUES
(`:serialno, :project_id, ....... etc. )";
...
...
echo yourdata
There is no return in add.php file. Though you are using dataType as 'json',
you should return the data in json format.
You should try something like this.
add.php
require 'foo.config.php';
if(isset($_POST['addStockIn'])) {
$query = "INSERT INTO stockin ( serialno, project_id, ...... etc. ) VALUES
(`:serialno, :project_id, ....... etc. )";
//extra code here
$output = array('res' => $data); //$data : form data to show in html file
$output = json_encode($output);
echo $output; exit;
jQuery:
jQuery("#addStockInForm").submit(function(e){
e.preventDefault();
dataString = jQuery("#addStockInForm").serialize();
jQuery.ajax({
type: "POST",
url: "add.php",
data: dataString,
dataType: "json",
success: function(data) {
//$("div#showinstant").html(data);
alert(data.res);
}
});
});
Main problem was in elsewhere... The Problem was in isset funciton parameter
if(isset($_POST['addStockIn'])) {
}
I have changed this to
if(isset($_POST['serialno'])) {
}
And it's working fine!
#LX7 was helped me to think differently, thanks dude...
So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}