Php Js Ajax I need some assistance - php

I am trying to create a social dating site and I have my problem in the Add as Buddy Button. When you click it, my site should be sending the uid of the sender (from_uid) and the uid of the receiver (to_uid) to the database. It sends out the from_uid successfully but the to_uid always sends 0.
PHP
<div class="member" data-user="<?php echo $member['xmpp_user']; ?>" data-uid="<?php echo $member['uid']; ?>">
<input type="hidden" id="hiddenuid" value="<?php echo $member['uid']; ?>">
<img src="https://s3.amazonaws.com/wheewhew/user/<?php echo $member['uid']; ?>/photos/<?php echo $member['profile_pic']; ?>" />
<div class="member_name"><?php echo $member['firstname']." ".$member['lastname']; ?></div>
<div id="addbutton"><button type="submit" class="add"> Add as Buddy </button></div>
</div>
Javascript
<script type="text/javascript">
var BOSH_SERVICE = 'http://wheewhew.com:5280/http-bind';
var connection = null;
var xmpp_user = "<?php echo $xmpp_user; ?>#wheewhew.com/default";
var xmpp_pass = "<?php echo $xmpp_password; ?>";
var uid = "<?php echo $uid; ?>";
$(document).ready(function () {
$('#btn-logout').click(logout);
$('.add').click(addBuddy);
connectXMPP();
//updateLastSeen();
});
</script>
jabber.js
function addBuddy(){
var xmpp_user = $(this).parent().attr('data-user')+'#wheewhew.com/default';
var to_uid = $(this).parent().attr('data-uid');
$.ajax({
type: "POST",
url: "./ajax/addBuddy",
data: "from_uid="+uid+"&to_uid="+to_uid,
success: function(data) {
var ret = eval('('+data+')');
if(ret.status == 'success'){
connection.send($pres({to:xmpp_user,type:'subscribe'}).tree());
}
}
});
}

Your addBuddy function doesnt have a reference for what $(this) is. Try this out:
$('.add').click(function(){
addBuddy($(this));
});
And then in your function:
function addBuddy($btn){
var xmpp_user = $btn.parent().attr('data-user')+'#wheewhew.com/default';
var to_uid = $btn.parent().attr('data-uid');
// ajaxy stuff
}
That should help. At the very least, we can continue the discussion here rather than in the comments for the OP.

Related

php did not send data by using jquery

This is a code with DropDown list which can update the database upon on change, it doesn't work for some reason. I realize that the value $ gp_name didn't send out, can someone help me to fix it?
<select name='status' id='status'>
<option value="<?php echo $status ?>"><?php echo $status ?></option>
<option value="Inquiry">Inquiry</option>
</select>
<input type="hidden" name="gp_name" id="gp_name" value="<?php echo $gp_name;?>" />
<div id="autosavenotify"></div>
<script>
$(document).ready(function() {
var gp_name = $('#gp_name').val();
$('select').on('change', function() {
var statusVal = $(this).val();
var gp_name = $('#gp_name').val();
alert(statusVal,gp_name);
$.ajax({
type: "POST",
url: "save.php",
data: {
statusType: statusVal,
gp_name: gp_name
},
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
save.php
<?php
require_once("connMysql.php");
$gp_name=$_POST['gp_name'];
$st=$_POST['statusType'];
$qry ="UPDATE lotus_gp SET status='".$st."' where gp_name='".$gp_name."'";
$done = mysql_query($qry);
if($done)
{
echo $gp_name;
echo $st;
}
?>
First, check if the data is getting from your front-end sides on your PHP page.
if(isset($_POST['gp_name']) && isset($_POST['statusType'])){
$gpname = $_POST['gp_name']; // echo it to ensure
$satype = $_POST['statusType']; // echo it to ensure
}
If the data is not printed then you might have an issue with inputs.

403 forbidden in Codeigniter Ajax request even with cookie transfer

I am submiting a form with Ajax, I am also sending the cookie, however I still get the 403 forbidden. These are the 2 ways I tried sending the cookie.
Directly setting csrf cookie name and value in Ajax.
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = $('#title').val();
var message = $('#message').val();
console.log(google_name);
var csrf_test_name = $("input[name=csrf_test_name]").val();
console.log(csrf_test_name);
console.log(title);
console.log(message);
$.ajax({
type: "POST",
url: 'http://localhost/hbp/review/submit',
data: {
title,
message,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
Getting the CSRF cookie from the form field
<form id="reviewForm" method="POST">
<div class="control-group">
<div class="controls">
<input type="text" class="form-control"
placeholder="Title" id="title" required
data-validation-required-message="Please enter the review title"/>
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<textarea rows="10" cols="100" class="form-control"
placeholder="Message" id="message" required
data-validation-required-message="Please enter your message" minlength="5"
data-validation-minlength-message="Min 5 characters"
maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div> <!-- For success/fail messages -->
<br>
<div class="g-signin2 btn btn-default pull-right" data-onsuccess="onSignIn"></div>
<br/>
</form>
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = $('#title').val();
var message = $('#message').val();
console.log(google_name);
var csrf_test_name = $("input[name=csrf_test_name]").val();
console.log(csrf_test_name);
console.log(title);
console.log(message);
$.ajax({
type: "POST",
url: 'http://localhost/hbp/review/submit',
data: {
title,
message,
'csrf_test_name ' : 'csrf_test_name ',
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
None of them seem to work, here's the controller if it helps.
public function review($google_name, $google_email, $google_image, $message, $title)
{
$this->load->library('session');
$csrf_token = $this->security->get_csrf_hash();
$data = array(
'csrf_token' => $csrf_token
);
if (!$google_name and $google_email and $google_image and $message and $title) {
$this->load->library('session');
redirect('/', $this->session->set_flashdata('review_form_error', 'Error! All yields are required!')
);
} else {
echo $google_name, $google_email, $google_image, $message, $title;
$this->review_model->set_review($google_name, $google_email, $google_image, $message, $title);
redirect(base_url(), $this->session->set_flashdata('review_success', 'Thank you for providing us with your helpful feedback'));
}
}
try ajax setup
$.ajaxSetup({
data: {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
});
How to troubleshoot CSRF token issues?
open developer console in browser
go to network tab
click on the request being made
go to Cookies tab - compare request and response cookies
You can also var_dump($_POST) on the server side.
Question-specific remarks:
'csrf_test_name ' : 'csrf_test_name ',
should this not be
'csrf_test_name ' : csrf_test_name,
Try with double quotes:
'<?php echo $this->security->get_csrf_token_name(); ?>' : "<?php echo $this->security->get_csrf_hash(); ?>",
EXTRA: how to pass CI variables to JavaScript in a clean way, avoiding PHP/JS clutter?
Create a view file and include it in the bottom of your template:
file name = views/public/ci_config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
?>
<script type="text/javascript">
var CONFIG = {
'base_url': '<?php echo base_url(); ?>',
'csrf_expire': '<?php echo $this->config->item('csrf_expire'); ?>',
'csrf_token_name': "<?php echo $this->security->get_csrf_token_name(); ?>", // needs double quotes!
'csrf_hash': "<?php echo $this->security->get_csrf_hash(); ?>" // needs double quotes!
};
</script>
Load it in a parent template, for example the footer partial, with:
<?php $this->load->view('public/ci_config'); ?>
Easily access this data anywhere in JS files:
var csrf_token_name = CONFIG.csrf_token_name;
var csrf_hash = CONFIG.csrf_hash ;
Or like Aria said:
$.ajaxSetup({
data: {
CONFIG.csrf_token_name : CONFIG.csrf_hash
}
});
Now you don't have to put all your JS code in a PHP file.

Get key from input id jQuery

I have list with several inputs
<input type="hidden" id="elevens_id_ea" value="<?php echo $_GET['elev_id']; ?>" />
<input type="hidden" id="arskursen_ea" value="<?php echo $arskursen; ?>" />
<?php
if ($extraanpassning_hamta['atgard'] == true){
?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-red btn-sm" value="Ja">
<?php } else { ?>
<input name="extraanpassning" id="knapp[<?php echo $amnets_id['amne_id']; ?>]" type="button" class="btn-u rounded btn-u-green btn-sm" value="Nej">
<?php } ?>
The main problem is how to "catch" the value in the two latest inputs with:
id="knapp[<?php echo $amnets_id['amne_id']; ?>]"
If knapp[4] -> how do I get the 4?
The code above is a part of a button that changes value when the user presses it (without refreshing the page).
The JS
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var extraanpassningVal = $(this).attr("value");
var amne_id_ea = $(this).attr("id");
var elevens_id_ea = $("#elevens_id_ea").val(); //värdet av elev_id
var arskursen_ea = $("#arskursen_ea").val(); //värdet av elev_id
$.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
});
});
</script>
EDIT:
The main problem is how to get the key from a input with an id like knapp[4].
How do get the key within knapp[]?
Update (thanks to user:SpYk3HH)
<script>
$(document).ready(function(){
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajax) this.ajax.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajax = $.ajax({
type: "POST",
url: "iup_extraanpassning_byta.php",
data: {extraanpassningType: extraanpassningVal, amne_id_ea: amne_id_ea, elevens_id_ea: elevens_id_ea, arskursen_ea: arskursen_ea},
success: function() {
location.reload();
}
})
})
});
</script>
I think I get it? You want the key when calling the button in JS? So like say: key = this.id.replace(/knapp|\[|\]/g, '')
Update, I didn't see the brackets before
$('input[type="button"]').click(function(){
var key = this.id.replace(/knapp|\[|\]/g, ''), // <---They key
extraanpassningVal = $(this).attr("value"),
amne_id_ea = $(this).attr("id"),
elevens_id_ea = $("#elevens_id_ea").val(),
arskursen_ea = $("#arskursen_ea").val();
if (this.ajx) this.ajx.abort(); // helps prevent multiple ajaxing (multiclicking)
this.ajx = $.ajax({/* options */});
})
Does that help?
FYI, $(this).attr("id") and this.id are the same thing
$('[name=test]').each(function(i) { $('#bob').text(this.id.replace(/knapp|\[|\]/g, '')) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="knapp4" name="test" value='my id is "knapp[4]"' />
<hr />
key: <span id="bob"></span>
Try this.
var amne_id_ea = "knapp[4]",
value = amne_id_ea.substring(amne_id_ea.lastIndexOf("[")+1,amne_id_ea.lastIndexOf("]"));
alert(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Hope you are expecting this.

Not getting jquery Ajax data using dynamic id selector

My PHP code looks like this -
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>"></input>
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</Submit>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
I want to get the data of these <input> elements using jquery dynamic id selectors. My jQuery looks like -
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("[id^=SelectPostComment-]").click(function(){
var $td = $(this).closest('input').next();
var CommentText = $td.find("[id^=GetCommentText-]").val();
var PostID = $td.find("[id^=GetPostID-]").val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
But I'm not getting value of ajax data CommentText and PostID in my test1.php file when i click <button>. Not sure what mistake I'm making. Please help.
try this:
for ($i=0;$i<=10;$i++) {
?>
<div id="">
<input type="text" id="GetCommentText-<?php echo $i;?>" />
<input type="hidden" id="GetPostID-<?php echo $i;?>" value="<?php echo $i;?>">
<button type="button" id="SelectPostComment-<?php echo $i;?>" >Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('[id^="SelectPostComment-"]').click(function(){ // changed here
var $td = $(this).parent(); // changed here
var CommentText = $td.find('[id^="GetCommentText-"]:first').val(); // changed here
var PostID = $td.find('[id^="GetPostID-"]:first').val(); // changed here
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: CommentText, PostID: PostID},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>
Or You could use more efficient way (no need to make garbages in DOM Tree):
<?php
for ($i=0;$i<=10;$i++) {
?>
<div data-postId="<?php echo $i; ?>">
<input type="text" name="commentText" value="" />
<button type="button" class="submit-comment">Submit</button>
</div>
<?php
}
?>
<div id="ShowAjaxesult"></div>
and js part:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.submit-comment').click(function(){
var $parent = $(this).parent();
var postId = $parent.data('postId');
var commentText = $parent.find('input[name="commentText"]:first').val();
$.ajax( {
type : 'GET',
url:'test1.php',
data : {CommentText: commentText, PostID: postId},
success:function(data) {
$('#ShowAjaxesult').html(data);
}
});
});
});
</script>

Passing variables using jquery and ajax php

i'm following this tutorial, so my issue is:
I have this code here, which are some tables.
<tr id="<?php echo $id; ?>" class="edit_tr">
<td class="edit_td">
<span id="first_<?php echo $id; ?>" class="text"><?php echo $kodi; ?></span>
<input type="text" value="<?php echo $kodi; ?>" class="editbox" id="first_input_<?php echo $id; ?>" />
</td>
<td class="edit_td">
<span id="last_<?php echo $id; ?>" class="text"><?php echo $vlera; ?></span>
<input type="text" value="<?php echo $vlera; ?>" class="editbox" id="last_input_<?php echo $id; ?>"/>
</td>
</tr>
Now, this is the script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#first_"+ID).hide();
$("#last_"+ID).hide();
$("#first_input_"+ID).show();
$("#last_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var kodi=$("#first_input_"+ID).val();
var vlera=$("#last_input_"+ID).val();
var dataString = 'id='+ ID +'&kodi='+kodi+'&vlera='+vlera;
$("#first_"+ID).html('<img src="load.gif" />'); // Loading image
if(first.length>0&& last.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
I'm not passing variables right maybe..because it won't save them, the query won't excecute.
Thanks
The easiest way in jQuery to pass your form fields in ajax is by using serialize:
data: $("form").serialize();
An additional problem is that you are using two variables, first and last but you are not defining them anywhere.
Try this code:
$(function() { // This makes the same than $(document).ready();
$(".edit_tr").each(function() { // Instead of assign the click event, we loop through each element
var $element = $(this);
var id = this.id;
var $first = $('#first_' + id);
var $last = $('#last_' + id);
var $firstInput = $('#first_input_' + id);
var $lastInput = $('#last_input_' + id);
$element.click(function() {
$first.hide();$last.hide();
$firstInput.show();$lastInput.show();
}).change(function() {
$first.html('<img src="load.gif" />');
// Here you have an if, but those elements are not defined in the script...
// if (first.length > 0 && last.length > 0) {
$.post("table_edit_ajax.php", {
id : id,
kodi : $firstInput.val(),
vlera : $lastInput.val()
}, function(html) {
// Here again the two vars not defined
//$first.html(first);
//$last.html(last);
});
// }
});
});
});

Categories