Ajax passing value to PHP - javascript

I would like to pass multiple values to php via ajax (on same page), here's my code:
HTML (user_list.php):
<button type="submit" class="button button-block savebutton" name="save_changes"/>
Save changes</button>
Javascript (user_list.php):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
PHP (user_list.php):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['delete_selected'])) { // Button to delete selected user(s)
if (!empty($_POST['check_list'])) {
foreach ($_POST['check_list'] as $id) {
$sql = "DELETE FROM users WHERE id=$id";
$mysqli->query($sql);
header("Refresh:0"); //Refresh page
}
}
}
// Other if above works fine
elseif (isset($_POST['result'])){
// I want to get the js array with the values here after ajax
}
else {
// But I get here, and I don't get the js array
}
}
So I have 2 problems, the first is that I pass the elseif, and the second is that I dont get the array. I think the problem is with ajax, since filling the array works properly
EDIT: I moved the php to a different page, now it's working.

Though your Ajax request is initiated, a "normal" submit request is also started, when you press the button. To prevent the second request (thus keeping only the Ajax request), you have to return false; at the end of your onclick callback.
Solution #1:
$(".savebutton").on("click", function () {
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
Solution #2 (as also suggested by #charlietfl):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
});

It seems that when you're submitting the POST request, the data is coming as their own POST fields. Simply check for the values of what you submitted. For example, if you had done the same, but put foo as bar and hello as world, you could check for foo and hello with something like this:
elseif (isset($_POST['foo'], $_POST['hello']) {
# your code
}

$('.savebutton').click(function (e) {
e.preventDefault()
var js = []
var i = 0
$('select').each(function (i) {
var a = {}
a.id = $(this).val()
a.permission = $(this).children(':selected').text()
js.push(a)
alert(js[i].permission + ' - ' + js[i].id)
})
js = JSON.stringify(js)
$.post('user_list.php', {result: js}
})

Try with this
<button type="submit" class="button button-block savebutton" name="save_changes[]"/>Save changes</button>

Related

Is it correct my ajax call and jQuery PHP for submit button only?

I'm using Kendo grid that has treeview with checkboxes. So, here I want to do POST using AJAX call to get the id of selected checkboxes. Is there any correction on this code? Because there is no function for submit button.
AJAX call for submit button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
$.ajax({
type: "POST",
url: "getTest.php",
//data: { name: "John" }
data: function () {
return {
method: "getTemplate",
// employeeID: "<?php echo $_SESSION['employeeID'];?>",
// propertyID: "<?php echo $_SESSION['propertyID'];?>",
}
},
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
}
jQuery PHP
function getTemplate() {
global $ehorsObj;
$positionTemplateID = (isset($_POST['positionTemplateID']) ? $_POST['positionTemplateID'] : '');
$hrsPositionID = (isset($_POST['hrsPositionID']) ? $_POST['hrsPositionID'] : '');
$programID = (isset($_POST['programID']) ? $_POST['programID'] : '');
$propertyID = (isset($_POST['propertyID']) ? $_POST['propertyID'] : '');
$employeeID = (isset($_POST['employeeID']));
If they are using : If isset $_POST ,
I'm a little bit confused here. Is there any solution on this?
Demo Here
Your demo link has checkedNodeIds function. This function holds checked nodes in a multidimensional array like
nodes[i].moduleID
nodes[i].groupID
nodes[i].programID
So return this array from this function and pass it as ajax data. Then process it in your PHP back-end.
function checkedNodeIds(nodes, checkedNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
//checkedNodes.push(nodes[i].moduleID);
// checkedNodes.push(nodes[i].groupID);
checkedNodes.push(nodes[i].programID);
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes);
}
}
}

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

JQuery Ajax returns Source code

I'm using JQuery Ajax on my website. I've tested it on our test server it worked perfectly, but when I tried to put it on our productive server the Ajax just returns the source code of the website itself.
JS File:
$(document).ready(function () {
$('#sshin').keyup(function () {
var query = $(this).val();
console.log(query);
if (query != '') {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function (data) {
console.log(data);
}
});
}
});
$(document).on('click', 'article', function () {
var text = $('#sshin').val();
text = text.substring(0, text.lastIndexOf(',') + 1);
text += $(this).text();
var uniq = text.match(/\b\w+\b/g).filter(function (el, idx, a) {
return idx === a.lastIndexOf(el);
});
text = uniq.join(',');
$('#sshin').val(text);
$('#sshout').fadeOut();
});
});
PHP File:
<?php
if(isset($_POST["query"])){
$query = $_POST["query"];
return '<ul><li>1</li><li>2</li></ul>';
}
?>
Any idea why it returns something different than it should?
This method once worked for me, hope it might help. Let me know.
this->output->set_content_type('application/json');
return $this->output->set_output(json_encode('<ul><li>1</li><li>2</li></ul>'));

On key up Ajax function for checking if name exist returns multiple identical values despite using codeigniter active record distinct query

I have utilized on key up function with ajax to check in my database if the course name already exist. A prompt then will be showed to the user after a match is found. I have used the distinct query in my model and then the controller returns the right value to the ajax however the returned value were duplicated or even multiple values are returned causing the pop up message in my page to show multiple times also. What is wrong with this? Thanks for the help.Here are my codes
View (Javascript):
<script>
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData={
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>courses/check_course_name_existince",
dataType:'json',
data: postData,
success: function(data)
{
if(data.msg == 'Exist')
{
console.log(data.msg);
$("#alert_exist").fadeIn(100);
$("#alert_exist").delay(3000).fadeOut(1000);
var a = 0;
$("input[type=radio][value=" + a + "]").attr("disabled",true);
document.getElementById('course_desc').disabled=true;
document.getElementById('userfile').disabled=true;
document.getElementById('is_public').disabled=true;
document.getElementById('submit').disabled=true;
}
else
{
console.log(data.msg);
var a = 0;
$("input[type=radio][value=" + a + "]").attr("disabled",false);
document.getElementById('course_desc').disabled=false;
document.getElementById('userfile').disabled=false;
document.getElementById('is_public').disabled=false;
document.getElementById('submit').disabled=false;
}
}
});
</script>
Controller:
function check_course_name_existince()
{
$course_name = $this->input->post('course_name');
$session_id = $this->session->userdata('username');
$result = $this->
course_booking_model->check_course_name_exist($session_id,$course_name);
if($result)
{
$msg="Exist";
}
else
{
$msg="Available";
}
echo json_encode(array('msg'=>$msg));
}
Model:
function check_course_name_exist($tennant_id,$course_name)
{
$where = array(
'tennant_id' => $tennant_id,
'course_name' => $course_name
);
$this->db->distinct();
$this->db->select('course_name');
$this->db->where($where);
$this->db->group_by('course_name');
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
Image Output:
The console log function returns 2 identical values resulting to 2 message pop up.
Try adding some checks before setting a new timeout to prevent multiple triggers to your ajax call
var typingTimer = null;
var doneTypingInterval = 3000;
$('#course_name').keyup(function () {
if (!typingTimer) {
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
}
});
$('#course_name').keydown(function () {
if (typingTimer) {
clearTimeout(typingTimer);
typingTimer = null;
}
});

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

Categories

Resources