I got a problem with blank space and special characters during a POST action using this AJAX function:
function comments(id,postId,user_id) {
var user_comments = encodeURIComponent($("#commentsId_"+id).val());
if(user_comments!=''){
var img = $("#img_"+id).val();
var username = "<?php echo $this->session->userdata('username'); ?>"
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/userscomment/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments},
success: function(data) {
$("#commentsId_"+id).val('');
var $sparkLines = $('.comments_body_'+id);
$("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+user_comments+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');
}
});
}
}
The PHP controller:
public function userscomment($comment_id,$post_id,$user_comments){
$this->load->model('comments');
$user_comments = utf8_decode(trim(mysql_real_escape_string($_POST['user_comments'])));
if(!empty($user_comments)){
$data = array("user_id" => $this->session->userdata('user_id'),
"comment_user_id" => $comment_id,
"comments" => $user_comments,
"post_id" => $post_id,
"username" => $this->session->userdata('username')
);
$this->comments->insertComments($data);
//logged user
$userRow = $this->register->get_login($this->session->userdata('user_id'));
redirect('social/userprofile/'.$userRow[0]['username']);
}
}
When an user post a comment like: "a b c d" the results showed in the view is: a%20b%20c%20d, if an user try to wrote a special characters like € i got this results %E2%82%AC
How can i prevent this problem?
EDIT:
Solved the problem was in the AJAX success function, i miss the
'+decodeURIComponent(user_comments)+'
success: function(data) {
$("#commentsId_"+id).val('');
var $sparkLines = $('.comments_body_'+id);
$("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+decodeURIComponent(user_comments)+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');}
Edit2: I've performed the code because encodeURIComponent don't allow this characters ~!*()'" , i've used replace functionality to bypass this limit, hope can be helpful.
function subcomments(id,postId,user_id) {
var user_comments = encodeURIComponent($("#commentsId_"+id).val()).replace(/\-/g, "%2D").replace(/\_/g, "%5F").replace(/\./g, "%2E").replace(/\!/g, "%21").replace(/\~/g, "%7E").replace(/\*/g, "%2A").replace(/\'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29");
if(user_comments!=''){
var img = $("#img_"+id).val();
var username = "<?php echo $this->session->userdata('username'); ?>"
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/userscommentcool/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments },
success: function(data) {
$("#commentsId_"+id).val('');
var $sparkLines = $('.comments_body_'+id);
$("#comments_add_"+id).append('<div id="id' + ($sparkLines.length + 1) + '" class="comments_body_"'+id+'><div class="feed-element comments_body_"'+id+'><a class="pull-left"><strong>'+username+' <i class="fa fa-comment-o"></i></strong></a><div class="media-body">'+decodeURIComponent(user_comments)+'<br></div><div class="col-lg-12"><a id="span_'+postId+'" onclick="callajaxcommcool('+postId+')" class="btn btn-xs btn-white"><i class="fa fa-star"></i><span id="span1_'+postId+'" style="display:none;">1</span> Cool </a></div></div></div></div>');
}
});
}
}
Don't use encodeURIComponent when you pass the parameter in an object. You only need that if you're constructing the URL-encoded string yourself. jQuery automatically encodes the parameters in the object, and the result is that it's being encoded twice. So just do:
var user_comments = $("#commentsId_"+id).val();
You should use javascript decodeURI("a%20b%20c%20d") convert it to "a b c d" again in your view.
Using php:
In your view, in the line that you put the encoded value, just use it:
echo urldecode("your_encoded_value");
Related
I have a save feature on my website so that the user can save an item. On the first click it updates and saves fine because it went through the PHP file, but what I am having trouble with is getting the ajax to update the link when clicked the second time since the link is created in the jquery code for updating it with AJAX. (passing the proper ID's is the problem) It should update the heart to red or green and add or remove the word 'Save'. I need to get the proper id updated on the second, third, etc. click.
Here is the jquery code:
I have 2 functions. saveLink and deleteLink.
This is my javascript file:
$(document).on("click", '.del-button', function () {
var savId = $(this).attr('data-sav-id');
deleteLink(savId);
});
$(document).on("click", '.sav-button', function () {
var delId = $(this).attr('data-del-id');
saveLink(delId);
});
function saveLink( saveID ){
var id = saveID;
$.ajax({
method: "POST",
url: "saveLink.php",
dataType: "json",
data: {
'id' : id,
},
success: function(returnID){
var returnID = $.trim(returnID);
if(returnID){
$('#showSaved' + id).html('<span id="removeSaved('+ id +');"><i class="fa fa-heart" style="color:#d52917;"></i></span>');
}
}
});
}
function deleteLink( deleteID ){
var deletedID = deleteID;
$.ajax({
method: "POST",
url: "deleteLink.php",
dataType: "json",
data: {
'deletedID' : deletedID,
},
success: function(deleteIDFunc){
var deleteIDFunc = $.trim(deleteIDFunc);
if(deleteIDFunc){
$('#removeSaved' + deletedID).html('<span id="showSaved('+ deletedID +');">Save <i class="fa fa-heart"></i></span>');
}
else {
alert('Your saved post was not removed. Please try again');
}
}
});
}
Here is the PHP code that handles the initial click:
$query = "SELECT
count(replies.reply_topic) as replyCount,
topics.topic_id,
topics.topic_subject,
topics.topic_date,
topics.topic_cat,
topics.topic_creator,
topics.topic_likes,
users.user_id,
users.username,
profile.profile_id,
profile.profile_pictureMain,
profile.profile_users,
savelink.saveLink_id,
savelink.saveUser_id,
savelink.link_id
FROM
topics
LEFT JOIN
users
ON
topics.topic_creator = users.user_id
LEFT JOIN
replies
ON
replies.reply_topic = topics.topic_id
LEFT JOIN
profile
ON
profile.profile_users = users.user_id
LEFT JOIN
savelink
ON
savelink.link_id = topics.topic_id
GROUP BY
topics.topic_id
ORDER BY
topics.topic_date DESC
LIMIT ?, ?
";
$stmt = $conn->prepare($query);
$stmt->bindParam(1, $start, PDO::PARAM_INT);
$stmt->bindParam(2, $limit, PDO::PARAM_INT);
$stmt->execute();
$returnAmt = $stmt->fetchAll();
if($stmt->rowCount() > 0){
$returnValues = "";
foreach($returnAmt as $row){
$returnValues .=
if(isset($_SESSION['user_session']) && $row['saveUser_id'] == $_SESSION['user_session']){
$returnValues .= '<span id="removeSaved'.$row['saveLink_id'].'"><i class="fa fa-heart" style="color:#d52917;"></i></span>';
}
else if(isset($_SESSION['user_session'])){
$returnValues .= '<span id="showSaved'.$row['topic_id'].'">Save <i class="fa fa-heart"></i></span>';
}
else{
$returnValues .= '</i>';
}
$returnValues .= '</div></div></span></div>
}
echo $returnValues;
Here is the html code for displaying the results:
<div role="tabpanel" class="tab-pane active" id="Top">
<div id="rowDisplayResults">
<!--Display results here-->
</div>
</div>
This is what I would like the save feature to look like. A red heart when saved and green when not.
Should I be adding another variable to the save and delete link functions to pass the proper ID's after the second click?
Any help would be much appreciated. thanks.
Change your code like this. Also change the html for this logic
$(document).on("click", '.del-button', function () {
var savId = $(this).attr('data-sav-id');
deleteLink(savId);
});
$(document).on("click", '.sav-button', function () {
var delId = $(this).attr('data-del-id');
saveLink(delId);
});
function saveLink( saveID ){
var id = saveID;
$.ajax({
method: "POST",
url: "saveLink.php",
dataType: "json",
data: {
'id' : id,
},
success: function(returnID){
var returnID = $.trim(returnID);
if(returnID){
$('#showSaved' + id).html('<span id="removeSaved('+ id +');"><a href="javascript:void();" class="del-button pull-right"'+
' data-sav-id=' + returnID + '"><i class="fa fa-heart" style="color:#d52917;"></i></a></span>');
//onclick="deleteLink('+ returnID +');
}
}
});
}
function deleteLink(deleteID) {
var deletedID = deleteID;
$.ajax({
method: "POST",
url: "deleteLink.php",
dataType: "json",
data: {
'deletedID': deletedID,
},
success: function (deleteIDFunc) {
var deleteIDFunc = $.trim(deleteIDFunc);
if (deleteIDFunc) {
$('#removeSaved' + deletedID).html('<span id="showSaved(' + deletedID + ');"><a href="javascript:void();" '+
'class="pull-right sav-button" data-del-id=' + deleteIDFunc + '">Save <i class="fa fa-heart"></i></a></span>');
}
//onclick="saveLink(' + deleteIDFunc + ');
else {
alert('Your saved post was not removed. Please try again');
}
}
});
}
Excuse my English, I hope you can understand my question...
In my program, when you submit a new record to the database (MySQL) using a modal+form, it is drawn in a data table without refreshing or recharging the actual page, it's appended dynamically.
What I need to do is, in every new record, draw/append the data AND 2 buttons (1 for deleting that record and 1 for updating it) with the ID of the new data.
I read I can use insert_id() to get the last inserted id, but I don't know how to use it and how to work with the result in my Ajax call.
Any hint, please? I'm pretty new to programming.
Thanks for your time.
EDIT
I need the data I introduced in the modal/form (for that I was using .serialize()) AND the ID generated in the DB...
I don't know how to use the model/controller returned ID info.
I have this in my controller:
public function nuevo_elemento_diccionario()
{
$this->load->helper('form');
$this->load->library('form_validation');
// Validation rules that I deleted for this post
if ($this->form_validation->run() === FALSE)
{
$this->load->view("header");
$this->load->view("section-aside");
$this->load->view("vista_nuevo_elemento_diccionario", $datos);
$this->load->view("footer");
}
else
{
$last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
echo json_encode(array('last_id' => $last_id));
redirect('/diccionarios/lista_diccionarios');
}
}
Model:
public function nuevo_elemento_diccionario()
{
$datos = array(
'ELDI_Key' => $this->input->post('eldi_key'),
'ELDI_Display' => $this->input->post('eldi_display'),
'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
);
$this->db->insert('elementos_diccionario', $datos);
/* $ultima_id = $this->db->insert_id();*/
$last_id = $this->db->insert_id();
return $last_id;
}
Javascript/Ajax (where you see var key = $('input[name="eldi_key"]').val(); and using it, is where I need to use the ID to use the new ID for delete and update clicking the generated buttons):
function nuevo_elemento()
{
var id =$('input[name="eldi_id"]').val();
var display = $('input[name="eldi_display"]').val();
var key = $('input[name="eldi_key"]').val();
key = key.split(" ").join("_").toLowerCase();
swal({
title: 'Añadir elemento',
text: "¿Quieres añadir este elemento?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sí',
cancelButtonText: 'No'
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
url: $("#base_url").attr("valor") +
"diccionarios/nuevo_elemento_diccionario",
data: $("#formNuevoElementoDiccionario").serialize(),
success: function(data) {
console.log(data);
$('#Modal_Add').modal('hide');
$("#formNuevoElementoDiccionario").trigger("reset");
var html =
'<tr>'+
'<td>' + key + '</td>' +
'<td>'+ display +'</td>'+
'<td>'+
'<span class="btn btn-default editar_elemento"
id=' + key + ' value="' + key + '">' +
'<a href="'+$("#base_url").attr("valor") +
"diccionarios/elemento_diccionario/"+key+'" title="Editar">' +
'<i class="material-icons">edit</i>' +
'</a>' +
'</span>' +
'</td>' +
'<td>' +
'<span class="btn btn-default borrar_elemento"
id="'+ key +'" value="'+ key +'">'+
'<i class="material-
icons">delete_outline</i>'+
'</span>'+
'</td>'+
'</tr>'
$('#tabla-diccionarios').append(html);
swal("Añadido", "Elemento añadido correctamente",
"success");
$(".borrar_elemento").off();
evento_borrar_elemento();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + textStatus);
}
});
}
})
}
You can use insert_id() only after inserting data to DB. If you need user last id in controller or js try this:
public function nuevo_elemento_diccionario()
{
$datos = array(
'ELDI_Key' => $this->input->post('eldi_key'),
'ELDI_Display' => $this->input->post('eldi_display'),
'ELDI_SuDiccionario' => $this->input->post('eldi_sudiccionario'),
);
$this->db->insert('elementos_diccionario', $datos);
$ultima_id = $this->db->insert_id();
return $ultima_id;
}
Then you can use json_encode() for return data to js in Controller:
public function nuevo_elemento_diccionario()
{
$this->load->helper('form');
$this->load->library('form_validation');
// Validation rules that I deleted for this post
if ($this->form_validation->run() === FALSE)
{
$this->load->view("header");
$this->load->view("section-aside");
$this->load->view("vista_nuevo_elemento_diccionario", $datos);
$this->load->view("footer");
}
else
{
$last_id = $this->mod_diccionarios->nuevo_elemento_diccionario();
echo json_encode(array('last_id' => $last_id));
// i`m not sure that you need to use redirect
redirect('/diccionarios/lista_diccionarios');
}
}
In you js edit success function:
success: function(data) {
var result = JSON.parse(data);
var insert_id = result.insert_id;
Ajax is Not Working : I want to update one record using Code Igniter framework. when i passing po_id to below url. my ajax is not working. but without passing id my below ajax is working.
<a class="btn btn-success" href="<?php echo base_url('inventory_c/view_purchase_update/'.$result->po_id);?>">Update</a>
Controller:
public function view_purchase_update() {
$data['pitems'] = $this->inventory_m->purchase_items_update($po_id);
$data['sname'] = $this->inventory_m->getsuppname($supplier_id);
$data['sid'] = $this->inventory_m->getsuppid($po_id);
$this->load->view('superadmin/editable_purchase_update',$data);
}
Ajax Code:
$.ajax({
type: "POST",
url: "add_temp_purchase",
cache: false,
data: 'itemnum='+itemnum+'&itemname='+itemname+'&costprice='+costprice+'&quantity='+quantity+'&customer_id='+customer_id+'&sales='+sales,
dataType: "html",
success: function(returnhtml) {
}
});
When sending data with Ajax mind that it's JSON formatted.
What you can do is below:
$.post( "add_temp_purchase", {
itemnum: itemnum,
itemname: itemname,
costprice: costprice,
quantity: quantity,
customer_id: customer_id,
sales: sales
}).success(function( data ) {
alert( "success" );
});
In your controller you would have the follwing
public function postData() {
$postData = $this->input->post();
$itemNum = $postData['itemnum'];
#etc....
}
Aswell can you confirm you can print out $result->po_id in your view?
It seems that you never parse that to the view, in your controller you should do the following to make sure you have this
public function view_purchase_update() {
$data['pitems'] = $this->inventory_m->purchase_items_update($po_id);
$data['sname'] = $this->inventory_m->getsuppname($supplier_id);
$data['sid'] = $this->inventory_m->getsuppid($po_id);
$data['po_id'] = $po_id;
$this->load->view('superadmin/editable_purchase_update',$data);
}
Then in your view you will use it like this
<a class="btn btn-success" href="<?= base_url('inventory_c/view_purchase_update/'.$po_id);?>">Update</a>
This question already exists:
Database values are not updating?
Closed 8 years ago.
I am using this code to call ajaxvote.php
$('.vote').click(function(){
$.ajax({
url: 'ajaxvote.php',
type: 'POST',
cache: 'false',
success: function () { alert("Success!"); } ,
error: function () { alert("Error!"); }});
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var postid = parent.data('postid');
var score = parent.data('score');
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('.vote-score').html(++score).css({'color':'orange'});
self.css({'color':'orange'});
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('.vote-score').html(--score).css({'color':'red'});
self.css({'color':'red'});
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
parent.addClass('.disabled');
This is the code from my webpage
<div class="item" data-postid="<?php echo $rows['ID'] ?>" data-score="<?php echo $rows['VOTE'] ?>">
<div class="vote-span">
<div class="vote" data-action="up" title="Vote up"><i class="fa fa-camera-retro"></i></div>
<div class="vote-score"><?php echo $rows['VOTE'] ?></div>
<div class="vote" data-action="down" title="Vote down"><i class="fa fa-camera-retro"></i></div>
</div>
This is my php code
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) && (isset($_POST['action']))) {
$postId = $_POST['postid'];
if (isset($_SESSION['vote'][$postId])) return;
$query = $mysqli - > query("SELECT VOTE from stories WHERE ID = $postId LIMIT 1");
while ($rows = mysqli_fetch_array($query)) {
if ($_POST['action'] === 'up') {
$vote = ++$rows['VOTE'];
} else {
$vote = --$rows['VOTE'];
}
$mysqli - > query("UPDATE stories SET VOTE = $vote WHERE ID = $postId ");
$_SESSION['vote'][$postId] = true;
}
}
}
I know I can connect to database because I can login. I also get the alert success I have set up above, However, the values are not updating in Database.
EDIT
I have added more Ajax code that I had already written.
When posting via ajax, you need to send through the data you actually want to post.
var postData = {name:"Mister",lastName:"Frodo"}; //Array
$.ajax({
url : "ajaxvote.php",
type: "POST",
data : postData,
success: function(data, textStatus, jqXHR)
{
//Handle response
},
error: function (e) {
// Handle error
}
});
In this case, the post ID and score needs to be grabbed. You also need to grab what kind of action is clicked (typically through a click event bind on the divs with class="vote". For example purposes, let's just set it to "up" for now:
var postId = $('div.item').attr('data-postid').val();
var score = $('div.item').attr('data-score').val();
var postData = {postId: postId, score: score, action: 'up'}
You can now post that "postData" to your ajaxvote.php.
Also, you can use jQuery's $.POST method
$.post("ajaxvote.php", { name: "Mister", lastName: "Frodo" } );
Now for parsing your form, have a look at jQuery's serialize which goes through your form takes each input's [name] attribute along with the value to create a data-string.
Example
name=Mister&lastName=Frodo
This is ideal for sending through with the "data" attribute in $.ajax. Have a look at this answer for more regarding jQuery's serialize.
I have an ajax call for a form submit; it works fine if I pass my sql arguments when I hard code them, however if I want to pass my sql query arguments with inputs (from View) in my model it says: Message: Undefined index: startDate and endDate.
Here is my View:
<?PHP
$formData2 = array(
'class' => 'form-horizontal',
'id' => 'frm2',
);
echo form_open('gallery/fetchAssociates', $formData2);
?>
<input id="startDate" class="span2" size="16" type="text" />
<input id="endDate" class="span2" size="16" type="text" />
<input type="submit" class="btn btn-primary"
value="Submit" id="querystartEnd" name="querystartEnd" />
<?PHP
echo form_close();
?>
and my javascript for AJAX call is as following:
$.ajax({
type: "POST",
async: false,
dataType: "json",
?>",
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success: function(data) {
html = "<table id='myTable'><thead><tr id='test'><th>ID</th><th>Start Date</th><th> LName</th></tr></thead><tbody id='contentTable'>";
for (var i = 0; i < data.length; i++)
{
html = html + "<tr id='trResponses' ><td><div >" + data[i]['id']
+ " </div></td><td><div >" + data[i]['start'] +
"</div> </td><td><div >" + data[i]['username'] +
"</div></td></tr>";
}
html = html + "</tbody></table>";
$("#resultFrm2").html(html);
},
error: function()
{
alert('error');
}
});
and here is my controller:
public function fetchAssociates() {
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
//die();
$this->load->model('user_model');
echo json_encode($this->user_model->getAll());
}
and my Model method is as following:
public function getAll()
{
$wtc = $this->load->database('wtc', TRUE);
$sql = "SELECT username, MIN(timeIn) as start
FROM tc_timecard
GROUP BY userid having MIN(timeIn) > ? and MIN(timeIN) < ?
order by MiN(timeIN);";
//$q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
$q = $wtc->query($sql, array($this->input->post('startDate'),
$this->input->post('endDate')));
if ($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
As you see my comments in my code: if I have
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
uncommented in firebug in response it says "Message: Undefined index: startDate and endDate."
Also in my controller if I have
// $q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
un-commented it works but once I want to pass the inputs by the following line of code it does not work :
$q = $wtc->query($sql, array($this->input->post('startDate'), $this->input->post('endDate')));
What can be the reason that I cannot access my inputs in my controller or Model?
If it is not clear for you, please let me know which part you need more clarification.
EDITED:
It is worth mentioning that my ajax call is inside the following block:
$('#frm2').submit(function(e)
{
e.preventDefault();
//My AJAX call here
});
Many thanks in advance,
You are not passing any data through ajax
// Collect data from form which will be passed to controller
var data = {
start_data : $('#startDate').val(),
start_data : $('#endDate').val(),
}
$.ajax({
type: "POST",
async: false,
dataType: "json",
data : data // data here
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success : function(data){
// Success code here
},
error: function(data){
// error code here
}
})