Unable to find the solution help me out ..regarding js and php - php

php code :
while($row = mysql_fetch_assoc($arr))
{
$id = $row['id'];
$user_from = $row['user_from'];
$user_to = $row['user_to'];
$date = $row['date'];
$msg_body = $row['msg_body'];
$opened = $row['opened'];
if(strlen($msg_body)>150)
{
$msg_body = substr($msg_body,0,150)."....";
}
echo "<div id='toggletext$id' style='background-color:#ADD8E6;padding:6px;' onclick='toggle()'>";
echo "<form method='post'>";
echo "<input type='hidden' id='id1' value=$id>";
echo "<a href='$username'>$username</a>&nbsp";
echo "&nbsp: $msg_body ";
echo "</form>";
echo "</div> <hr/>";
}
** it will echo the value present in $arr in forms of div so each $arr row will get displayed with unique div id **
js code :
function toggle()
{
var hr = new XMLHttpRequest();
var id = document.getElementById("id1").value;
var tx = "toggletext"+id;
var fn = document.getElementById(tx);
var url = "in.php";
fn.style.backgroundColor = "#fff";
var v = '<?php echo #$username;?>';
var vars = "post="+v+"&id="+id;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
// The problem is ...when there are 2 div(if $arr has 2 rows)..if i click the second div first div will get selected ..

Change your id in your input type hidden
echo "<input type='hidden' id='id".$id."' value=$id>";
and get like this in your javascript...
var incval = '<?php echo $id ?>';
var id = document.getElementById("id"+incval).value;
I am giving php echo because you already call username....
Finally, try to use My_Sqli function instead my_sql

Related

Get Value of Appended Element After Submit Button with POST Type Form

I want to get the value of appended elements after submitting. It appends the right name attributes, but I can't get the value
<script>
<?php
$options = '';
while($searched_species_adding = mysqli_fetch_array($search_species_adding)){
$name = $searched_species_adding['name'];
$options = $options.'<option>'.$name.'</option>';
}
echo 'var options = "'.$options.'";';
?>
var count=2;
$( "#add-species" ).click(function() {
var html=$("<tr id='species-"+count+"'><td><select name='species-"+count+"' class='form-control'>"+options+"</select></td><td><input id='species-num-"+count+"' name='species-num-"+count+"' class='form-control' type='number'></td></tr>");
$("#species-container").append(html);
$("#species-num-"+count).prop('required',true);
count++;
var wew = ($('tr', $("#wew").find('tbody')).length);
$(".tr-num").remove();
$("#species-container").append("<input class='tr-num' type='hidden' value='"+wew+"' name='tr_count'>");
$(".tr-num").val(wew);
});
$( "#remove-species" ).click(function() {
count--;
$("#species-"+count).remove();
var wew = ($('tr', $("#wew").find('tbody')).length);
$(".tr-num").val(wew);
});
</script>
Above is the script for appending.
And here is my code in getting the values in a form after submitting:
if(isset($_POST['add-delivered'])){
$requestor = $_POST['requestor'];
$org_office = $_POST['org_office'];
$address = $_POST['address'];
$date_pickup = $_POST['date_pickup'];
$location = $_POST['location'];
$planting_type = $_POST['planting_type'];
$tr_count = $_POST['tr_count'];
$species = '';
for($x = 1; $x <= $tr_count; $x++){
$species = $species.$_POST['species-'.$x];
}
echo '<script>alert("'.$tr_count.'")</script>';
exit();
}

EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. - Codeigniter

I am getting an error while implementing SSE.
Error :
EventSource's response has a MIME type ("text/html") that is not "text/event-stream". Aborting the connection. - Codeigniter
Below you can find the code :
if(typeof(EventSource) !== "undefined") {
var path = "<?php echo base_url()?>lawyer/consultation/video_calling/<?php echo $client_user_id ?>";
var source = new EventSource(path);
source.onmessage = function(event) {
var img_url = '<?php echo base_url() ?>assets/images/main-logo.png';
var resp = JSON.parse(event.data);
var id = resp.id;
var sender_id = resp.sender_id;
var receiver_id = resp.receiver_id;
var session_id = resp.session_id;
var token = resp.token;
var client_receiver_id = <?php echo $client_user_id ?>;
if(client_receiver_id == receiver_id){
// alert('fgdgdg');
spawnNotification('Somebody calling you!', ''+img_url+'', 'LawOn says');
//document.getElementById("result").innerHTML += event.data + "<br>";
}
};
} else {
document.getElementById("result").innerHTML = "SSE not Supported";
}

unable to pass variable to other page using ajax

I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>

getting multiple post id wordpress

I am making a voting system for my theme
It is working fine in single.php
But when i keep it in index.php it only considers the id of first post and rest don't work
I think its not dealing with multiple post id
Here is the full code
Setting a cookie, calling Ajax action with jQuery
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$("#vote").not(".disabled").click(function() {
var el = $(this);
el.html('<span id="loader"></span>');
var nonce = $("input#voting_nonce").val();
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: '<?php echo $post->ID; ?>',
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = "<?php echo $post->ID; ?>";
} else {
var newcookie = cookie + ",<?php echo $post->ID; ?>";
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
This is what I put in my functions.php to register actions
add_action("wp_ajax_add_votes_options", "add_votes_options");
add_action("wp_ajax_nopriv_add_votes_options", "add_votes_options");
function add_votes_options() {
if (!wp_verify_nonce($_POST['nonce'], 'voting_nonce'))
return;
$postid = $_POST['postid'];
$ip = $_POST['ip'];
$voter_ips = get_post_meta($postid, "voter_ips", true);
if(!empty($voter_ips) && in_array($ip, $voter_ips)) {
echo "null";
die(0);
} else {
$voter_ips[] = $ip;
update_post_meta($postid, "voter_ips", $voter_ips);
}
$current_votes = get_post_meta($postid, "votes", true);
$new_votes = intval($current_votes) + 1;
update_post_meta($postid, "votes", $new_votes);
$return = $new_votes>1 ? $new_votes." votes" : $new_votes." vote";
echo $return;
die(0);
}
this is how I call my vote button and count button
<?php
// This will display "0 votes" and increase as votes are added
$votes = get_post_meta($post->ID, "votes", true);
$votes = !empty($votes) ? $votes : "0";
if($votes == 1) $plural = ""; else $plural = "s";
echo '<div id="votecounter">'.$votes.' vote'.$plural.'</div>';
?>
<?php
// This will display the vote button and disable it if a cookie has already
// been set. We also add the security nonce here.
$hasvoted = $_COOKIE['better_votes'];
$hasvoted = explode(",", $hasvoted);
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' class="disabled"';
} else {
$vtext = "VOTE";
$class = "";
}
?>
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce', 'voting_nonce'); ?>
As for a beginning, you shouldn't have the same id for your button over and over again, so change this:
<a href="javascript:void(0)" id="vote"<?php echo $class; ?>><?php echo $vtext; ?></a>
To this:
<?php
if(in_array($post->ID, $hasvoted)) {
$vtext = "VOTED";
$class = ' disabled';
} else {
$vtext = "VOTE";
$class = "";
}
<?php echo $vtext; ?>
This will result in id attribute of each vote button in the form of "vote-{post id}". And since I guess you still want to address all of your buttons in some way, you can now use the .vote-btn selector.
The problem with your JavaScript is that you pass the ID of the post to the script directly. This is fine, when you have only one post on the page, but when you have multiple posts, you have to either print your code multiple times, or get the post ID dynamically.
I prefer the second option, here's how your JS code should change in order to get that working:
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
function setCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
$(".vote-btn").not(".disabled").click(function() {
var el = $(this),
nonce = $("input#voting_nonce", el.parent()).val(),
id = el.attr('id').replace(/vote-/, ''); // get the Post ID
el.html('<span id="loader"></span>');
var data = {
action: 'add_votes_options',
nonce: nonce,
postid: id,
ip: '<?php echo $_SERVER['REMOTE_ADDR']; ?>'
};
$.post('<?php echo admin_url('admin-ajax.php'); ?>', data,
function(response){
if(response!="-1") {
el.html("VOTED").unbind("click");
if(response=="null") {
alert("A vote has already been registered to this IP address.");
} else {
$("#votecounter").html(response);
alert("Thanks for your vote.");
}
var cookie = getCookie("better_votes");
if(!cookie) {
var newcookie = id;
} else {
var newcookie = cookie + "," + id;
}
setCookie("better_votes", newcookie, 365);
} else {
alert("There was a problem registering your vote. Please try again later.");
}
});
return false;
});
})(jQuery);
/* ]]> */
</script>
So, in the above code, we get the ID of the post that the user is voting from, by replacing "vote-" with an empty string(so only the ID remains). Note also the following line:
nonce = $("input#voting_nonce", el.parent()).val(),
In this line, I assume that the nonce input as well as the button have the same parent(although you should be able to use the same nonce for all posts). You can also take your nonce one step further, by changing the code that generates it to:
<?php if(function_exists('wp_nonce_field')) wp_nonce_field('voting_nonce-' . $post->ID, 'voting_nonce'); ?>
And change your add_votes_options function to:
$postid = $_POST['postid'];
if ( ! wp_verify_nonce( $_POST['nonce'], 'voting_nonce-' . $postid ) )
return;
This will bind each nonce to the ID of the post, that the nonce is for.
I think that's pretty much your problem. Please try my code and tell me if there are problems with it(if it's a JS error, please add message from the error console in FireBug, or WebKit's inspector).
PP: Just saw this:
Looking for an answer drawing from credible and/or official sources.
My answer was backed-up by my experience with WordPress and jQuery - and I earn my living by working mainly with WordPress(less jQuery, but I use it relatively often as well). Hope this will be enough :)

jquery hide() executing wrongly

I have built an AJAX driven form wherein when i press the submit button,it displays data via AJAX.All that is working fine.Now i want to hide a specific too as a part of the AJAX function.But instead of just hiding that the whole page goes blank!Heres the code
The AJAX function:
function ajax_post(){
$("#form1").hide();
var hr = new XMLHttpRequest();
var url = "my_parse_filefe.php";
var fn = document.getElementById("description").value;
var nm = document.getElementById("name").value;
var sel = $('#list option:selected').text()
var vars = "todo="+fn+"&name="+nm+"&sel="+sel;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
}
The PHP in the same file:
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM timetracking");
while($row = mysql_fetch_array($sql))
{$name = $row['name'];
$description = $row['description'];
$hours = $row['hours_invested'];
$finaltable1 .= '<table class="ftable" width="650">
<tr>
<td align="center">'.$name.'</td>
<td align="center">'.$description.'</td>
<td align="center"> '.$hours.'</td>
</tr>
';}
?>
<div id="form1"><?php print $finaltable1; ?> </div>
<div id="status"></div>
Note:When I put normal text inside the "form1" div it works!when i put php tags it stops working.

Categories