How to get php Json array data of Jquery ajax - php

My jQuery Ajax code:
$(".comment").click(function(){
var id = $(this).data("id");
var name = $("#username_"+id).val();
if(name==''){
alert("Please Fill All Fields");
}else{
$.ajax({
type: "POST",
url: "comments",
data:{username:name},
dataType: "JSON",
success: function(jsonStr){
$("#cmt_output").html(JSON.stringify(jsonStr));
}
});
}
});
My Php Code:
............
$con = mysqli_connect("localhost","root","","quotes") or die("Error".mysqli_error($con));
$name = $_POST['username'];
$user = get_userdetails();
$vw_id = $user->id;
$query = mysqli_query($con,"INSERT INTO tlb_comments(user_id,comments) values ('$vw_id','$name')");
$comments = mysqli_query($con,"SELECT * FROM tlb_comments");
$avatar = mysqli_query($con,"SELECT * FROM tlb_avatar WHERE `vw_id`='".$vw_id."'");
$avatar_select = mysqli_fetch_all($avatar);
$comment_select = mysqli_fetch_all($comments);
array_push($avatar_select,$comment_select);
echo json_encode($avatar_select);

Related

How to get two arrays from php using mysqli,jquery ajax?

i want the function(data) to get 2 attribute value from the database
This is the select option that display the display the address and contact value of the selected option in an input field
$('#recipient').change(function(){
var FULL_NAME = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{FULL_NAME:FULL_NAME},
success:function(data){
$('#address').val(data);
$('#contact').val(data);
}
});
});
and this is the load_data.php
<?php
$sql = "SELECT * FROM recipient";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output1 = $row["ADDRESS"];
$output2 = $row["CONTACT"];
$arr = array($output1,$output2);
}
echo $output1,$output2;
?>
How do i pass the $output1 into $('#address').val(data) and $output2 into $('#contact').val(data)
$('#recipient').change(function(){
var FULL_NAME = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
dataType: "json",
data:{FULL_NAME:FULL_NAME},
success:function(data){
$('#address').val(data['ADDRESS']);
$('#contact').val(data['CONTACT']);
}
});
});
and the load_data.php
<?php
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$arr["ADDRESS"] = $row["ADDRESS"];
$arr["CONTACT"] = $row["CONTACT"];
}
echo json_encode($arr);
?>

Getting the value from option

Hello im doing some try and error. This is the code where select-option populate from database but this gives me null value
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from try where name = '".$_POST['name']."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
datatype: 'json',
success: function(result){
alert(result);
document.getElementById("sub").innerHTML = result;
}
});
<select id="sub" name="subb"></select>
my problem is whether i select from dropdown the content is there but no value. pls help..
PHP:
$ajaxAnswer = "<option value=\"\">"."Select"."</option>";
$instructor = mysqli_real_escape_string($conn,$_POST['instructor']);
$qry = "select * from try where name = '".$instructor."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
$ajaxAnswer .= "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
echo $ajaxAnswer;
Jquery:
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
success: function(result){
$("#sub").html(result);
}
});
data: {instructor:$('#SELECT_ELEMTN_ID').val()},
Depending on scope and stuff, you may not wanna use "this".
Jquery
$(document).ready(function () {
$.ajax({
type: "GET",
url: "phpfile.php",
dataType: "json",
success: function (data) {
$.each(data, function (idx, obj) {
$('#selectdata').append('<option value="'+obj.user_id+'">'+obj.user_name+'</option>' )
});
}
});
});
</script>
</head>
<body>
<select id="selectdata">
</select>
</body>
phpfile.php
<?php
$host = "localhost";
$user = "root";
$password ="";
$database= "databasename";
$con = mysqli_connect($host , $user , $password);
$database_connect = mysqli_select_db($con, $database);
$result = mysqli_query($con, "select Id as user_id,Name as user_name from users");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
?>

How to Retrieve Values Resulting From AJAX Live Search?

Below is a jQuery function that retrieves 2 textbox values and posts them to another file ("Student Search Results.php"), where a live search is run using the values.
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = Team_Name + '?????' + Teacher;
$.ajax({
type: "POST",
url: "Student Search Results.php",
data: {
query: Search_Data
},
cache: false,
success: function() {
alert('The values were sent');
}
});
});
</script>
Below is the PHP script on the search page ("Student Search Results.php") that makes use of these values.
<?php
include "Connection.php";
if(isset($_POST['query'])){
$searchData = explode('?????', $_POST['query']);
$teamName = $searchData[0];
$teacher = $searchData[1];
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
echo $query;
?>
How would I be able to take variables from the PHP script (such as $result) to the first page, so I can create a result table? Simply including the PHP file does not work, as the file is only included once.
Thank you for your time.
Best option is to serialize to JSON using json_encode
I think best you can do is,
success: function(result) {
alert(result);
}
and Student Search Results.php print result in tabular format.
P.S. : Please follow proper file naming convention
use a proper URL, and send the data (and stop using camelcase for everything) :
$(".search").on('keyup', function() {
var data = {
team_name : $('#TeamName').val(),
teacher : $('#Teacher').val()
}
$.ajax({
type: "POST",
url: "student_search_results.php",
data: data,
cache: false
}).done(function(result) {
console.log(result);
});
});
And in PHP, you have to actually get the result into an array and json_encode it :
<?php
include "Connection.php";
$team_name = !empty( $_POST['team_name'] ) ? $_POST['team_name'] : null;
$teacher = !empty( $_POST['teacher'] ) ? $_POST['teacher'] : null;
if ($team_name && $teacher) {
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email,
teacher_user_table.Teacher_Name LIKE '%" . $teacher . "%',
club_table.Club_Name LIKE '%" . $teamName . "%';";
}else{
$query = "SELECT club_table.Club_Name, teacher_user_table.Teacher_Name
FROM club_table, teacher_user_table
WHERE club_table.Teacher_Email = teacher_user_table.Teacher_Email;";
}
$result = mysqli_query($con, $query);
$data = $result->fetch_all( MYSQLI_ASSOC );
echo json_encode( $data );
?>
<script>
$(".search").keyup(function() {
var Team_Name = $('#TeamName').val();
var Teacher = $('#Teacher').val();
var Search_Data = "Team_Name="+'Team_Name'&Teacher='+Teacher;
$.ajax({
type: "POST",
url: "Student_Search_Results.php",
data: Search_Data,
cache: false,
success: function(result) {
$('$output').html(result);
}
});
});
</script>
Here is output div
<div id="output"></div>
On Student_Search_Results.php page get
$tname = $_POST['Team_Name'];
$teacher = $_POST['Teacher'];
//your search query & print data

Selecting different data with Ajax

I'm trying to select various bits of data out of my insert.php page. Such as post id, username and users id so far.. And I will be adding other bits of selected data. Now I could get the id of the div with response, but when I added more queries and echo them out they ended up all together so I had my postidusernameuserid all in one string. How do I separate them?
Also I'm aware of the depreciated MYSQL_ I just haven't got around to updating my code yet.
AJAX
<script>
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: {toid:content, newmsg: newmsg},
success: function(response){
$("#homestatusid").prepend("<div id='divider-"+response+"'><div class='userinfo'>"+newmsg+"<a href='/profile.php?username="+response+"'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><div style='cursor:pointer;position:relative;top:0px;float:right;padding-right:5px;' onclick=\"delete_('"+response+"');\">X</div></div></div>");
}
});
});
});
</script>
INSERT.PHP
$check = "SELECT streamitem_id FROM streamdata";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
echo $resultArr['streamitem_id'];
$check = "SELECT username,id FROM users";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
echo $resultArr['username'];
echo $resultArr['id'];
Is it a case of success: function(response,responsetwo){ and so on.
In PHP try returning the data in JSON format.
echo json_encode(array);
The response variable in JavaScript will be an object you can get the data from.
console.log(response['username']);
JavaScript:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
dataType: "json",
data: { toid: content, newmsg: newmsg },
success: function(response){
$("#homestatusid").prepend("<div id='divider-"+response['streamitem_id']+"'><div class='userinfo'>"+newmsg+"<a href='/profile.php?username="+response['username']+"'><img class='stream_profileimage' style='border:none;padding:0px;display:inline;' border=\"0\" src=\"imgs/cropped"+response['id']+".jpg\" onerror='this.src=\"img/no_profile_img.jpeg\"' width=\"40\" height=\"40\" ></a><div style='cursor:pointer;position:relative;top:0px;float:right;padding-right:5px;' onclick=\"delete_('"+response['id']+"');\">X</div></div></div>");
}
});
});
});
PHP:
$json = array();
$check = "SELECT `streamitem_id` FROM `streamdata`";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['streamitem_id'] = $resultArr['streamitem_id'];
mysql_free_result($check1);
$check = "SELECT `username`, `id` FROM `users`";
$check1 = mysql_query($check);
$resultArr = mysql_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
mysql_free_result($check1);
echo json_encode($json);
I took the liberty of guessing where you wanted to use 'username', 'id', and 'streamitem_id'.

why pdo don't save sign of + and & into database?

Why when i typed "+-1-23$%^&sdfsdf/><" in the textarea but it save only "-1-23$%^" into database?
Code :
function postingMsg (){
$('.error').hide();
var messageposting2= $("textarea#messageposting").val();
var dataString = 'messageposting2='+ messageposting2;
$.ajax({
type: "POST",
url: "note-send.php",
data: dataString,
success: function(msg) {
msg = parseFloat(msg)
}
});
return false;
}
if ((isset($_POST['messageposting2'])) && (strlen($_POST['messageposting2']) > 0)) {
$messageposting3 = $_POST['messageposting2'];
$sql = "UPDATE users
SET my_note=?
WHERE user_id=?";
$q = $conn->prepare($sql);
$q->execute(array($messageposting3, $_SESSION['user_id']));
echo "1";
} else {echo "0";}
It has nothing to do with PDO or your database. You must URL-encode your string before sending it through Ajax.
var dataString = 'messageposting2='+ encodeURIComponent(messageposting2);

Categories