Selecting different data with Ajax - php

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'.

Related

How to get php Json array data of Jquery ajax

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);

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 bring json and html data in one ajax call

I have a two jquery function to bring ratings and comments separately from two files which is working fine.
Now i want to do it in a single ajax call, i am trying to merge two function together this way but its not working.
jquery
function get_review(){
$.ajax({
type: "POST",
url: '../review.php',
data: {value1:value1, value2:value2, value3:value3},
dataType: 'json',
cache: false,
success: function(data)
{
var x = data[0];
var rating = (x-0.5)*2
var y = (20 * rating)+40;
$('#urating').css("backgroundPosition","0%" +(y)+ "px");
$('#comments').html(data);
}
});
};
PHP
$find_data = "SELECT * FROM $tablename WHERE table_name='$table' AND product_id='$id' ORDER by id DESC";
$query = mysqli_query($connection, $find_data);
$find_data2 = "SELECT * FROM $tablename2 WHERE id='$id'";
$query2 = mysqli_query($connection, $find_data2);
$row2 = mysqli_fetch_assoc($query2);
header('Content-type: application/json');
echo json_encode($row2);
?>
<?php while($row = mysqli_fetch_assoc($query)):?>
<div class="comment-container">
<div class="user-info"><?php echo $row['user_name']; ?></div>
<div class="comment"><p><?php echo $row['quick_comment']; ?></p></div>
</div>
<?php endwhile;?>
Please see and suggest any possible way to do it.
Thanks.
Try to encode whole response to JSON object!
Something like:
$response = array(
'success' => true,
'object' => $yourobject_or_array,
'html' => '<b>Bla bla</b>'
);
echo json_encode($response);
die();
JS:
function(response) {
var res = false;
try {
res = jQuery.parseJSON(response);
} catch(e) {}
if (res && res.success) {
// Use res.object and res.html here
}
}

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