Splitting multiple elements and sending via ajax - javascript

I'm trying to map every element that has a contenteditable attribute in order to send the results with each individual element's value being sent. However, I am running into a problem when I try to use comma's inside a field because I am joining the elements then splitting them to get an array of values.
Here is my code:
function getProfileData(element, button) {
var profile_data = $(element).html();
var data = $(element).blur(function() {
profile_data = $(element).map(function() {
return this.innerHTML;
}).get();
});
$(button).on('click', function() {
var edited_content = profile_data.join(", ");
var split = edited_content.split(",");
$.ajax({
method : "POST",
url : "/members/profile/create-profile",
data : {
display_name : split[0],
email_address : split[1],
age : split[2],
location : split[3],
bio : split[4]
},
}).done(function() {
alert("Profile saved!");
location.href = '/members/profile';
}).fail(function() {
alert("Error saving profile, please try again");
});
});
}
Is there any way to not having a comma inside a field cut off the rest of the text after it?
Thanks!

Related

Ajax if more then one #mention

I am trying to make a facebook and twitter style mention system using jquery ajax php but i have a problem if i try to #mention more then one user. For example if i start to type something like the follow:
Hi #stack how are you.
The results showing #stack but if i try to mention another user like this:
Hi #stack how are you. i am #azzo
Then the results are nothing. What i am missing my ajax code anyone can help me please ?
I think there is a regex problem for search user_name. When i write some username after first one like #stack then the ajax request posting this:
f : smen
menFriend : #stack
posti : 102
But if i want to tag my other friend in the same text like this:
Hi #stack how are you. I am #a then ajax request looks like this:
f : smen
menFriend : #stack, #a
posti : 102
So what I'm saying is that apparently, ajax interrogates all the words that begin with #. It needs to do is interrogate the last #mention from database.
var timer = null;
var tagstart = /#/gi;
var tagword = /#(\w+)/gi;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var goWord = contents.match(tagstart);
var goname = contents.match(tagword);
var type = 'smen';
var data = 'f=' +type+ '&menFriend=' +goname +'&posti='+ID;
if (goWord.length > 0) {
if (goname.length > 0) {
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
}else{
$(".menlist"+ID).hide().empty();
}
}
});
}
}
}, 500);
});
Also here is a php section for searching user from database:
$searchmUser = mysqli_real_escape_string($this->db,$searchmUser);
$searchmUser=str_replace("#","",$searchmUser);
$searchmUser=str_replace(" ","%",$searchmUser);
$sql_res=mysqli_query($this->db,"SELECT
user_name, user_id
FROM users WHERE
(user_name like '%$searchmUser%'
or user_fullname like '%$searchmUser%') ORDER BY user_id LIMIT 5") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($sql_res,MYSQLI_ASSOC)) {
// Store the result into array
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
Looks like you're sending an array which is result of match you in AJAX request.
Though I cannot test it but you can use a lookahead in your regex and use 1st element from resulting array. Negative lookahead (?!.*#\w) is used to make sure we match last element only.
var timer = null;
var tagword = /#(\w+)(?!.*#\w)/;
$("body").delegate(".addComment", "keyup", function(e) {
var value = e.target.value;
var ID = e.target.id;
clearTimeout(timer);
timer = setTimeout(function() {
var contents = value;
var type = 'smen';
var goname = contents.match(tagword);
if (goname != undefined) {
var data = 'f=' +type+ '&menFriend=' +goname[1] +'&posti='+ID;
$.ajax({
type: "POST",
url: requestUrl + "searchuser",
data: data,
cache: false,
beforeSend: function() {
// Do Something
},
success: function(response) {
if(response){
$(".menlist"+ID).show().html(response);
} else {
$(".menlist"+ID).hide().empty();
}
}
});
}
}, 500);
});

$_POST does not pass non-alphanumeric

I want to pass data via AJAX. The variable consists of both numbers and non-alphanumeric variables ("001.0/210.00"). My $_POST['task'] doesn't return a value. I've attempted to change the data to JSON, but that doesn't seem to work.
$(document).ready(function(e){
var trigger = $('.task a'),
var container = $('#content1');
trigger.on('click', function(e){
var shotElement = event.currentTarget.children[0].innerText;
$.ajax({
type : 'POST',
url : 'indexPipeline.php',
data : { task: shotElement },
success : function(response) {
$("#displayPipeline").load("indexPipeline.php");
}
});
return false;
});
});

Javascript access TDs from closest TR. Javascript PHP Session

I am using this snippet: http://bootsnipp.com/snippets/featured/payment-form-with-total-preview
And my problem is on the X click, when removing an element, I would like to access the value of the TDs (Concept, Description, Amount, Status and Date), in order to, after having those values, removing the element from my PHP session array, which is an array of all the payments, so I just would do an unset based on the values I get.
This is what I have done so far:
$(document).on('click', '.input-remove-row', function(){
var tr = $(this).closest('tr');
var tds = tr.children('td');
var txt = $(tds[0]).text()
var txt1 = $(tds[1]).text()
var txt2 = $(tds[2]).text()
document.write (txt1)
tr.fadeOut(200, function(){
tr.remove();
calc_total()
});
});
I have trying printing the value of txt, txt1 and txt2 but I always get the amount, I don't reach the other tds, and they are all supposed to be tds with class input based on the other function.
Another question would be how to handle the session here, but that's not the highest priority issue.
Any idea¿? Thank you in advance.
Edit :
If you want to use php to store session value, then you should use $.ajax:
$(document).on('click', '.input-remove-row', function(){
var tr = $(this).closest('tr');
var tds = tr.children('td');
var txt = $(tds[0]).text()
var txt1 = $(tds[1]).text()
var txt2 = $(tds[2]).text()
var data = {
concept: txt,
description: txt1,
amount: txt2
};
$.ajax("YOUR_PHP_POST_URL", {
type: 'POST',
data: data,
success: function(response) {
//Check if store success
if (POST_SUCCESS) {
// remove tr and calc total here
tr.fadeOut(200, function(){
tr.remove();
calc_total();
});
} else {
//notify store failed...
}
},
});
});
When you want the sessioned data, you can use:
$.ajax("YOUR_PHP_GET_URL", {
success: function(response) {
// convert reposnse to object
// then do something like append this data to table, and calc_total
},
});
Or if you use PHP to create the page, you can directly put those session data on table while rendering.
For more about ajax, go to jquery ajax, and you can also find more details, examples on internet.

How to load json response which contain string values only to a combo box already created

I have a String array containing some names. I return it as a Json response and now I need to load those names in to a combo box in my html page. Combo box have been already created ans say its id is names. This is the function I wrote.
function loadSiteOfficers(ele){
var selected = ele.value;
if(selected == "Site Officer"){
jQuery.ajax({
type : "POST",
url : "/TFProject/load_officers.htm",
success : function(response) {
if (response.status == "SUCCESS") {
alert(response.result);
// load response results to the combo box
} else {
////// some code here
}
},
error : function(e) {
alert('Error: ' + e);
}
});
}
}
alert(response.result) gives me names separated by commas. They are retrieved from the database.
I am bit confused here and need to know how to load the data. I will be grateful if you can help me
Thanks.
try something like this...
$.each(response.result, function(key, value) {
$('#names').append($('<option></option>').val(key).html(value));
});

Assign value to id in html link with javascript

I have the following link that passes an id to my controller to render a report.
Print Report
I would like to assign this value id in the link above to the result I have returned from the database in the call below....
// Global variable
var DocumentID = null;
$('#Save').click(function(e) {
if (document.forms[0].checkValidity()) {
e.preventDefault();
$.ajax({
url: "/Home/SaveDetails",
dataType: "json",
type: "POST",
data: ko.toJSON(viewModel),
contentType: "application/json;charset=utf-8",
success: function(result) {
if (result > 0) {
//Assign return value to DocumentID
DocumentID = result;
alert("This work request has been successfully saved in database. The Document ID is: " + result);
} else {
alert("The Work Request was not saved, there was an issue.");
}
},
complete: function() {
// Hide loading image.
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle error.
alert(errorThrown);
}
});
} else {
alert("Form is not valid");
}
});
The call above works and returns a DocumentID and displays this in an alert with success. The link above works if the id has a hard-coded value; I would just like to make this value dynamic.
if (result > 0) {
//Assign return value to DocumentID
var DocumentID = result;
var href = '#Url.Action("GetReport", new { type = "PDF", id =' + DocumentID +'})';
$("a:contain('Print Report')").attr('href', href);
}
The above suggestions will generate an error for an unsupported pseudo, in this case 'contain' which is not available or known to the anchor tag. There is also an error with the syntax of putting the DocumentID in the Url.Action. I was not able to get this to work, instead I found another error: Too many characters in literal.
Instead give your anchor an id and find that id using jQuery and replace it's href attribute, this is done in the second line of code under Javascript.
html:
<a href="#" **id="Report"**>Print Report</a>
Javascript:
var DocumentID = result; var href = '#Url.Action("GetReport")?type="PDF"&id=' + DocumentID + '';
$("#Report").attr('href', href);
Take note of two things. The URL is formed and the anchor tag is found differently versus previous suggestions.
This has been tested and works for parameters of type string and int, respectively in your callback function to handle getting the report. If you want two strings then add an additional double-quote around the DocumentID like this: id=" ' + DocumentID + ' "';
in your ajax-success handler just set the href of the anchor to whatever you want
var newHref = '#Url.Action("GetReport", new { type = "PDF", id = '+DocumentID +'})';
$('a').attr('href',newHref);

Categories

Resources