I would like to select streamitem_id from my insert.php and add it to my existing post div. I'm needing the id of the post made so I can add it into my div so later when I add my delete button it will delete the post and the div that holds it. Hope I've made sense and I can do this with what I have as I'm trying to learn but it is a difficult language like any when first starting out.
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(){
$("#homestatusid").prepend("<div id='divider-"+WHERE MY STREAMITEM_ID NEEDS TO BE+"'><div class='userinfo'>"+newmsg+"</div></div>");
}
});
});
});
</script>
INSERT.PHP
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_id=$user1_id";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
echo $check2;
In your javascript should be
$.ajax({
type: "POST",
url: "insert.php",
data: {toid:content, newmsg: newmsg}, # pay attention to this line
success: function(data){
$("#homestatusid").prepend("<div id='divider-"+data+"'><div class='userinfo'>"+newmsg+"</div></div>");
}
});
PHP
$toid = isset($_POST['toid']) ? $_POST['toid'] : null;
$newmsg = isset($_POST['newmsg']) ? $_POST['newmsg'] : null;
And do not use mysql_* since it deprecated
The first argument passed to the success callback is the responseText from the AJAX call. Modify your jQuery code to this:
success: function(responseText){
$("#homestatusid").prepend("<div id='divider-"+responseText+"'><div class='userinfo'>"+newmsg+"</div></div>");
// I'm assuming that insert.php returns just the ID you're interested in
}
success: function(response){
$("#homestatusid").prepend("<div id='divider-"+response+"'><div class='userinfo'>"+newmsg+"</div></div>");
}
Related
i have a readmore link that allows people to read more posts once it has been clicked, what i don't want is the button showing again and i also don't want the whole post to show again, i just want the remaining posts to add to the previous that the reader has read or being reading just as its done on facebook page when you click seemore link.
Thanks
$(function(){
$(".readMore").click(function(event){
event.preventDefault();
var link = $(this).attr('href');
var dataString = 'link='+ link;
$.ajax({
type : "POST",
url: "readmore-post.php",
data: dataString,
cache : false,
success: function(html){
$(".read_more").before(html);
}
});
});
});
this is the html part
<?php echo substr($post,0,250); ?>..
<?php
if(strlen($post)>250)
{
echo"<a href='$postID' style='font-size:0.8em;' class='readMore'>readmore</a> </br>";
}
?>
<div class="read_more"></div>
this is the php part
<?php
include('../config/connect.php');
$read_id = $_POST['link'];
$srm = "SELECT * FROM page_timeline WHERE timelineID='$read_id' ORDER BY timelineID DESC";
$sre = $db->query($srm);
while($rowr = $sre->fetch_array())
{
$postID = $rowr['timelineID'];
$post = $rowr['post'];
}
echo "<p>".$post."</p>";
?>
Try this and see inline comments
$(function(){
$(".readMore").click(function(event){
event.preventDefault();
var that=$(this);
var link = $(this).attr('href');
var dataString = 'link='+ link;
$.ajax({
type : "POST",
url: "readmore-post.php",
data: dataString,
cache : false,
success: function(html){
$(".read_more").empty().append(html);
//clear all the contents and append new one to .read_more div
that.hide(); //hide the button on successful load
},
});
});
});
I read similar answer here in this question: How to insert into MYSQL row from multiple $_POST arrays and How to insert into MYSQL row from multiple $_POST arrays but the problem is these answers do not work in my code. Is it because im using an ajax? and i only get the value of the first array.
If i also place the variable declaration inside the for loop it is not working too.
Here is my ajax:
var name = [];
$('input[name="name[]"]').map(function(){ name.push($(this).val()); }); var studid = [];
$('input[name="studid[]"]').map(function(){ studid.push($(this).val()); }); var nameStr = name != '' ? '&name='+ name : '';
var studStr = studid != '' ? '&studid='+ studid : '';
var dataString = 'subject='+ subject + '§ion=' + section + studStr + nameStr;
$.ajax({ type: "POST", url: 'save.php', data: dataString, dataType: "html",
success: function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); }); },
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); } });
return false;
});
Here is my php:
if(isset($_POST['studid']) || isset($_POST['name'])){
$studid = array_map(mysql_real_escape_string, explode(",",$_POST['studid']));
$name = array_map(mysql_real_escape_string, explode(",",$_POST['name']));
for ($i=0; $i<count($studid); $i++){
$sql_1 = "INSERT INTO tbl_student(StudentID, StudentName, SubjectID) VALUES ('".$studid[$i]."', '".$name[$i]."', LAST_INSERT_ID())";
mysqli_query($con,$sql_1);
}
}
use mysql_insert_id();
instead of LAST_INSERT_ID()
You're not sending data correctly from the jQuery and its seems you'r mixing arrays and string together.
This is a simple request that posts studid-array from jQuery
var saveData = $.ajax({
type: 'POST',
data: {studid: studid},
url: 'save.php',
dataType: 'html'
});
saveData.done(function(data) {
$('input#subject-field').val('');
$('input#section-field').val('');
$('input.record-input-forms').val('');
$('#status-message').css({"color":"#39b1c6"});
$('#status-message').html('Save successfully',function(){
$('#status-message').fadeOut(2000); });
});
saveData.fail(function(ts) {
alert(ts.responseText);
});
When save.php is called, $_POST['studid'] would be set (if there are anything in the array)
If you instead do like this:
var saveData = $.ajax({
type: 'POST',
url: 'save.php?studid=' + studid,
dataType: 'html'
});
When save.php is called, $_GET['studid'] would be set (if there are anything in the array). The best way though is to use data-option in the ajax-function call (in my first case). If you choose to use this option you would have to serialize the stuid-array before putting it in as a part of an url.
UPDATE
If you want to pass multiple arrays you would have to do something like this:
var saveData = $.ajax({
type: 'POST',
data: {studid: studid, name_arr2: data_arr2},
url: 'save.php',
dataType: 'html'
});
I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});
Ok fixed jQuery code with help of others on stack overflow
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-','')",
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' /> Error...");
}
});
});
});
The PHP code for view.php
include 'object/db.class.php';
if($_GET['ajax'] == '1') {
#make a call to my sql to fetch some sort of ID
$nid = $_GET['nid'];
$q = mysql_query("SELECT * FROM `notice` WHERE nid = '".$nid."'");
$a = mysql_fetch_array($q);
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
$note_viewer .= <<<NOTE_VIEWER
<h2>By: $author</h2> - <h2>$date</h2>
<br/>
<p>$note</p>
<p>Request: $private</p>
NOTE_VIEWER;
echo $note_viewer;
}
The AJAX seems to be working now as it gives me Error...
concerning the docu of jQuery, you attach an event with the live() method. In your code, you define the click-method of node twice, I think: once with the live-attaching-stuff and once with note.click(). So it is not clear what to do when clicking or better when node is clicked, the click-event is defined :-) You define two different actions when note is clicked... try this one:
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
}
});
});
});
So what exactly is it doing? and What element is not visible? Your AJAX call isnt even using the response. If I understand your logic correctly, it should be...
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html(html);
}
});
the "html" variable in the success function is the response from the php script.
I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});
Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.
Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault
I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??