$_POST does not pass non-alphanumeric - javascript

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;
});
});

Related

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

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);
});

Need to be able to run an ajax call with element loaded after document.ready()

I've got checkbox inputs on a page and am filtering the results using ajax.
One search option is type and the vendors option updates depending on the type selected. But this means that the change function used to update the actual results no longer works within the document.ready(). To rectify this, I also call the function within .ajaxComplete().
But as an ajax call is being called within the ajaxComplete(), it is causing an infinite loop and crashing the site.
$(document).ready(function(){
$('input[type=radio]').change(function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});
$('#vendor-filter input[type=checkbox]').change(function(){
filterResults(this);
});
});
$(document).ajaxComplete(function(){
$('#vendor-filter input[type=checkbox]').click(function(){
filterResults(this);
});
});
function filterResults($this)
{
var type = $('input[type=radio]:checked').attr("data-id");
var vendor = $($this).attr('data-id');
if($($this).prop('checked'))
{
var action = 'add';
vendors.push(vendor);
}
else
{
var action = 'remove';
var index = vendors.indexOf(vendor);
if(index >= 0)
{
vendors.splice(index, 1);
}
}
$.ajax({
method: 'POST',
url: 'assets/ajax/filter-results.php',
data: {'vendor' : vendor, 'action' : action, 'vendors' : vendors, 'filter_type' : type},
success: function(data)
{
$('#results').empty();
if(action == 'add')
{
window.history.pushState("", "Title", window.location.href+"&v[]="+vendor);
}
else if(action == 'remove')
{
var newUrl = window.location.href.replace("&v[]="+vendor, "");
window.history.replaceState("", "Title", newUrl);
}
$('#results').html(data);
}
});
}
How do I get the .change function to still work after the input checkbox has been called via ajax previously and without causing a loop with .ajaxComplete() ?
Any help would be greatly appreciated.
Thanks
Please try by change function as follow :
$(document.body).on("change",'input[type=radio]',function(){
var type = $(this).attr('data-id');
$.ajax({
method: 'POST',
url: 'assets/ajax/update-filters.php',
data: {type : type},
success: function(data)
{
$('#vendor-filter input[type=checkbox]').prop('checked', false);
vendors = [];
$('#vendor-filter').empty();
$('#vendor-filter').html(data);
}
});

Splitting multiple elements and sending via ajax

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!

onSubmit form - Ajax request to validate the form

I have this scenario where when submiting html form we call javascript method to validate the form. Problem is that validation is done through Ajax request calling php function which returns json array which is empty or contains array with errors.
I am using Ajax request as this newValidation function will be used on all forms on my application so all field ids names and stuff is dynamic same as validation messages.
Console log results are:
Undifiend
It should be True or False.
So it looks like .done run after console.log.
I thought .done is waiting until ajax is finished and only then proceed?
Reason why I am asking I need this .done to run first so it can assing answer variable and only then return boolean to the form. Does this even possible?
UPDATED:
Html form:
<form id="systemManagementSettings" action="#" method="POST" onsubmit="return newValidation('systemManagementSettings')">
JavaScript
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
answer = true;
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
answer = false;
}
});
console.log(answer);
return answer;
}
How do you prevent the form from actually being submitted?
Use event.preventDefault().
UPDATE
Submit the form in the done function.
function newValidation(formId){
var answer;
var $inputs = $('#'+formId+' :input');
var values = {};
$inputs.each(function() {
values[this.id] = $(this).val();
$( "div#"+this.id+"_validation" ).text("");
});
var FinalValidation = $.ajax({
url: "validation/getValidationData",
type: "POST",
data: {form: formId, values: values},
});
FinalValidation.done(function(data){
var resultArray = JSON.parse(data);
if($.isEmptyObject(resultArray))
{
$.ajax({
url: $('#'+formId).attr('action'),
type: "POST",
data: {form: $('#'+formId).serializeArray()},
});
}
else
{
$.each( resultArray, function( key, value ) {
$( "div#"+key+"_validation" ).text(value);
});
}
});
return false; //all the time
}

Categories

Resources