Ok, I have two pages. getprofilecomment.php and getprofilecomment.js. The get getprofilecomment.php is functioning, but the getprofilecomment.js is not working for some reason. It is not displaying any content. The div id is correct. Here is the code:
$(function()
{
var userId = $(#userid).val();
$.ajax({
url: "api/getprofilecomment.php",
method: "GET",
data: userId,
cache: false,
success: function(comment){
$(#usercommentdiv).apprend('<li>' + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + '</li>');
}
});
});
Once again, the json_encode is echoing the content successfully to the page.
<?php
include ("../db/database.php");
include ("../classes/profilecommentclass.php");
session_start();
$profileCommentHandler = new ProfileComment($db);
$userId = $_GET['userId'];
$profileComment = $profileCommentHandler->getComment($userId);
echo json_encode($profileComment, JSON_FORCE_OBJECT);
?>
Hi you are missing id (usercommentdiv) in quotes,
success: function(comment){
$('#usercommentdiv').apprend('<li>' + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + '</li>');
}
Related
I php code that will insert into database but it always returns false even if it is inserting values into the database.
Here is my code: PHP
<?php
require_once 'connection.php';
if (isset($_POST['borrowBook']))
{
newBorrowRequest();
}
function newBorrowRequest()
{
$b_id = $GLOBALS['db']->real_escape_string($_POST['b_id']);
$userID = $GLOBALS['db']->real_escape_string($_POST['userID']);
$dateBorrowed = $GLOBALS['db']->real_escape_string($_POST['dateBorrowed']);
$remarks = $GLOBALS['db']->real_escape_string($_POST['remarks']);
$sql = "INSERT INTO `tbl_requestbook`(`b_id`, `userID`, `dateBorrowed`, `remarks`) VALUES ('$b_id','$userID','$dateBorrowed','$remarks')";
if($GLOBALS['db']->query($sql))
{
$GLOBALS['db']->close();
header("location:../../admin/Book-Items.php?r=success", true);
}
else
{
header("location:../../admin/Book-Items.php?r=failed", true);
}
}
>?
And here is my Ajax Code:
<script>
$("#borrowBook").click(function(event) {
var bookID = $("#bookBorrow").val();
var userID = $("#borrowBook").val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
$.ajax({
url: '../assets/php/functions-book.php',
type: 'POST',
data: {borrowBook: 'true', b_id: bookID, userID: userID, dateBorrowed: output, remarks: $("#remarks").val() },
success: function(result) {
window.location.reload();
},
error: function(result) {
//window.location.reload();
console.log(result);
}
});
});
</script
There is something wrong with the php query, it will not iterate with the condition thus, it will call the ajax error function.
[EDITED]
I solved this by changing 'header("location:../../admin/Book-Item.php?r=success");' to 'header("location:../../admin/Book-Items.php?r=success");'. It was a wrong call.
My problem now is, after success the header remains. It can't be replace by the new header that I want to change. I already changed the php code to the latest.
I am trying to display data fetched as JSON from MySQL DB using PHP into an HTML element say a table. Below is my code for this:
<!DOCTYPE html>
<html>
<head>
<title>Test Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#display").change(function()
{
var type = document.getElementById('display').value;
$.ajax(
{
//create an ajax request to load_page.php
type: "POST",
url: "DBOperations.php",
data : "type=" +type,
dataType: "text", //expect text to be returned
success: function(response)
{
var tr = $('<tr>');
tr.append('<td>' + response.client_id + '<td>');
tr.append('<td>' + response.client_name + '<td>');
tr.append('<td>' + response.client_title + '<td>');
tr.append('<td>' + response.client_type + '<td>');
$('#myTable').append(tr);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});
});
});
</script>
</head>
<body>
<form>
<select id="display" name="clienttype" onchange="showClient(this.value)">
<option value="">Select a Client:</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</form>
<br>
<table id="myTable">
<tr>
<th>ClientID</th>
<th>ClientName</th>
<th>ClientTitle</th>
<th>ClientType</th>
</tr>
</table>
</form>
</body>
</html>
Here is what i am getting from php as JSON:
[{"client_id":"1","0":"1","client_name":"asdf","1":"asdf","client_title":"asdf","2":"asdf","client_type":"a","3":"a"}]
Besides if i set the datatype in AJAX to json, it displays the error as in this question:
how to remove parsererror: SyntaxError: Unexpected token < in JSON at position 0
So i keep it as either html or text which at least displays the response wtihout the error. but i need to format the response and feed it to another element.
Thanks in advance.
$.ajax(
{
//create an ajax request to load_page.php
type: "POST",
url: "DBOperations.php",
data : {"type :" +type},
dataType: "text", //expect text to be returned
success: function(response)
{
var data = response.d;
var tr = $('<tr>');
tr.append('<td>' + data .client_id + '<td>');
tr.append('<td>' + data.client_name + '<td>');
tr.append('<td>' + data.client_title + '<td>');
tr.append('<td>' + data.client_type + '<td>');
$('#myTable').append(tr);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});
try this one.
First of all, if you're expecting a JSON string back from server then you should put dataType: "json" in your AJAX request. And second, your success callback function should be like this:
success: function(response){
var tr = $('<tr>');
tr.append('<td>' + response[0].client_id + '<td>');
tr.append('<td>' + response[0].client_name + '<td>');
tr.append('<td>' + response[0].client_title + '<td>');
tr.append('<td>' + response[0].client_type + '<td>');
$('#myTable').append(tr);
}
Update(1): Based on the question link you shared, it's clearly visible that you're creating and outputting json string in the wrong way, your PHP and AJAX code should be like this:
PHP code:
try{
$dsn = 'mysql:host=localhost;dbname=practice_db'; //your host and database name here.
$username = 'root';
$password = '';
//Connect to database
$conn = new PDO($dsn, $username, $password);
$query = "SELECT * FROM client WHERE client_type = :client_type";
//Prepare and Execute Query
$stmt = $conn->prepare($query);
$stmt->bindParam(':client_type', $type);
$stmt->execute();
$rows = $stmt->fetchAll();
echo json_encode($rows);
}catch (PDOException $ex){
echo "There was a problem executing the Query: " . $ex->getMessage();
}
AJAX code:
$.ajax({
type: "POST",
url: "DBOperations.php",
data : "type=" + type,
dataType: "json",
success: function(response){
$.each(response, function(key,value) {
var tr = $('<tr>');
tr.append('<td>' + value.client_id + '<td>');
tr.append('<td>' + value.client_name + '<td>');
tr.append('<td>' + value.client_title + '<td>');
tr.append('<td>' + value.client_type + '<td>');
$('#myTable').append(tr);
});
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});
I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.
Here there is my code which insert a row in ajax, it's working perfectly.
I need to display the new row that the user inserted inside my select multiple without reload the page but i don't know how to do ..
Thank you for you help
Ajax call :
$('#insertForm').on('click', function(){
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php?insertForm="+insertForm+"&form_user="+form_user+"&form_intitule="+form_intitule+"&form_organisme="+form_organisme+"&form_date="+form_date+"&form_benefice="+form_benefice+"&form_dispositif="+form_dispositif+"&form_entpro_ActionAutre="+form_entpro_ActionAutre,
dataType : "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success:function(data){
}
});
});
My select multiple in function.php :
$displayFormation = $bdd->prepare('SELECT * FROM FORMATION WHERE form_id_user = :idSalarie ORDER BY form_date DESC');
$displayFormation->bindParam(':idSalarie', $_POST['idSalarie']);
$displayFormation->execute();
$data['formation'] .='
<div class="form-group">
<label for="nomSalarie" class="col-sm-1 control-label" id="nameSelect">Formations</label>
<div class="col-sm-11">
<select name="listeFormation[]" id="listeFormation" class="form-control" multiple>';
while($ligne = $displayFormation->fetch()){
$data['formation'] .='<option value="'. $ligne['form_id'].'">'.$ligne['form_intitule']. " [" . $ligne['form_organisme'] . "]". " [Année : " . dateAnglaisVersFrancaisAnnee($ligne['form_date']) . "]" . " [Bénéfices : " . $ligne['form_benefice'] . "]" . " [Dispositif : " . $ligne['form_dispositif'] . "]".'</option>';
}
$data['formation'] .='
</select>
</div>
</div>';
I am going to make some guesses and also some suggestions. Without knowing what your resulting data is going to be, it's hard to answer fully.
My working example and tests: https://jsfiddle.net/Twisty/053q24dh/
Here is the JQuery I would advise:
$('#insertForm').on('click', function() {
var form_user = $('input[name=form_user]').val();
var form_intitule = $('input[name=form_intitule]').val();
var form_organisme = $('input[name=form_organisme]').val();
var form_date = $('input[name=form_date]').val();
var form_benefice = $('textarea[name=form_benefice]').val();
var form_dispositif = $('#form_dispositif').val();
var form_entpro_ActionAutre = $('input[name=entpro_ActionAutre]').val();
$.ajax({
type: "GET",
url: "lib/function.php",
data: {
"insertForm": insertForm,
"form_user": form_user,
"form_intitule": form_intitule,
"form_organisme": form_organisme,
"form_date": form_date,
"form_benefice": form_benefice,
"form_dispositif": form_dispositif,
"form_entpro_ActionAutre": form_entpro_ActionAutre,
},
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
},
success: function(data) {
// Asumming the page returns the following HTML, or something similar:
// <option value="9">Title [Organize] [Année : 02/02/16] [Bénéfices : 1] [Dispositif : 1]</option>
$("#listeFormation").append(data);
}
});
});
Again, this assumes that the HTML that is being returned to data is a single option tag to be appended to the select object. It looks like your PHP in the Post is looking for POST and your ajax is making a GET, so I am assuming they are different PHP Scripts. If they are not, you need to make sure the PHP knows how to respond properly and is not sending back too much data.
Also, I noticed that insertForm is not defined in this code snippet. If it's defined globally, that's fine, otherwise you need to define it within the scope of this function.
I have four variables I'm trying to pass via AJAX to be processed by some PHP on the same page: newJudgeName, newJudgeSection, newJudgeStatus, and originalJudgeName. The success function echos them out and they're the correct values, it's just the newJudgeStatus variable is not being picked up by my PHP. I've switched newJudgeStatus with newJudgeName in the data line on the AJAX request and then the value is sent just fine (I can see it in the db under Judge Name)... it's only when it's in the original spot in the ajax request that it doesn't work. I'm completely new to Ajax. Any help would be much appreciated.
AJAX:
$.ajax({
type: "POST",
url: "test.php",
data: 'newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus + '&originalJudgeName=' + originalJudgeName,
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
PHP:
if(isset($_POST['newJudgeName'])){
$newJudgeName = $_POST['newJudgeName'];
$newJudgeSection = $_POST['newJudgeSection'];
$newJudgeStatus = $_POST['newJudgeStatus'];
$originalJudgeName = $_POST['originalJudgeName'];
$judgeID = judgeNametoID($originalJudgeName);
$con = mysql_connect("-","-","-");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else {
// connected to database successfully
}
mysql_select_db("cm", $con);
$query = ("UPDATE `casemanagers`.`judges` SET `Name`='$newJudgeName' , `Section`='$newJudgeSection', `Active`='$newJudgeStatus' WHERE `judgeID`='$judgeID';");
$result = mysql_query($query);
mysql_close($con);
}
You have an errant space in your data string:
'&newJudgeStatus =' + newJudgeStatus +
---------------^^^^
// Should be
'&newJudgeStatus=' + newJudgeStatus +
You should send the data this way:
$.ajax({
type: "POST",
url: "test.php",
data: {
'newJudgeName' : newJudgeName,
'newJudgeSection' : newJudgeSection,
'newJudgeStatus' : newJudgeStatus,
'originalJudgeName' : originalJudgeName
},
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
Instead of manual processing, I'll recommend to put all these inside a form & use following code to send data:
$('#id_of_the_form').serialize();
instead of buggy:
newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName ...
See http://api.jquery.com/serialize/