Updating selection menu after fresh input into database (JSON) - php

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.

Related

How to grab data and auto fill a form on change event using Ajax

What I need
I need when someone change my calendar, a php script should run in background and fetch some data and show it in the form fields accordingly. To do that, I have the following HTML code and Ajax script
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
$('#normalShiftOperator').val(result["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(result["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(result["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
<div class="form-group">
<div class="row">
<div class="col-sm text-center" id="normalShiftOaDiv" class="">
<label for="currentOa">Current OA?</label><br>
<input type="radio" name="currentOa" id="normalShiftOa" value="normalShiftOa">
</div>
<div class="col-sm" id="normalShiftOperatorNameDiv">
<label for="normalShiftOperator">Normal Shift</label>
<select class="form-control" id="normalShiftOperator" name="normalShiftOperator">
<option></option>
<option>A</option>
<option>B</option>
</select>
</div>
<div class="col-sm" id="normalShiftOperatorDurationDiv">
<label for="normalShiftOperatorDuration">Duration</label>
<select class="form-control" id="normalShiftOperatorDuration" name="normalShiftOperatorDuration">
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
<div class="col-sm">
<label for="normalShiftPinCount">Pin Count</label>
<input type="number" class="form-control" id="normalShiftPinCount" name="normalShiftPinCount" value="23">
</div>
<div class="col-sm">
<label for="normalShiftDate">Date</label>
<input type="date" class="form-control" id="normalShiftDate" name="normalShiftDate">
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" style="margin-top: 30px;" id="normalShiftUpdate" name="normalShiftUpdate">Update</button>
</div>
</div>
</div>
I want to show the php variables $normalShiftOa, $normalShiftOperatorDuration and $normalShiftPinCount in the form fields with id normalShiftOperator, normalShiftOperatorDuration, normalShiftPinCount respectively when someone change calendar. Please see the contents of supervisorEditAjax.php. How can I show these three variables into the three id fields?
I only know how to show to one single field. But if there are multiple values to be shown in multiple fields, how can we do that?
Can someone please help?
Edit 1
Contents of supervisorEditAjax.php
<?php
$normalShiftOa = "A";
$normalShiftOperatorDuration = "2";
$normalShiftPinCount = "100";
$arr = array('normalShiftOa' => $normalShiftOa, 'normalShiftOperatorDuration' => $normalShiftOperatorDuration, 'normalShiftPinCount' => $normalShiftPinCount);
echo json_encode($arr);?>
I tried to use some Json method. But it is not working
After many trial and error, I am able to show it in the respective form fields. The issue was at the Ajax part. Basically I need to parse the Json object in order to get the specific values. Replace the AJAX code as below and it works fine
< script >
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
var returnedData = JSON.parse(result); //This is the change done to the code
$('#normalShiftOperator').val(returnedData["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(returnedData["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(returnedData["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
</script>
Please read more about JSON.parse here

Insert data into mysql database using ajax in php multiform

Hey I am trying to insert into mysql/php/ajax with multiforms on a page.
The insert works fine, but form nr 2, sets form nr 1´s data into the mysql DB.
I have 4 forms on each page, it is a firecheck on a dorm, where I need to check 28 kitchens if they keep the standard firerules.
so what I need is the little goldcorn to make this work :) so each form, only respond on the data in that form.
Here is my code:
<div class="content">
<a class="hide" id="1a" name="1a">1A</a><br>
<form action="" id="1a" method="" name="1a" novalidate="novalidate">
<div class="wrapper">
<div class="table">
<br>
<br>
<div class="row header">
<div class="cell">
1A
</div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Døre
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="door" name="door" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Skilte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="skilt" name="skilt" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Nødlys
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="lys" name="lys" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandtæppe
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_t" name="b_t" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandspørjte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_s" name="b_s" rows="3">Ok</textarea>
</div>
</div>
</div>
<input id="dato" name="dato" type="hidden" value="<?php echo date(">") ?> <!--class = "btn btn-success btn-block" -->/>
<button class = "send" id = "insert-data1a" name = "insert-data1a" onclick = "insertData1a()" type = "button">Insert Data</button><br>
<p id = "message1a"></p>
</div><!--end wrapper -->
</form>
</div><!--end content -->
<script type = "text/javascript">
function insertData1a() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1a.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1a").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
the next form, looks the same, but new insert-data name and form name.
Insert Data
<script type="text/javascript">
function insertData1b() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1b.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1b").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
<?php
include('db.php');
$door=$_POST['door'];
$skilt=$_POST['skilt'];
$lys=$_POST['lys'];
$b_t=$_POST['b_t'];
$b_s=$_POST['b_s'];
$dato=$_POST['dato'];
$stmt = $DBcon->prepare("INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
$stmt->bindparam(':door', $door);
$stmt->bindparam(':skilt', $skilt);
$stmt->bindparam(':lys', $lys);
$stmt->bindparam(':b_t', $b_t);
$stmt->bindparam(':b_s', $b_s);
$stmt->bindparam(':dato', $dato);
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
the one for b, looks almost the same
$stmt = $DBcon->prepare("INSERT INTO 1_b(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
In addition to Bakayaro's answer, if all your forms got the same fields, you can optimize your code to use only one javascript function and one PHP insert script.
Factorise your code ! Rembember one thing : DRY (Don't Repeat Yourself)
HTML
Add a click listener on each .send button instead of using onclick() on them
Add specific ID on each different form, with kitchen ID
Add data to .send button with related form's kitchen ID
Example for kitchen 1A:
<!-- Add specific ID with kitchen ID -->
<form action="" id="kitchen1a" method="" name="1a" novalidate="novalidate">
...
<!-- Add data to each .send button with related form's kitchen and remove onclick() -->
<!-- data-kitchen="1a" -->
<button class = "send" id = "insert-data1a" name = "insert-data1a" data-kitchen="1a" type = "button">Insert Data</button>
Don't use same ID on different HTML elements, as your a and form tag.
Javascript
Use click listener
Get active form's data from each field's name
Working example based on your code:
$('.send').on('click', function(e) {
var kitchen = $(this).data('kitchen');
var form = $('#kitchen' + kitchen);
var data = {
door: form.find('[name="door"]').val(),
skilt: form.find('[name="skilt"]').val(),
lys: form.find('[name="lys"]').val(),
b_t: form.find('[name="b_t"]').val(),
b_s: form.find('[name="b_s"]').val(),
dato: form.find('[name="dato"]').val(),
// add active kitchen in your POST data
kitchen: kitchen,
};
// AJAX code to send data to php file.
$.ajax({
type: "POST",
// use same PHP script for each forms
url: "insert.php",
data: data,
dataType: "JSON",
success: function (data) {
// use kitchen's specific message tag
$("#message" + kitchen).html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
// alert(err);
console.log(err);
}
});
});
PHP file
Use one single PHP script for each form and generate table name in your SQL query from given kitchen value.
Working example based on your code:
$kitchen = $_POST['kitchen'];
// if your kitchens are all formatted like this : 1a, 2c, 14a, ...
preg_match('/(\d)+([a-z])/', $kitchen, $matches);
$stmt = $DBcon->prepare("INSERT INTO " . $matches[1] . '_' . $matches[2] . "(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
Generated query for your 1a form:
INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato) VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)
If I do understand well, you have multiple forms on one page and the second form posts the values of the first form.
I think the problem is that you're using tha same ids on the fields of the forms.
Take a look at:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
These are the fields from insertData1a() function and it's the same in the other function:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
So basically the problem is that you're referencing the same fields in the second function.
The id attribute must be a unique id for an HTML element, so you should use different ids in each form or if you're already using different ids (you didn't post the html of the second form) you just have to rewrite the elements in your second function.

execute jquery .submit AFTER ajax success return new form

I believe my problem has something to do with the fact that my first form RETURNS a new form via ajax success .html(result) AFTER DOM has executed. My jquery within DOM isn't being recognized because elements aren't visible until after the submit of first form. HOW to get my $("#fullFormMA").on(submit,(function(e){ to execute is eluding me. Here is my html
<?php
session_start();
require_once('functions.php');
include('header.htm');?>
<title>Membership Application</title>
<meta name="description" content="">
</head>
<body>
<div id="container">
<div id="loginBanner">
<?php include ("loginMenu.php"); ?>
<?php include ("bannerIcons.php"); ?>
</div> <!--end loginBanner-->
<div id="header" class="clear">
</div> <!--end header-->
<div id="content"><div class="content">
<div id="colLt">
<?php include('tabContent.php');?>
<?php include('leftSidebar.php');?>
</div>
<div id="colRt"><div class="content">
<h1>New Member Application</h1>
<ul><li>submitting an application</li><li>submitting payment</li></ul><h6>Step #1—the application</h6>Please enter an email which will ultimately be used as your website username. This email will remain as your private email.</p><br><br>
<form method="post" name="checkUserMA" id="checkUserMA">
<label class="clear" style="width:120px">Username/Email<br><span class="small"></span></label>
<input type="text" name="usernameMA" id="usernameMA" class="green" style="width:300px;"/><br><br>
<input type="submit" id="checkUserMA" class="submit" value="Submit" />
</form>
<div class="clear"></div>
<div id="errorMA" style="background:yellow;width:200px;height:100px"></div>
<div id="resultMA"></div>
</div></div>
<div class="clear"></div>
</div></div><!--end content-->
<div id="footer">
<?php include("footer.htm") ?>
<!--<?php include("disclaimer.htm") ?>-->
</div><!--end footer-->
<div class="clear"></div>
</div><!--end container-->
<div class="clear"></div>
</body>
</html>
Here is my jquery:
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
});//end dom
Here is checkMA.php...
<?php
session_start();
include('functions.php');
connect();
$username = urldecode(protect($_POST['usernameMA']));
$_SESSION['guestUser'] = $username;
$sql2 = mysql_query("SELECT username FROM members WHERE username = '$username'");
$checkNumRows = mysql_num_rows($sql2);
if (!$username){
echo "<p class='red'>Enter an email to be used as your username...</p>";
} else if ($checkNumRows == 1){
echo "<span style='font-weight:bold'>The username: ".$username." is already in use.</span>";
} else if ($checkNumRows == 0){
echo "<hr><p class='green'>This username is available.</p><p>Please continue with the registration process...</p><br>";?>
<form method="post" name="fullFormMA" action="memberAppProcess.php">
<h6>Public Information - this information will be displayed to website visitors</h6>
<label class="clear" style="width:75px">Name</label>
<label class="error" id="name_error">This field is required.</label>
<input type="text" name="firstName" id="firstName" class="left inputCheck" style="width:150px" placeholder="first name"/>
<input type="text" name="lastName" id="lastName" class="inputCheck" style="margin-left:10px" placeholder="last name"/><br><br>
<input type="submit" name="fullFormMA" id="fullFormMA" class='submit right' onClick='submitFullForm();' value="Submit application">
</form>
<?php
}?>
My #checkUserMA works but my #fullFormMA doesn't work. I would love to understand why (DOM already loaded?) and how I might fix my code to allow for a form added "after the fact" via ajax .html(result). Thank you.
The DOM is ready before your ajax success so you can write this JQuery full code
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
RunAfterAjax();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
function RunAfterAjax(){
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
}
});//end dom
It's executing, you just aren't waiting long enough for it to exist. Move the event binding for the new form to the line right after you add the new form to the document.
$("#resultMA").html(result).fadeIn();
$("#fullFormMA").on(submit,(function(e){...
$("#fullFormMA").on(submit,(function(e){ /* ... */ });
fullFormMA is an <input>, you should bind click instead of submit, and use quotes around the event name.
When you use $('#something').on('event', ...), it only works if the #something element already exists.
You could fix your code by delegating the listener to an upper existing element :
$('#content').on('click', '#fullFormMA', function() { /* ... */ });
This code will detect the click event on #fullFormMA event if it is added after an ajax response.

How to get Ajax to execute within an Ajax generated FancyBox?

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>

jQuery ajax fails on form submit with link

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.

Categories