Getting data wtith Ajax (Placing inside div) - javascript

I'm trying to add my data into a div, and its not working. The php is fine but I need a fine eye to see if they can spot any errors or can suggest any work arounds to help figure out why its not working.
I've tried to fix it for the past 5 hours or so and its racking my brains.
The user comments on a status like post and its suppose to add it to the div. Just like my main status does. The ajax for the main status is almost identical to the comment ajax below..yet the comment ahax isn't playing nice and is not inserting any data at all.
<script>
$(document).ready(function(){
$("form#mycommentform").submit(function() {
var streamidcontent = $('#streamidcontent').val();
var contents = $(this).children('#contents').val();
$.ajax({
type: "POST",
url: "comment_add.php",
cache: false,
dataType: "json",
data: { streamidcontent: streamidcontent, contents: contents},
success: function(data){
$('#containerid').html('<div class="stream_comment_holder" style="display:none;"
id="comment_holder_'+data['comment_streamitem']+'"><div
id="comment_list_'+data['comment_streamitem']+'"><div
id="tgy"></div><div class="stream_comment"
id="comment_'+data['comment_id']+'" style="margin-top:0px;"><table
width=100%><tr><td valign=top width=30px><img
class="stream_profileimage"
style="border:none;padding:0px;display:inline;" border=\"0\"
src=\"imgs/cropped'+data['id']+'.jpg\"
onerror="this.src=\"img/no_profile_img.jpeg\"" width=\"40\"
height=\"40\" ></a><td valign=top align=left>'+data['first']+'<div
class="commentholder">'+data['first']+'</div><br/><div
id="commentactivitycontainer"></div></div></table></div></div><div
class="form"><form id="mycommentform" method="POST"
class="form_statusinput"><input type="hidden" name="streamidcontent"
id="streamidcontent" value="'+data['comment_streamitem']+'"><input
type="text" name"contents" id="contents" placeholder="Say something"
autocomplete="off"><input type="submit" id="button"
value="Feed"></form></div><div class="stream_comment_holder"
style="display:;"><div class="like_name"><b><a
href="profile.php?username='+data['username']+'">You Like
This</a></b></div></div>');
}
});
return false
});
});
</script>
ERROR FOUND
success: function (data) {
alert("SUCCESS!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.status);
alert(thrownError);
}
OK
200
SyntaxError.JSONparse:Unexpectedcharacter
JSON
$json = array();
$check = "SELECT comment_id, comment_datetime, comment_streamitem FROM streamdata_comments WHERE comment_streamitem=".$_POST['streamidcontent']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['comment_id'] = $resultArr['comment_id'];
$json['comment_streamitem'] = $resultArr['comment_streamitem'];
mysqli_free_result($check1);
$check = "SELECT * FROM users WHERE id=".$_SESSION['id']."";
$check1 = mysqli_query($mysqli,$check);
$resultArr = mysqli_fetch_array($check1);
$json['username'] = $resultArr['username'];
$json['id'] = $resultArr['id'];
$json['first'] = $resultArr['first'];
$json['middle'] = $resultArr['middle'];
$json['last'] = $resultArr['last'];
mysqli_free_result($check1);
echo json_encode($json);

I would recommend using some sort of templating system to do all the hard work assembling your content.
Take a look into Create a makeshift Javascript templating or John Resig's solution.
Building that string of mark-up inside html() is a little crude.
You also have an inline style of display:none on the first div, so you won't see it.
Have you tried stripping the function down just to see if anything gets populated
success: function(data){
$('#containerid').html('blurb');
}

I don't know if this is the only problem, but where you're trying to embed quotation marks inside the html attributes that you're creating, e.g.:
'onerror="this.src=\"img/no_profile_img.jpeg\""'
It will produce this invalid string:
onerror="this.src="img/no_profile_img.jpeg""
You should embed single quotes instead, like this:
'onerror="this.src=\'img/no_profile_img.jpeg\'"'
Which would produce:
onerror="this.src='img/no_profile_img.jpeg'"
Also, on about the sixth last line you have an attribute missing an = sign:
name"contents"
And the outer-most div you are inserting has style="display:none;".

Related

Ajax call returns data but in purely string format.

In PHP I can do things like this:
echo "<div>".$myvariable."</div>";
Which will print out my variable with div's in HTML for its tags. However recently, I needed to do a ajax call using jquery. I'm somewhat familiar with ajax but I don't use it much. Anyways, I run the ajax code, it prints the data into my HMTL element box like I wanted, however, the div tags are printed and displayed along with the content itself!
The entire return data is pretty much 1 long string, rather than the PHP parsing my data like I want it to. Where did I go wrong? Why is it only returning 1 long string?
PHP CODE:
<?php
require 'database.php';
$meal = $_POST['meals'];
$meal_q = "SELECT item
FROM meal_ingredients
WHERE meal_name='$meal'
ORDER BY item";
$meal_c = $conn->query($meal_q);
while ($row = $meal_c->fetch_assoc()){
$view_ingredient = $row['item'];
echo "<div>".$view_ingredient."</div>";
};
?>
JQUERY CODE:
if($('body').hasClass('CreateMealPage')){
$('tr').on('click', function(e){
$('#sidebar').animate({right: '-200px'}, 500);
var meals = $(this).find('.meals').text();
$.ajax({
method: "POST",
url: 'meal_list.php',
data: {meals: meals},
success: function(data) {
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = "";
sidebar.append(data);
}
});
});
};
WHAT IS RENDERED ON SCREEN:
<div>ingredientname</div>
<div>ingredientname</div>
<div>ingredientname</div>
RATHER THAN:
ingredientname
ingredientname
ingredientname
just replace
sidebar.innerHTML = "";
sidebar.append(data);
with
sidebar.innerHTML = data;
To answer your comment you can use append with following in jquery
$(sidebar).append($(data))
so jquery's append needs to be used, instead of append, from dom api, which takes a node element only in arguments. If you still need to use append of dom api, use something like:
sidebar.append(document.createRange().createContextualFragme‌​nt(data))
Add dataType: "html" to the properties in your $.ajax() call, like this:
$.ajax({
method: "POST",
url: 'meal_list.php',
dataType: "html",
data: {meals: meals},
success: function(data) {
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = "";
sidebar.append(data);
}
});
This will inform the call to expect HTML data to be returned in the response body.

AJAX call returns undefined in Header / form-data

I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.

Passing JSON through AJAX Plus Button Dilema

so I am attempting to pass some information in a JSON object and have a php page insert the data into a database. However, I am running into some trouble. The "update" button exists in a popup window. The user then clicks "update" and the inputted data should be processed accordingly. However, I fear that I am not even reaching my .click function. None of my alerts seems to be triggered. Below I will point out where issues are occurring. Thank you!
<script>
function updateTable()
{
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
$('#update').click( function() {
alert("help!");
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
#.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
//data: 'popUpString = '+ popupString,
data: popupObj,
cache: false,
success: function(data) {
updateTable();
alert("testing tests");
}
});
});
</script>
<html>
<button onClick="openPopup(<?php echo $row['ID'];?>);"><?php echo $row['ID'];?></button> <!--opens a popup with input options-->
<button id="update">Update</button> <!-- this button is supposed to cause the javascript above to run when clicked, however none of my alerts seem to be reached.-->
</html>
Thank you for looking!
1)I can only guess that you're trying to use JQUERY?
Where do you include the library?
2 )#.ajax isnt valid Jquery function
try $.ajax instead

Adding data dynamically to HTML Table in PHP

I want to add data's from input fields to the HTML Table dynamically when clicking the Add button as shown in the sample image. How can I accomplish this? Can I do it with PHP? As I'm a
beginner I can't find the exactly matched results from here,
but I found a related thread, Creating a dynamic table using php based on users input data, but I think this process is done by 2 pages (1 page for inputs and another for showing that input data's in table) as per the code... Any help will appreciated.
Assuming you're using jquery (given your tag), something like the following will work:
$("button").click(function() {
var newRow = "<tr>";
$("form input").each(function() {
newRow += "<td>"+$(this).val()+"</td>";
});
newRow += "</tr>";
$("table").append(newRow);
});
There are better ways to do this, but this is probably a very simple place to start if you're just beginning to learn. The functions you should be interested in here are: .click, .each, .val, and .append. I'd recommend you check out the jquery docs - they will give you good examples to expand your knowledge.
If you can use jQuery you can do it like this. It's not the full code it's just to give you the idea how to start with it.
jQuery('#add').click(function(){
var memberName = jQuery('#memberName').val();
var address = jQuery('#address').val();
var designation = jQuery('#designation').val();
// Do some saving process first, using ajax and sending it to a php page on the server
// then make that php return something to validate if it's succesfully added or something
// before you show it on table. You can use ajax like
jQuery.ajax({
type: 'POST',
url: 'you php file url.php',
data: { name: memeberName, addr: address, desig: designation },
dataType: 'json', // any return type you like
succes: function(response){ // if php return a success state
jQuery('#tableID tbody').append('<tr><td>' + memberName + '</td><td>' + address + '</td><td>' + designation + '</td></tr>');
},
error: function(response){ // if error in the middle of the call
alert('Cant Add');
}
});
});
Be sure to change the id to the id you have in your html elements.
This is only on the front end side. If you have other processes like saving the newly added into the DB then you have to process that first before showing it on the table.
First, let's make this:
into table, like this:
<table id='mytable'>
<tr>
<tr>
<td>Member Name</td><td><input type="text" name="member[]"></td>
</tr>
<tr>
<td>Address</td><td><textarea></td>
</tr>
<tr>
<td>Designation</td><td>
<select>
<option value="asd">Asd</option>
<option value="sda">Sda</option>
</select></td>
</tr>
</tr>
</table>
<div>
<input name='buttonadd' type='button' id='add_table' value='Add'>
</div>
And add this javascript in head or body:
$("#add_table").click(function(){
$('#mytable tr').last().after('<tr><td>Member Name</td><td><input type="text" name="member[]"></td></tr><tr><td>Address</td><td><textarea></td></tr><tr><td>Designation</td><td><select><option value="asd">Asd</option><option value="sda">Sda</option></select></td></tr>');
});
Inside after(''); don't use enter, just type the code sideways.
Hope this can help you.
Ty jean for your instant reply..i tried that code, but i couldn't get +ve result,coz of my knowledge with javascript,jquery, etc are very poor.now my code is like this
so i expect you will help me coz of im just stepping into javascript and jquery.
$(document).ready(function()
{
$("#ser_itm").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
alert(dataString);
$.ajax
({
type: "POST",
url: "bar_pull.php",
data: dataString,
cache: false,
success: function(data)
{
$("#tbl").html(data);
}
});
});
});

Assigning selectors to variables to call them depending on the type of button

Thats the best description I could think of. I normally do not post, but I honestly cannot figure this out.
Still in jquery learning mode, and basically what I want to accomplish is that depending on the type of button that is submitted, the script assigns variables to div's on the page. What I am making is a admin side of a user script to allow them to update that particular div that appears on the page.
When I put in the actual selectors, the script works.
When the page loads, it will take the field of the database that corresponds with the and load it. Once they push the update button, a new div will appear. The admin inputs his new data (the new information he wants to display) and it updates the mysql table, then pulls it back in through jquery's ajax.
Sorry for the long explanation. Like I said, I've never really posted, just always liked figuring it out on my own.
php page
<?php //
if(isLoggedIn())
{
echo '<button id="adultClassButton">Edit Class Information</button>';
}
?>
<div class="class" id="adultClass"><?php
$row = checkPost('adult');
echo $row['info'];
?>
</div>
<?php
echo '<div id="adultClassInput">
<textarea rows="2" cols="80" id="adultClassUpdate"></textarea>
<input type="hidden" id="className" name="adult"/>
<button id="adult">Save the Updated Class Info</button></div>';
?>
javascript (jquery) file
$(".button").click(function(){
var button = $(this).attr('id');
if (button == 'adult'){
var classDiv = $("#adultClass");
var className = $("#className");
var classDesc = $("#adultClassUpdate").val();
var classUpdateDiv = $("#adultClassInput");
postData(classDiv, className, classDesc, classUpdateDiv);
}
});
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: "name="+ className+ "& info="+ classDesc,
success:function(data){
$("#" + classDiv).html(data);
}
})
$("#" + classDesc).val('');
$("#" + classUpdateDiv).hide();
}
Like I said, if I have normal selectors in the function, it works as intended. But as of right now, I'm just stumped as to whats wrong.
Thanks a bunch!
classDiv is a jquery object not the ID of the element. So when you use this
$("#" + classDiv).html(data);
That's not working as expected.
Try
classDiv.html(data);
Your function should be like this:
function postData(classDiv, className, classDesc, classUpdateDiv){
$.ajax({
url: 'insert.php',
type: 'POST',
data: {"name": className.val(), "info": classDesc}
success:function(data){
classDiv.html(data);
}
})
$("#"+classDesc).val('');
classUpdateDiv.hide();
}
because you already passed jquery objects (not strings) to your function, except for classDesc.
Hope this helps. Cheers

Categories