I've got this form that updates user information on db. However, this functionality is not working with ajax (works with a simple submit with refresh).
This postes form serialized data to the server
jQuery
$('#commit-changes').click(function(){
$('#validation').submit(function(){
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error:function(){
alert("ERROR");
}
});
});
});
Here's the HTML that outputs the markup
HTML
$rcs_roles = $user->getRoles();
$role ='';
foreach($rcs_roles as $roles)
{
if($roles->role_number == $rcs_user->permissao)
$role .= '<option value="'.$roles->role_number.'" selected="selected">'.$roles->role.'</option>';
else
$role.= '<option value="'.$roles->role_number.'">'.$roles->role.'</option>';
}
if($rcs_user->activo == 0)
{
$activo = '<input type="checkbox" name="activo" class="on_off_checkbox" value="1" />';
}
else
{
$activo = '<input type="checkbox" name="activo" class="on_off_checkbox" checked="checked" value="1" />';
}
$response = '';
$response.='<form id="validation" action="" method="post">
<fieldset >
<input type="hidden" name="user_id"
value="'.$_POST['user_id'].'"/>
<legend>Actualizar Dados Utilizador</legend>
<div class="section ">
<label>Nome<small>Insira o seu nome</small></label>
<div>
<input type="text" class="validate[required,custom[onlyLetterSp]] large" name="nome" id="f_required" value="'.utf8_encode($rcs_user->nome).'">
</div>
</div>';
$response.='<div class="section ">
<label> Email<small>Insira o seu email</small></label>
<div>
<input type="text" class="validate[required,custom[email]] large" name="email" id="e_required" value="'. utf8_encode($rcs_user->email).'">
</div>
</div>';
$response.= '<div class="section">
<label>Permissões<small>Seleccione o tipo de utilizador </small></label>
<div>
<select class="medium" name="role">
'.$role.'
</select>
</div>
</div>
<div class="section">
<label>Activo<small>Activar utilizador</small></label>
<div>
'.$activo.'
<span class="f_help">ON / OFF </span>
</div>
</div>
<div class="section last">
<div>
<a id="commit-changes" class="uibutton submit_form" name="submit" >Gravar</a><a class="uibutton special" onClick="ResetForm()" title="Limpar Formulário" >Limpar Formulário</a>
</div>
</div>
</fieldset></form>';
And then the server side processing
PHP
$response='';
$id_user = $_POST['user_id'];
$name = utf8_encode($_POST['nome']);
$email = utf8_encode($_POST['email']);
$permitions = $_POST['role'];
if(!isset($_POST['activo']))
{
$active = 0;
}
else
{
$active = 1;
}
$user = new Users();
try
{
$user->updateUsers($name, $email, $permitions, $active, $id_user);
$response = "SUCESSO";
}
catch (Exception $e)
{
$response = "ERRO".$e->getMessage();
}
echo $response;
Glad for all the help I can get
From an initial glance, it looks like you aren't waiting until the document has loaded before binding an event handler. This means that #commit-changes doesn't even exist when you try to add the .click event handler.
To fix this in jQuery, wrap this around your entire code:
$(document).ready(function(){
// do stuff
});
This function sends a callback to jQuery's document.ready handler, so that all the code only executes once the page is loaded.
Remove the .submit() function. something like this.
$.post("modules/user/updateuser.php",{data:$("#validation").serialize()},function(response){
$("#response-update").html(response);
});
on the php side try to print_r($_POST['data']); and please post the output.
In the updateUsers function (in Users class) you try to update the field nome or name ?
You are suppose to use nome only right?
Related
I have a custom dropdown. Want to change the value of the button as selected option of dropdown
list.
This is my view code. I tried with jquery but unsuccessfull.
Please some one help me with jquery
<div class="col-md-5 col-sm-6">
<div class="form-group droplist">
<label for="project_category">project Categary</label><br/>
<input type="button" class="form-control" id="relig" value="<?php if(isset($projectDetails->project_category) && !empty($projectDetails->project_category)){
echo #$projectDetails->project_category;
}else{
echo "select Category";
}?>">
<div id="religions" class="dropdownmenu" style="display:none;padding-left:17px">
<?php foreach($categories as $cat){ ?>
<div id="<?php echo $cat['code'] ?>" class="maincategory">
<label><input type="radio" class="category" name="project_category" id="category" value="<?php echo $cat['code'] ?>"> <?php echo $cat['Project_classification_id']." - ".$cat['Description'] ?></label><br/>
</div>
<?php } ?>
</div>
</div>
</div>
I have above 140 dropdown values for that i used foreach, notonly 3 values
This is my jquery. I done all thing but unable to show the checked radio value as button value(title)
$('#relig').click(function(){
$('#religions').slideToggle("fast");
});
traversed_ids = [];
$(document).on('change','.project_category',function() {
maincat = $(".project_category:checked").val();
if ($.inArray(maincat, traversed_ids) < 0) { //check element exist in array or not
traversed_ids.push(maincat); //add element to array
changeCategoryList(maincat); //call ajax
}
});
function changeCategoryList(maincategory){
$.ajax({
url: '<?php echo site_url("abcd/xyz"); ?>',
type: 'POST',
data: { maincategory:maincategory },
dataType: 'json',
success: function(data) {
$.each(data, function(key, value) {
var MoreTag='';
MoreTag += '<div id="'+value.code+'" Style="padding-left:20px" class="subcategory">';
MoreTag += '<label ><input type="radio" class="project_category" name="project_category" id="project_category" value="'+value.code+'"> '+value.Project_classification_id+' - '+value.Description+'</label><br/>';
MoreTag += '</div>';
$("#"+maincategory).append(MoreTag);
});
}
});
}
$(".maincategory").click(function (e) {
e.stopPropagation(); //to stop event bubbling
if ($(this).children('.subcategory').is(':checked')) { //check if hidden or not
$(this).children('.subcategory').hide(); //if yes hide
} else {
$('.maincategory').children('.subcategory').hide();
$(this).children('.subcategory').show(); // else show
}
});
I have made sample example as per my understanding from your question.
Please check below example.
$(document).on('change','input[name="rgroup"]',function() {
radio = $("input[name='rgroup']:checked").val();
$("#btn").val(radio);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="rgroup" value="test1">Test1
<input type="radio" name="rgroup" value="test2">Test2
<input type="radio" name="rgroup" value="test3">Test3
<input type="radio" name="rgroup" value="test4">Test4
<br>
<input type="button" id="btn" value="Change">
I want to post three element to backend use ajax.
There are input type name is "suppid" checkbox array name is "lang[]" and select type name is "guide".
All three are successfully post to the backend use ajax. But I wrote a function before to detect if the post is null, and it failed to detect checkbox,no matter what I try I fail to detect checkbox array and only when write this I can check both three successfully.
function check()
{
//$vali1=checknullnew($_POST); I can not use this function
//if($vali1['vali']=='Y') if I use this no matter checkbox
//are clicked or not it will be successfully uploaded.
if(isset($_POST['lang']) && isset($_POST['suppid']) &&isset($_POST['guide']))
//I can only use this to successful detect three post are null or not
{
$result['vali']='Y';
$result['message']='successfully uploaded';
$result['redirect_url']='test4.html';
return $result;
}
else
{
$result['vali']='N';
$result['message']='no';
return $result;
}
}
$response=check();
echo json_encode($response);
//My html form is like this
<form role="form" id="myform" >
<div class="form-group">
<label>
suppid
</label>
<input type="text" class="form-control" name="suppid" style="width: 120px;">
</div>
<div class="form-group">
<label >
lang
</label>
<label class="checkbox-inline"><input type="checkbox" name="lang[]" value="en">English</label>
<label class="checkbox-inline"><input type="checkbox" name="lang[]" value="zh-CN">Chinese</label>
<label class="checkbox-inline"><input type="checkbox" name="lang[]" value="zh-TW">Cantonese</label>
<label class="checkbox-inline"><input type="checkbox" name="lang[]" value="jp">Japanese</label>
<label class="checkbox-inline"><input type="checkbox" name="lang[]" value="kr">Korean</label>
</div>
<div class="form-group">
<label>
guide
</label>
<select class="form-control" name="guide" style="width: 120px;">
<option value="Y">yes</option>
<option value="N" selected>no</option>
</select>
</div>
<input name="submit" type="button" class="btn btn-default" id="button1" value="上传">
</form>
//My javascript is
<script>
$(document).ready(function() {
$('input[name=submit]').on('click',function(){
var suppid = $('input[name=suppid]').val().trim();
var lang = new Array;
$("input[name='lang[]']:checked").each(function() {
lang.push($(this).val().trim());
});
var guide = $('select[name=guide]').val().trim();
//alert('ok');
$.ajax({
type: "POST",
url: "test4.php",
data: {
suppid:suppid,
lang:lang,
guide:guide
},
dataType: "json", //send it along with your call
success: function( data )
{
if( data.vali == 'N' )
{
alert(data.message);
}
else {
alert(data.message);
window.location.href = data.redirect_url;
}
}
});
});
});
</script>
//My detect null function is like this
function checknullnew($check)
{
$valid=0;
foreach($check as $key => $value)
{
if($key=='lang')
{
if(!issset($value)){$valid=1;}
}
else
{
if(trim($value)=="")
{
$valid=1;
}
}
}
if($valid==0)
{
$result['vali']='Y';
return $result;
}
else{
$result['vali']='N';
$result['message']='Please input complete messages';
return $result;
}
}
//also I try this function too
//I use isArray() to detect the checkbox array and use isset()to detect if the //array is null or not.
I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>
I have an jquery ajax call where I add a new comment to a database. It saves just fine but when i want to reaload the div where the comments are shown, I always get an additional div which I do not want. When I reaload the page everything is just fine and displayed as wanted!
The script:
<script>
$("#addcmt").click(function() {
var UserID = $("#UserID").val();
var ClassID = $("#ClassID").val();
var text = $("#appendedInputButton").val();
var option;
if($("#option").is(':checked')) {
option = 3;
} else {
option = 1;
}
$.ajax({
type: "GET",
url: "/comment/functions/add_class_comment.php",
data: "text=" + text + "&UserID=" + UserID + "&ClassID=" + ClassID + "&option=" + option,
success: function(msg) {
$("#CommentList").load(location.href+' #CommentList');
$('#appendedInputButton').val("");
$('.criticalcomment').attr('checked', false);
}
});
});
</script>
The php+html where they comments are shown:
<div class="bs-docs-example" id="message">
<div id="CommentList">
<?php
for ($i=0; $i<$l; $i++) {
switch($commentarr[$i]->getOption()) {
case 1:
$option="alert-success";
break;
case 2:
$option="alert-info";
break;
case 3:
$option="alert-error";
}
echo '<div class="Comments alert '.$option.'"><div class="CommentsName">'.$userarr[$i]->getFirstname().' '.$userarr[$i]->getLastname().'</div>';
echo '<div class="CommentsDate">'.renderDate($commentarr[$i]->getDate()).'</div><div class="CommentsText">'.$commentarr[$i]->getText().'</div>';
if ($deletebutton == 1) {
echo '<div class="deleteButtonAdmin"><input type="button" class="btn btn-small btn-primary delcmt" value="Löschen" name="'.$commentarr[$i]->getID().'"></div>';
}
echo '</div>';
}
?>
</div>
<form class="Comments postmessage">
<div class="input-append" style="margin-top: 10px;">
<input type="hidden" name="ClassID" id="ClassID" value="<?php echo $c->getID(); ?>">
<input type="hidden" name="UserID" id="UserID" value="<?php echo $u->getID(); ?>">
<textarea class="span12" name="text" id="appendedInputButton" type="text"></textarea>
<label for="option">Kritisch?</label><input type="checkbox" id="option" class="criticalcomment" name="option" value="1">
<input type="button" class="btn" id="addcmt" value="Post">
</div>
</form>
</div>
I hope someone got an idea or hint for me!
Well, $("#CommentList").load(location.href+' #CommentList'); tells jQuery to replace the contents of #CommentList with #CommentList, so you get two nested #CommentLists, correct?
You might have to do $("#CommentList").remove().load(location.href+' #CommentList'). If that does not work, try introducing a temporary div:
$("<div />").load(location.href+' #CommentList', function (div) {
$('#CommentList').replaceWith($(div));
})
try adding this after loading the div!
$("#CommentList").find('div').unwrap(); or
$("#CommentList").find('#CommentList').unwrap();//I am doubtful about this
jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.