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));
?>
Related
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>');
});
}
});
});
Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': 'diklat'},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$get_action = $_GET['action'];
if($get_action=='diklat'){
$diklat = $_GET['diklat'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
The value didnt include in my ajax, ajax only read echo. how to get that value
You have written data: {'action': 'diklat'} but it should dilkat without quotes as its variable so in php you will get value in $_GET['action'].
Ajax
$(document).ready(function(){
$("#diklat").change(function(){
var diklat = $("#diklat").val();
$.ajax({
url: "function.php",
data: {'action': diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
if($_GET['action'] == 'diklat'){
$diklat = $_GET['action'];
$angkatan = mysql_query("SELECT id,name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan)){
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
You should pass 2 variables, one action and another id (diklat)
Ajax:
$(document).ready(function(){
$("#diklat").on('change', function(){
var diklat = $("#diklat").val();
$.ajax({
type: "POST",
url: "function.php",
data: {'action': 'diklat', 'diklat':diklat},
cache: false,
success: function(msg){
$("#angkatan").html(msg);
}
});
});
PHP
$action = isset($_POST['action']) ? $_POST['action'] : '';
if ($action == 'diklat')
{
$diklat = isset($_POST['diklat']) ? $_POST['diklat'] : '';
$angkatan = mysql_query("SELECT id, name FROM batches WHERE IdMasterDiklat='$diklat' order by id");
echo "<option>-- Pilih Angkatan --</option>";
while($p = mysql_fetch_array($angkatan))
{
echo "<option value=\"".$p['id']."\">".$p['name']."</option>\n";
}
}
Two things:
For a GET request, to ask a PHP server, data should be URL-encoded (as you see here, query string is just appended to the URL...) So tell 'data' : '?action=diklat' ...
EDIT : Jquery automatically converts object to Url-encoded query string... So It work with array ! I'm confusing with angular's $http...
And also, the parameter will be in $_GET['action'] (because action is parameter name, and diklat the value... So PHP convert query string to associative array, with parameters names as keysn and values as values...
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);
}
});
});
});
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'}
$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){}
});
$("#follow"+I).hide(); ///showing the remove button after the data has been entered
$("#remove"+I).show();
return false;
});
});
The PHP file listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
?>
what I want to do is when I click the follow button, I want to check if the data has been entered into the database, before showing the remove button, basically checking on the background.
mysql_query will return TRUE or FALSE. You can echo that from the PHP script, and have the ajax call read it.
listen.php:
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
echo json_encode(array('response'=>$registerlistener));
?>
In your JavaScript:
$.ajax({
type: "POST",
url: "listen.php",
data: info,
dataType: 'json',
success: function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}
});
If you want, you can use the $.post shorthand:
$.post('listen.php', info, function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}, 'json');
Put the code you want to execute inside your 'success' callback function.
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){
$("#follow"+I).hide();
$("#remove"+I).show();
}
});
do it like this:
listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
if($registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')")):
echo "true";
else:
echo "false";
endif;
?>
pass parameter in success function, example "msg". whatever was echo'ed in listen.php will be in the msg variable now
success: function(msg){}
if(msg == "true")
{
//do something
}
else
{
//show error message
}
});