In the sequence of this question, the content I've got in a form is now updating the DB. However, when I click this link
<a onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>
The jQuery .ajax function fires the error callback AND updates the DB with the information as well.
Here's the code
function doUpdate()
{
e.preventDefault();
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error: function(data){
$("#response-update").html("Erro na submissão");
}
});
}
I'd like to get the success callback, in order to display a nice message to the user when it saves the data.
However if I simply do this
Gravar
<script>
$(function(){
$('#commit-changes').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error: function(data){
$("#response-update").html("Erro na submissão");
}
});
});
});
</script>
The "submition" doesn't work at all.
How can I solve this problem? Been stuck with this part for days! :(
EDIT - HTML for the form (This is also a response loaded in the begging of the page)
$response.='<form id="validation" 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 onclick="return doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a><a class="uibutton special" onClick="ResetForm()" title="Limpar Formulário" >Limpar Formulário</a>
</div>
</div>
</fieldset></form>
Have you put your jQuery code inside a document.ready handler?
jQuery(function ($) {
// put jQuery here
});
The first example will work without document.ready (but doesn't make much sense because you're using jQuery anyway). The second won't.
In order to behave doUpdate() function as expected, Try this
modify the anchor tag onclick attribute to
<a onclick="return doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>
and also change the doUpdate function to
function doUpdate()
{
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error: function(data){
$("#response-update").html("Erro na submissão");
}
});
return false;
}
The jquery ajax success/error callbacks will fire based upon whether the POST request was received or not, it has nothing to do with what actually happens within the file you have posted to. It's strange you would get the error callback and have the database updated, but you can try and have the php file you are posting to give a response and then run success/error based upon that response.
In your php file you could have something like this:
$testQuery = "QUERY STRING HERE";
if(!mysql_query($testQuery))
{
echo "error";
exit;
}
else
{
echo "sucess";
exit;
}
And then in your doUpdate function you can run the success callback and output based upon the html
function doUpdate()
{
e.preventDefault();
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
if(data == "success")
{
$("#response-update").html(data);
}
else
{
$("#response-update").html("Erro na submissão");
}
}
});
}
You can also use the "complete" callback which will fire even if the POST was not received, that wont tell you anything other than the function has been ran though
I've got a solution. Not the prettiest, as I wanted a pure jQuery solution, but, it works well.
Just needed to change the
<a onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form">Gravar</a>
To
<input onclick="doUpdate()" href="#" id="commit-changes" class="uibutton submit_form" value="Gravar" />
And now it works with the sucess callback firing.
Thanks for all the help on this.
Related
I want to display text message for success in popup div without refreshing the page
My popup form like this
<div class="modal-content">
<div id="message">Your message has been sent.<br /><br /></div>
<form action="<?php echo $_SERVER['REQUEST_URI'];?>" id="CallBackForm" name="CallBackForm" method="post">
<div class="form-group">
<input id="custmobileNo" name="custmobileNo" type="text" required="required">
<input type="submit" value="call" id="callback" name="callback" class="btn btn-info">
</div>
</form>
</div>
When I click on this link pop up will call
<a href="#" data-toggle="modal" data-target="#call-back">
<input type="submit" value="Call" class="btn-d btn-doctor" >
</a>
CSS:
<style type="text/css">
#message {
display:none;
font-size:15px;
font-weight:bold;
color:#333333;
}
</style>
Ajax Call:
<script>
$("#callback").click(function () {
var custmobileNo = $("#custmobileNo").val();
$.ajax({
url: "<?php echo base_url('Call'); ?>",
type: 'post',
data: {custmobileNo: custmobileNo},
beforeSend: function () {
if (custmobileNo != "") {
$("#message").fadeIn(); //show confirmation message
$("#CallBackForm")[0].reset(); //reset fields
}
}
});
});
</script>
I wrote beforeSend function() with some data either it was standard code or not I don't know. It was calling message fine but it was not closing I want it will close with in some seconds and click on again that button success message validation was showing I want clear that text also.
Try something like this maybe :
$.ajax({
url: "<?php echo base_url('Call'); ?>",
type: 'post',
data: {custmobileNo: custmobileNo},
beforeSend: function () {
if (custmobileNo != "") {
$("#message").fadeIn(); //show confirmation message
$("#CallBackForm")[0].reset(); //reset fields
}
},
success: function() {
setTimeout(function() { //hide message after a certain time
$("#message").fadeout();
}, 5000); // choose after how many time message should hide, here 5s
}
});
But if your Ajax call fail you won't go in the success part so becareful !
You can do the same with complete : function() {...} instead of success : function() {...}, here is some information about Ajax event : https://api.jquery.com/Ajax_Events/
Is it what you are looking for?
sbms.php
<?php
header('Access-Control-Allow-Origin: *');
if(isset($_POST['signup']))
{
$id = $_POST['val'];
echo $id;
}
?>
index.html
<form>
<label class="item-input">
<span class="input-label">ID</span>
<input type="text" id="cid">
</label>
<label class="item-input">
<button class="button button-block button-positive" id="signup">Submit</button>
</label>
</form>
<div class="card">
<div class="item item-text-wrap">
<p id="res"></p>
</div>
</form>
ajax script:-
$(document).ready(function(){
$('#signup').click(function(){
var data = $('#cid').val();
$.ajax({
type : "POST",
data : val,
url : 'http://127.0.0.1/ionic/sbms.php',
crossDomain : true,
success : function (data) {
alert(data);
}
});
});
});
I am just trying to a dummy response from the server but the response I get is totally blank. I am not able to figure out the problem
You're not sending a signup value, you're just sending in an unnamed value so your PHP script is not entering the if condition. Try changing your ajax call to this:
$.ajax({
type : "POST",
data : { val: val, signup: true }
url : 'http://127.0.0.1/ionic/sbms.php',
crossDomain : true,
success : function (data) {
alert(data);
}
});
I am creating simple login screen which will accept username & password on click of submit button.I tried using .click but its not working at all so i am using .live but its passes same parameter twice in request.
$("#loginsubmit").live('click', function (e) {
$.ajax({
url: 'auth_check.php',
data: $(loginForm1).serialize(),
type: 'POST',
cache: false,
success: function (result) {
if (result == 'success') {}
},
error: function (result) {}
});
e.preventDefault();
$.prettyPhoto.close();
return false;
});
This is what i am getting in request
pusername=&ppassword=&pusername=abc&ppassword=abc
I am using jquery first time and there is something called pretty photo used in my template.
I guess this pretty photo might be causing issues.
LoginForm1 looks like as follows :
<div class="login_register_stuff hide"><!-- Login/Register Modal forms - hidded by default to be opened through modal -->
<div id="login_panel">
<div class="inner-container login-panel">
<h3 class="m_title">SIGN IN YOUR ACCOUNT TO HAVE ACCESS TO DIFFERENT FEATURES</h3>
<form name="loginForm1" method="post" enctype="multipart/form-data" />
CREATE ACCOUNT
<input type="text" name="pusername" class="inputbox" placeholder="Username" />
<input type="password" name="ppassword" class="inputbox" placeholder="Password" />
<input type="submit" id="loginsubmit" name="loginsubmit" value="LOG IN" />
</form>
<div class="links">FORGOT YOUR USERNAME? / FORGOT YOUR PASSWORD?</div>
</div>
prettyphoto section snippet
enter <!-- prettyphoto scripts & styles -->
function ppOpen(panel, width){
jQuery.prettyPhoto.close();
setTimeout(function() {
jQuery.fn.prettyPhoto({social_tools: false, deeplinking: false, show_title: false, default_width: width, theme:'pp_kalypso'});
jQuery.prettyPhoto.open(panel);
}, 300);
} // function to open different panel within the panel
jQuery(document).ready(function($) {
jQuery("a[data-rel^='prettyPhoto'], .prettyphoto_link").prettyPhoto({theme:'pp_kalypso',social_tools:false, deeplinking:false});
jQuery("a[rel^='prettyPhoto']").prettyPhoto({theme:'pp_kalypso'});
jQuery("a[data-rel^='prettyPhoto[login_panel]']").prettyPhoto({theme:'pp_kalypso', default_width:800, social_tools:false, deeplinking:false});
jQuery(".prettyPhoto_transparent").click(function(e){
e.preventDefault();
jQuery.fn.prettyPhoto({social_tools: false, deeplinking: false, show_title: false, default_width: 980, theme:'pp_kalypso transparent', opacity: 0.95});
jQuery.prettyPhoto.open($(this).attr('href'),'','');
});
});
here
could you please help me to find out the issue.
This is, because prettyphoto clones your inline content by opening. After opening your inline content, you have to clear the original content - otherwise you've got everything twice - and if you close prettyphoto, you have to put it back there, if its not dynamic generated.
Example:
$.fn.prettyPhoto({
ajaxcallback:function(){
$("#yourhiddenformid").html("");
},
callback:function(){
no need, if its dynamic generated, otherwise:
rewrite html of div;
}
You have to bind onsubmit event on form:
$("#loginForm1").on('submit', function (e) {
$.ajax({
url: 'auth_check.php',
data: $('#loginForm1').serialize(),
type: 'POST',
cache: false,
success: function (result) {
if (result == 'success') {}
},
error: function (result) {}
});
e.preventDefault();
$.prettyPhoto.close();
return false;
});
I'm working on a new website, and i want to learn more about JSON
The website is using jQuery and PHP
I have a jQuery window that gets opend to add a new menu item or submenu item. In this window is also standing a select menu with the added menu and submenu items.
If i have added a new item than it will be added by an ajax request into the database, ofcourse i want to try to avoid window refreshing to see the new added items in the select menu.
The next code is triggering my window and sends the form to a PHP script.
`
var SITE_URL = "http://martin.eenwittekerst.nl/";
$$.ready(function() {
$( "#dialog_add_menu" ).dialog({
autoOpen: false,
modal: true,
width: 900,
open: function(){ $(this).parent().css('overflow', 'visible');
$$.utils.forms.resize() }
}).find('button.submit').click(function(){
var $el = $(this).parents('.ui-dialog-content');
if ($el.validate().form()) {
var filename = SITE_URL+"/admin/requests/menu.php";
$.ajax
({
type: "POST",
url: filename,
data: "do=add&"+$('form#menu').serialize()+"",
success: function(msg)
{
document.getElementById("return_message").innerHTML = msg;
}
});
var filename2 = SITE_URL+"/admin/reloads/menuItems.php";
$.ajax({
type: "GET",
url: filename2,
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
//do your stuff with the JSON data
alert(data);
}
});
$el.find('form')[0].reset();
$el.dialog('close');
}
}).end().find('button.cancel').click(function(){
var $el = $(this).parents('.ui-dialog-content');
$el.find('form')[0].reset();
$el.dialog('close');;
});
$( ".open-add-menu-dialog" ).click(function() {
$( "#dialog_add_menu" ).dialog( "open" );
return false;
});
});
`
This is included a part where i'm testing with JSON, i will put that piece of code here again where i'm trying to do the JSON thing
`
var filename2 = SITE_URL+"/admin/reloads/menuItems.php";
$.ajax({
type: "GET",
url: filename2,
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
//do your stuff with the JSON data
alert(data);
}
});
`
At the end i have an alert that's not giving anny respons, not even an empty alert
Sorry for beeing a noob in this, but this is my first time i'm doing this. I have tested a lot what's standing on the internet without success.
The code in my PHP code is verry simple and only for testing ofcourse
`
include(BASE_DOC."config.php");
include(BASE_DOC."classes/cls.db.php");
// Open the database connection
$cOpenDB = new database_connection;
echo $cOpenDB->db_open(DB_HOST, DB_USER, DB_PASS, DB_TABLE);
$rows= array();
$sql = mysql_query("SELECT * FROM menu_items") or die(mysql_error());
while($data = mysql_fetch_array($sql))
{
$rows[] = $data['id'].",".$data['menu_item_name'];
}
echo json_encode($rows);
?>
`
Now i dont understand how to get the JSON array from my PHP script and how to rebuild the HTML of my select menu
Here i have the code of my HTML of the windowedbox to add a new sub- menu item
`
<!-- Add New Menu Item -->
<div style="display: none;" id="dialog_add_menu" title="Voeg een nieuw menu item toe">
<fieldset id="menu">
<form action="" class="full validate" id="menu">
<div class="row">
<label for="d2_menu_item">
<strong>Menu item naam</strong>
</label>
<div>
<input class="required" type="text" name="menu_name" id="menu_name" />
</div>
</div>
<div class="row">
<label for="d2_menu_item_alt">
<strong>Menu item alt</strong>
</label>
<div>
<input class="required" type="text" name="menu_alt" id="menu_alt" />
</div>
</div>
<div class="row">
<label for="d2_menu_item_sub">
<strong>Wordt dit een submenu item?</strong>
</label>
<div>
<select name="sub_option" id="sub_option">
<option value="n">Nee</option>
<option value="y">Ja</option>
</select>
</div>
</div>
<div class="row" id="showMenuItems">
<label for="d2_select_menu_item">
<strong>Selecteer een Menu item om een submenu item aan te koppelen</strong>
</label>
<div>
<div id="sub_menu_item_of">
<select name="sub_of" id="sub_of">
<option>Kies een menu item om een sub menu item aan te koppelen</option>
<?PHP
$cMenuItems = new menu();
echo $cMenuItems->menuItemsSelect("'menu_item_name','menu_item_alt'", "menu_items");
?>
</select>
</div>
</div>
</div>
</form>
<div class="actions">
<div class="left">
<button class="grey cancel">Annuleren</button>
</div>
<div class="right">
<button class="submit">Voeg menu item toe</button>
</div>
</div>
</fieldset>
</div>
<!-- End if #dialog_add_menu -->
`
For the first time is this a real pain in the ass to do, but if someone can help me with this than i'm forever greatfull to you all!
If you have anny questions or need more information let me know!
Sorry for sometimes my poor english
Kind regards
Martin Meijer
When debugging ajax, you have to make sure
- the ajax request did sent (check you firebug network console)
- the php did return a reponse : log before the return "json_encode($rows);"
- the ajax did got a correct reponse : add a error block in your ajax call :
$.ajax({
...
error: function(response) {
alert(JSON.stringify(response));
}
});
Also check you php.log file.
I'm facing a problem using the FancyBox plugin. I'm trying to submit a form with Ajax and just print a nice little success message, no validation just yet, trying to get it to work. I can submit with jQuery and display the value of any input within the FancyBox. However when I try to execute Ajax it just closes the FancyBox down. I'm not an expert...
The FancyBox's content is generated using Ajax because it requires data from a database.
Here are the important code parts: (Texts are German...)
The file loaded into the FancyBox using Ajax
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
alert('Richtig.');
}
else
{
alert('Falsche Benutzername/Passwort Kombination.');
}
}
});
});
</script>
<div class="login">
<div class="widget_header">
<h4 class="widget_header_title wwIcon i_16_wysiwyg">Benutzer Bearbeiten</h4>
</div>
<div class="widget_contents lgNoPadding">
<form method="post" id="form-edit">
<p id="errormessagehere"></p>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Benutzername</span></div>
<div class="g_9 g_9M">
<input type="text" name="login" id="login" value="<?php echo getusername($_GET['u']) ?>" class="simple_field tooltip" placeholder="Benutzername" autocomplete="off"></div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Passwort</span></div>
<div class="g_9 g_9M">
********
</div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_6">Abschicken
</div>
<div class="clear"></div>
</div>
</form>
</div>
</div>
Here's how I call the Fancy box
$(document).ready(function() {
$(".fancybox").fancybox({
'scrolling' : 'no',
'padding' : 0,
'titleShow' : false
});
});
handleuseredit.php just echoes "ok" to fullfill the data variable requirement.
You can test something like this with the version 2 of fancybox (http://fancyapps.com/fancybox/):
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
$.fancybox( '<h1>Richtig.</h1>' );
}
else
{
$.fancybox( '<h1>Falsche Benutzername/Passwort Kombination.</h1>' );
}
}
});
});
</script>