We are trying to send multiple associative array values from javascript/ajax to php but we receive an empty object/array at the php file.
So can you please help to get values of an associative array from javascript to php?
We have tried serializing array and passing to a php file.
We have tried to convert an array to string and then try to pass it to a php file.
Please check the following code:
// javscript
function saveData(id) {
//var actionData = [];
var actionData = $('#' + id).closest('tr').find("[id^='action_']");
var ownerData = $('#' + id).closest('tr').find("[id^='owner_']");
//var type = $.type(actionData);
//alert(type); exit();
/*alert(actionData[0]['action']);exit;
actionData['owner'] = $('#' + id).closest('tr').find("[id^='owner_']");
actionData[2]['dueDate'] = $('#' + id).closest('tr').find("[id^='dueDate_']");
actionData[3]['completedDate'] = $('#' + id).closest('tr').find("[id^='completedDate_']");
//var myData = JSON.stringify(actionData['owner']);
//alert($('#' + id).closest('tr').find('#projId').val());*/
var dataObject = [];
dataObject['projId'] = $('#' + id).closest('tr').find('#projId').val();
//alert(myData);
//var newData1 = $.extend({}, actionData['owner']);
var newData = $.extend({}, dataObject);
/*dataObject = {
projId: $('#' + id).closest('tr').find('#projId').val(),
riskNumber: $('#' + id).closest('tr').children('td#riskNumber').text().slice(0,-4),
cause: $('#' + id).closest('tr').find('#cause').val(),
effect: $('#' + id).closest('tr').find('#effect').val(),
functionAffectedControl: $('#' + id).closest('tr').find('#functionAffectedControl :selected').val(),
categoryControl: $('#' + id).closest('tr').find('#categoryControl :selected').val(),
impact: $('#' + id).closest('tr').find('#impact :selected').val(),
severityControls: $('#' + id).closest('tr').find('#severityControls').val(),
probability: $('#' + id).closest('tr').find('#probability :selected').val(),
riskOwnerControl: $('#' + id).closest('tr').find('#riskOwnerControl :selected').val(),
manageability: $('#' + id).closest('tr').find('#manageability :selected').val(),
residualProbability: $('#' + id).closest('tr').find('#residualProbability :selected').val(),
residualImpact: $('#' + id).closest('tr').find('#residualImpact :selected').val(),
statusControl: $('#' + id).closest('tr').find('#statusControl :selected').val()
//actions: JSON.stringify(actionArray)
//owners: $('#' + id).closest('tr').find("[id^='owner_']").val(),
//dueDates: $('#' + id).closest('tr').find("[id^='dueDate_']"),
//CompletedDates: $('#' + id).closest('tr').find("[id^='completedDate_']")
}*/
$.ajax({
type: "POST",
url: "/apps/projmgmt/reports/SaveData.php",
data: { data: actionData, owner:ownerData}, //
dataType: 'json',
success: function(response) {
console.log(response);
alert('Data Saved Successfully');
}
});
}
// html
<table class="table table-bordered table-striped tree-basic">
<tbody>
{foreach from=$obj->getRiskActionList() name=risk item=risk}
<tr class="{$class}" data-count="2" id="{$k}">
{$i = $i+1}
{$class='treegrid-'|cat:$i}
{$j = $i-1}
{$classNode='treegrid-parent-'|cat:$j}
<td style="font-weight: bold;">
<div class="treegrid-container">
<span class="treegrid-expander treegrid-expander-collapsed"></span>
{'ACTION'|gettext|escape}</div>
</td>
<td colspan="6" >
<input type="hidden" name="actionId[]" id="actionId_{$k}" value="{$risk->getId()|escape}" />
<div class="treegrid-container">
<span class="treegrid-expander"></span>
<textarea rows="2" cols="100" id="action_{$k}" name="mitigationAction[]" maxlength="256">{$risk->getMitigationAction()|escape}</textarea></div>
</td>
</tr>
<tr class="{$class} {$classNode}">
{$i = $i+1}
{$class='treegrid-'|cat:$i}
<td style="font-weight: bold;" >
<div class="treegrid-container">
<span class="treegrid-expander"></span>{'OWNER_NAME'|gettext|escape}</div></td>
<td>
<input type="text" name="actionOwner[]" size="50" id="owner_{$k}" value="{$risk->getOwnerName()|escape}" maxlength="80"/>
</td>
<td style="font-weight: bold; text-align: center;" >{'DUE_DATE'|gettext|escape}</td>
<td>
<input type="hidden" class="riskPopupCalendar" id="actionDueDate_{$i}" name="actionDueDate[]" value="{$smarty.request.actionDueDate[$i]|escape}">
<div size="10" name="actionDueDateText[]" id="dueDate_{$k}">{if null != {$risk->getDueDate()|escape}}{$risk->getDueDate()->format('d/m/Y')|escape}{/if}</div>
<img src="/images/calendar.gif" id="actionDueDateDatepicker_{$i}" style="width:16px;height:16px;">
<a href="#"><img src="/images/calendar_delete.gif" class="riskPopupCalendarDelete" style="width:16px;height:16px;"
data-input="actionDueDate_{$i}" data-text="actionDueDateText_{$i}" id="actionDueDateDelete_{$i}"></a>
</td>
<td style="font-weight: bold; text-align: center;" >{'COMPLETED_DATE'|gettext|escape}</td>
<td>
<input type="hidden" class="riskPopupCalendar" id="actionCompletedDate_{$i}" name="actionCompletedDate[]" value="{$smarty.request.actionCompletedDate[$i]|escape}">
<div size="10" name="actionCompletedDateText[]" id="completedDate_{$k}>{if null != {$risk->getCompletedDate()|escape}}{$risk->getCompletedDate()->format('d/m/Y')|escape}{/if}</div>
<img src="/images/calendar.gif" id="actionCompletedDateDatepicker_{$i}" style="width:16px;height:16px;">
<a href="#"><img src="/images/calendar_delete.gif" class="riskPopupCalendarDelete" style="width:16px;height:16px;"
data-input="actionCompletedDate_{$i}" data-text="actionCompletedDateText_{$i}" id="actionCompletedDateDelete_{$i}"></a>
</td>
</tr>
<tr class="{$class} {$classNode}">
<div class="treegrid-container">
<span class="treegrid-expander"></span>
<td data-column="name"><img src="/images/blank.gif" class="ib_left"><input type="button" id="{$k|escape}" name="removeActionButton" value="{'REMOVE_ACTION'|gettext|escape}" class="removeActionButton ib"><img src="/images/blank.gif" class="ib_right"></td></div>
</tr>
{$i = $i+1}
{$k = $k+1}
{$class='treegrid-'|cat:$i}
{/foreach}
<tr>
<td></td><td></td><td></td><td></td><td></td>
<td align="right"><img src="/images/blank.gif" class="ib_left"><input type="button" onclick="updateData('{$row}','{$k}');" data-number="{$i}" value="{'ADD_ACTION'|gettext|escape}" class="addActionButton ib"><img src="/images/blank.gif" class="ib_right"></td>
</tr>
</tbody>
</table>
First ensure you data is what you think it is:
var data = JSON.stringify({ data: actionData, owner:ownerData})
console.log(data)
If it is then sent the data object in your ajax call. Then on the the php side I would confirm that the received data matches the sent data. Then parse said data. This should help you narrow down and resolve your issue(s).
Related
I have table where I loop dynamic data and each of those dynamic items has input fields then I send those input fields along with dynamic items id to back-end.
Issue
Issue is that my fields in ajax giving me strange data as array.
Code
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.newservicesSave').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var idmess = $(this).data("id");
// this array data are wrong
var newservices = [];
$(".newservices").each(function() {
newservices.push($(this).val());
});
console.log('newservices: ', newservices);
$.ajax({
url: '{{ url('
panel / addnewservices ') }}/' + encodeURI(idmess),
type: 'POST',
dataType: "JSON",
data: {
"id": idmess,
"newservices": newservices,
"_method": 'POST',
"_token": "{{ csrf_token() }}",
},
success: function(data) {
$('#servicesTable').empty();
$.each(data.data, function(key, value) {
$("#servicesTable").append('<tr><td>' + value['name'] + '</td><td><textarea name="' + services['key']['description'] + '" class="form-control" name="description"></textarea><input type="hidden" name="' + services['key']['service_id'] + '"/></td><td><input type="text" class="form-control" placeholder="Harga" name="' + services['key']['price'] + '"/></td><td><input class="form-checkbox" type="checkbox" name="' + services['key']['active'] + '" /></td></tr>');
});
}
});
});
});
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>Service</th>
<th>Description</th>
<th>Harga</th>
<th>Active</th>
</tr>
</thead>
<tbody>
#foreach($services as $index => $service)
<tr>
<td>{{$service->name}}</td>
<td>
<textarea name="newservices[{{$index}}][description]" class="newservices form-control" name="description"></textarea>
<input type="hidden" class="newservices" name="newservices[{{$index}}][service_id]" />
</td>
<td>
<input type="text" class="newservices form-control" placeholder="Harga" name="newservices[{{$index}}][price]" />
</td>
<td><input class="newservices form-checkbox" type="checkbox" name="newservices[{{$index}}][active]" /></td>
</tr>
#endforeach
</tbody>
</table>
<button type="button" data-id="{{$laundry->id}}" class="newservicesSave btn btn-primary">Save changes</button>
Result
Expected data from ajax
Data should come to backend as follow structure
newservices [
0 [
active => 0,
service_id => '123456',
description => 'abc',
price => '1000'
],
1 [...],
2 [...],
// etc.
]
Any idea?
To get the structure you want you will need to loop over rows and create an object for each row
Try something like :
var newservices = $('#myTable tbody tr').map(function(){
var $row = $(this);
return {
description: $row.find('.newservices[name*="description"]').val(),
service_id : $row.find('.newservices[name*="service_id"]').val(),
// ... same for other properties
}
}).get();
I have problem getting the value of the replace new table row, I will let you show the codes for the replacing new table row.
The is the Table B, Where this code use for replacing new table row to the Table A
$('#edit_chainingBuild').on('click','tr.clickable-row',function(e){
$('table#edit_chainingBuild tr').removeClass('selected');
$(this).addClass('selected');
var find_each_id_will_update = $(this).find('.data-attribute-chain-id').attr('data-attribute-chain-id');
$('.id_to_update_chain').val(find_each_id_will_update);
var find_each_id_condiments = $(this).find('.data-attribute-chain-id').attr('data-attribute-condiments-section-id');
$.ajax({
url:'/get_each_id_section_condiments',
type:'get',
data:{find_each_id_condiments:find_each_id_condiments},
success:function(response){
var get_each_section = response[0].condiments_table;
$.each(get_each_section, function (index, el) {
var stringify = jQuery.parseJSON(JSON.stringify(el));
var cat_condi_screen_name = stringify['cat_condi_screen_name'];
var cat_condi_price = stringify['cat_condi_price'];
var cat_condi_image = stringify['cat_condi_image'];
var condiment_section_name = stringify['condiment_section_name'];
var image = '<img src=/storage/' + cat_condi_image + ' class="responsive-img" style="width:100px;">';
// $('#edit_chainingBuild').append("<tr class='clickable-row'><td>" + Qty + "</td><td class='clickable-row-condiments'>" + Condiments + "</td><td>" + Price + "</td><td style='display:none;' data-attribute-chain-id="+menu_builder_details_id +" class='data-attribute-chain-id'>"+menu_builder_details_id+"</td></tr>");
$('table#edit_table_chaining_condiments').append("<tr class='edit_condimentsClicked' style='font-size:14px; border:none;'><td>"+condiment_section_name +"</td><td class='edit_condimentsScreenNameClicked'>" + cat_condi_screen_name + "</td><td class='edit_condimentsScreenPriced'>" + cat_condi_price + "</td><td>"+image+"</td></tr>");
});
$("table#edit_table_chaining_condiments tr").click(function(e){
var tableBhtml = $(this).closest('tr').html();
var condiments_name = $(this).closest("tr").find(".edit_condimentsScreenNameClicked").text();
var condimentsScreenPriced = $(this).closest("tr").find(".edit_condimentsScreenPriced").text();
// var input = '<input type="number" id="qty" name="qty" class="form-control changeQuantity" value="1" min="1">';
var id_to_edit_build = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").html('');
var id_to_edit_builders = $('.id_to_update_chain').val();
$("#edit_chainingBuild tr.selected").replaceWith("<tr data-attribute-chain-id=" + id_to_edit_build + " class='clickable-row'><td class='new_condiments_name'>"+condiments_name+"</td><td>"+condimentsScreenPriced+"</td><td style='display:none;' data-attribute-chain-id="+id_to_edit_builders +" class='data-attribute-chain-id'>"+id_to_edit_builders+"</td></tr>");
$('#EditcondimentsBuilderModal').modal('hide');
});
},
error:function(response){
console.log(response);
}
});
$('#EditcondimentsBuilderModal').modal('show');
});
Looking forward if the table row already replace, I want to get the value of the class of new_condiments_name. So I create a variable to find the class of new_condiments_name. It look like this.
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
So now when I try alert the variable new_condiments_name using the click function it shows null only.
$('.edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});
My Html Table:
<div class="modal-body">
<div class="container">
<div class="header" style="text-align: center;">
<br>
<h3 style="color:#007BFF;">Build Your Chain Button</h3>
<label>This button will be served as customers menu.</label><br>
<i class="fab fa-creative-commons-remix" style="font-size:70px;"></i>
<br><br>
<input type="hidden" value="" class="edit_hidden_noun_id" name="">
<table class="table table-hover" id="edit_chainingBuild">
<thead>
<tr style="font-size: 15px;">
<!-- <th scope="col">Qty</th> -->
<th scope="col">Condiments</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody style="font-size:14px;">
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="edit_build_success_insert btn btn-primary">Build Done</button>
</div>
I have here the image to proof that the value that i get always null.
$('table .edit_build_success_insert').click(function(){
var new_condiments_name = $(this).closest("tr").find(".new_condiments_name").text();
alert(new_condiments_name);
});
I'm trying to return the contents of a SharePoint list to a HTML page using a JavaScript Query and json.
The two SharePoint columns are called Title and IssueID and are a Single line and Number column. I need it to return it to the Table cell '' in the HTML. I've attached a screen grab from Firefox debugger but I don't know where this is pointing? Debugger
JavaScript:
function getDeviceKnownIssues() {
var txtTitle = "";
var query = "http://collaboration-dev.norgine.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$select=IssueID,Title";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = result.Id;
var tempTitle = result.Title;
txtTitle = txtTitle + "<p><a href='/sites/it/SystemInventory/SitePages/Service%20Catalogue.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
//txtStatus = "<p>" + StatusType + "</p>";
});
$('#knowntitle').append($(txtTitle));
//$('#servivestatus').append(txtStatus);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
HTML
<html xmlns:mso="urn:schemas-microsoft-com:office:office"
xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>
<script src="/jquery-1.10.1.min.js"></script>
<script src="/it/SystemInventory/SiteAssets/scripts/moment.min.js"></script>
<script src="/sites/it/SystemInventory/SiteAssets/getDevices.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceDetails.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceKnownIssues.js"></script>
<script type="text/javascript">
function parseQueryString(queryString)
{
var params = {}, queries, temp, i, l;
queries = queryString.split("&");
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
}
$(document).ready(function(){
function getDeviceID() {
if(typeof parseQueryString === "function") {
if(window.location.href.indexOf("?") >= 0) {
var qs = parseQueryString(window.location.href.split("?")[1])
window.DeviceId = qs.did;
getDeviceDetails();
getDeviceKnownIssues();
}
}
}
getDeviceID();
getDevices();
});
</script>
</head>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border- style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Devices</h1>
<div id="devices">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Details</h1>
<div id="devicedetails">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Overview</h1>
<div id="deviceoverview">
<div id="devicekind">
</div>
</td>
</tr>
</table>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Accessories</h1>
<div id="deviceacc">
</div>
</td>
<td class="tg-yw4l">
<h1>Typical Usage</h1>
<div id="deviceuse">
</div>
</td>
<td class="tg-yw4l">
<h1>Spare Cell</h1>
<div id=" ">
</div>
</td>
</tr>
</table>
Known Issues
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Title</h1>
<div id="knowntitle">
</div>
</td>
<td class="tg-yw4l">
<h1>Service Status</h1>
<div id="servivestatus">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Type</h1>
<div id=" ">
</div>
</td>
</tr>
</table>
Replace your call.done method with the below code,
call.done(function (data,textStatus, jqXHR){
var result = data.d.results;
$.each(result , function(index, item) {
var tempID = result.Id;
var tempTitle = result.Title;
txtTitle = txtTitle + "<p><a href='/sites/it/SystemInventory/SitePages/Service%20Catalogue.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
//txtStatus = "<p>" + StatusType + "</p>";
});
$('#knowntitle').append($(txtTitle));
//$('#servivestatus').append(txtStatus);
});
I'm trying to return the contents of a SharePoint list to a HTML page using a JavaScript Query and JSON.
The line:
var query = "**http://collaboration-xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$select=DeviceID,Title**
does return the DeviceID and Title in browser.
However I don't quite know how I should construct the var query to return results from all the columns. What I've got is:
**var query = " xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$expand=Knownissues&$filter=DeviceID eq " + window.DeviceId + "";**
I've copied the 'windowsDeviceId' from a previous file which did work. Just having the first var query doesn't return anything and the second returns the attached screen grab. Error code.
The SharePoint columns are: Title, ServiceStatus, Devicetype and DeviceID
JavaScript:
function getDeviceKnownIssues() {
var txtTitle = "";
var txtStatus = "";
//var ServiceStatus = "";
//var Devicetype = "";
//var query = "http://collaboration-xxx/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$select=DeviceID,Title",
var query = "http://collaboration-xxx.com/sites/it/SystemInventory/_vti_bin/listdata.svc/Knownissues?$expand=Knownissues&$filter=DeviceID eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function(index, item) {
var tempID = result.DeviceId;
var tempTitle = result.Title;
var StatusType = ServiceStatus;
txtTitle = txtTitle + "<p><a href='/sites/it/SystemInventory/SitePages/Service%20Catalogue.aspx?did=" + tempID + "'>" + tempTitle + "</a></p>";
txtStatus = "<p>" + StatusType + "</p>";
});
$('#knowntitle').append($(txtTitle));
$('#servivestatus').append(txtStatus);
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving data: " + jqXHR.responseText);
});
}
HTML
<html xmlns:mso="urn:schemas-microsoft-com:office:office"
xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"><head>
<script src="/jquery-1.10.1.min.js"></script>
<script src="/it/SystemInventory/SiteAssets/scripts/moment.min.js"></script>
<script src="/sites/it/SystemInventory/SiteAssets/getDevices.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceDetails.js"></script>
<script
src="/sites/it/SystemInventory/SiteAssets/getDeviceKnownIssues.js"></script>
<script type="text/javascript">
function parseQueryString(queryString)
{
var params = {}, queries, temp, i, l;
queries = queryString.split("&");
for ( i = 0, l = queries.length; i < l; i++ ) {
temp = queries[i].split('=');
params[temp[0]] = temp[1];
}
return params;
}
$(document).ready(function(){
function getDeviceID() {
if(typeof parseQueryString === "function") {
if(window.location.href.indexOf("?") >= 0) {
var qs = parseQueryString(window.location.href.split("?")[1])
window.DeviceId = qs.did;
getDeviceDetails();
getDeviceKnownIssues();
}
}
}
getDeviceID();
getDevices();
});
</script>
</head>
<style type="text/css">
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border- style:solid;border-width:1px;overflow:hidden;word-break:normal;}
.tg .tg-yw4l{vertical-align:top}
</style>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Devices</h1>
<div id="devices">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Details</h1>
<div id="devicedetails">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Overview</h1>
<div id="deviceoverview">
<div id="devicekind">
</div>
</td>
</tr>
</table>
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Accessories</h1>
<div id="deviceacc">
</div>
</td>
<td class="tg-yw4l">
<h1>Typical Usage</h1>
<div id="deviceuse">
</div>
</td>
<td class="tg-yw4l">
<h1>Spare Cell</h1>
<div id=" ">
</div>
</td>
</tr>
</table>
Known Issues
<table class="tg">
<tr>
<td class="tg-yw4l">
<h1>Title</h1>
<div id="knowntitle">
</div>
</td>
<td class="tg-yw4l">
<h1>Service Status</h1>
<div id="servivestatus">
</div>
</td>
<td class="tg-yw4l">
<h1>Device Type</h1>
<div id=" ">
</div>
</td>
</tr>
</table>
I have been working on a webpage with some simple form validation and submit using javascript functions and ajax. I have written a function that validates a form and then submits it to another php page. I have then created a second form and validating/submitting javascript function. Both work separately, so I don't think it is my functions that are wrong, however when I try to put them into one js file to call them, only one of the functions works. I can remove the other re-upload it and it calls fine. I would appreciate it if someone could spot what I am doing wrong.
$(function () {
$('.error').hide();
});
function publication(){
$('.error').hide();
var title = $("input#title").val();
if (title == "") {
$("label#title_error").show();
$("label#title_error").css("color", "red");
$("input#title").focus();
return false;
}
var author = $("input#author").val();
if (author == "") {
$("label#author_error").show();
$("label#author_error").css("color", "red");
$("input#author").focus();
return false;
}
var publisher = $("input#publisher").val();
if (publisher == "") {
$("label#publisher_error").show();
$("label#publisher_error").css("color", "red");
$("input#publisher").focus();
return false;
}
var avail = $("input#avail").val();
if (avail == "") {
$("label#avail_error").show();
$("label#avail_error").css("color", "red");
$("input#avail").focus();
return false;
}
var info = $("textarea#info").val();
if (info == "") {
$("label#info_error").show();
$("label#info_error").css("color", "red");
$("textarea#info").focus();
return false;
}
var webaddr = $("input#webaddr").val();
var YYYY = $("input#YYYY").val();
var img = $("input#img").val();
var dataString = 'title='+ title + '&author=' + author + '&publisher=' + publisher + '&avail=' + avail + '&info=' + info + '&YYYY=' + YYYY + '&webaddr=' + webaddr + '&img=' + img;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/includes/add_publication.php",
data: dataString,
success: function() {
$('#event_form').html("<div id='message'></div>");
$('#message').html("<h2>Publication Added</h2>")
.append("<p>The publication has been added to the database.</p>")
.hide()
.fadeIn(1500);
}
});
return false;
}
function events(){
$('.error').hide();
var eventname = $("input#eventname").val();
if (eventname == "") {
$("label#event_error").show();
$("label#event_error").css("color", "red");
$("input#eventname").focus();
return false;
}
var venue = $("input#venue").val();
if (venue == "") {
$("label#venue_error").show();
$("label#venue_error").css("color", "red");
$("input#venue").focus();
return false;
}
var info = $("textarea#info").val();
if (info == "") {
$("label#info_error").show();
$("label#info_error").css("color", "red");
$("textarea#info").focus();
return false;
}
var webaddr = $("input#webaddr").val();
var DD = $("input#DD").val();
var MM = $("input#MM").val();
var YYYY = $("input#YYYY").val();
var DD2 = $("input#DD2").val();
var MM2 = $("input#MM2").val();
var YYYY2 = $("input#YYYY2").val();
var img = $("input#img").val();
var dataString = 'eventname='+ eventname + '&venue=' + venue + '&info=' + info + '&webaddr=' + webaddr + '&DD=' + DD + '&MM=' + MM + '&YYYY=' + YYYY + '&DD2=' + DD2 + '&MM2=' + MM2 + '&YYYY2=' + YYYY2 + '&img=' + img;
//alert (eventString);return false;
$.ajax({
type: "POST",
url: "/includes/add_event.php",
data: dataString,
success: function() {
$('#event_form').html("<div id='message'></div>");
$('#message').html("<h2>Event Added</h2>")
.append("<p>The event has been added to the database.</p>")
.hide()
.fadeIn(1500);
}
});
return false;
}
The publication and events functions are called via click handlers in the HTML (here it's publication):
<table width="100%" id="publication">
<tr>
<td width="20%">Title:</td>
<td>
<input name="title" type="text" id="title" size="50" />
</td>
<td width="30%">
<label class="error" for="title" id="title_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Author:</td>
<td>
<input name="author" type="text" id="author" size="50" />
</td>
<td>
<label class="error" for="author" id="author_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Publisher:</td>
<td>
<input name="publisher" type="text" id="publisher" size="50" />
</td>
<td>
<label class="error" for="publisher" id="publisher_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Publication Year:</td>
<td>
<input name="YYYY" type="text" id="YYYY" size="4" />
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Website:</td>
<td>http://
<input name="webaddr" type="text" id="webaddr" size="50" />
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Availability:</td>
<td>
<input name="avail" type="text" id="avail" size="30" />
</td>
<td>
<label class="error" for="avail" id="avail_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td valign="top">Publication Information:</td>
<td>
<textarea rows="4" cols="50" name="info" id="info"></textarea>
</td>
<td>
<label class="error" for="info" id="info_error">This field is required.</label>
</td>
</tr>
<tr>
<td colspan="2"></td>
</tr>
<tr>
<td>Image Name:</td>
<td>
<input name="img" type="text" id="img" size="50" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" class="button" id="pubs_btn" value="Add" onclick="publication()" />
</td>
</tr>
</table>
As you can hopefully see there are three things happening here. 1: all error messages are being hidden on page load, second and third are my two functions - publication and events. I have several verified fields which get given a rec error message if they are blank. I am then sending all the variables into a string to be submitted via ajax to a php file to insert them into my sql database.
I could be missing something as simple as a semi-colon somewhere - but as I have never written multiple functions in one file I haven't worked that out.
You have a syntax error:
var eventString = 'eventname='+ eventname + '&venue=' + venue + '&info=' + info '&webaddr' + webaddr + '&DD' + DD + '&MM' + MM + '&YYYY' + YYYY + '&DD2' + DD2 + '&MM2' + MM2 + '&YYYY2' + YYYY2 + '&img' + img;
// Here ------------------------------------------------------------------------^
This prevents your JavaScript from being correctly parsed, thereby preventing your code from being run when the click occurs.
Your web browser was telling you about this: If you open your web console or developer tools, you'll see the error listed.