I am using Ajax to post the results from a php form to a database using an API. However when the script runs, I am not getting anything in return stating that it was a success or an error. I can log into the database and see that it has added the entry but I am not getting an alert when it saves to the database.
What I would like the script to do is:
-First save to the database (Done)
-Second: Alert the user that the operation was completed successfully or error
-Third: reset the values in the form if success, keep values if error
Here is what I have tried and have so far:
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
$('form#directory-create').on('submit', function (e) {
//stops the submit action
e.preventDefault();
//format the data into javascript object
var data = $(this).serializeArray();
//calls function to create record, passing participant information as arguments
createRecord(data);
});
function resetStudyInfo() {
//resets all form values to default
$('form#directory-create').find('input:text, input:radio, input:email, input:phone').val('');
return true;
}
function createRecord(data) {
//converts into json data format
var myData = JSON.stringify(data);
console.log(myData);
$.ajax({
//setup option for .ajax func
type: "POST",
url: "directory-create-record.php",
data: {
//user_data : contains all the fields and their data
user_data: myData
},
//shows output message on error or success
success: function () {
showSuccess('Study created successfully, you may now add participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
PHP side:
require "RestCallRequest.php";
function insertData($data_from_user){
$status = 2;
$url = "xxxx";
$token = "mytokenishere";
$fname = $data_from_user[0]->value;
$lname = $data_from_user[1]->value;
$title = $data_from_user[2]->value;
$school = $data_from_user[3]->value;
$facultystafftrainee = $data_from_user[4]->value;
$email = $data_from_user[5]->value;
$phone = $data_from_user[6]->value;
$record_id = $lname .'_'. $fname;
# an array containing all the elements that must be submitted to the API
$data = "record_id,f_name,l_name,title,school,facultystafftrainee,email,phone,directory_complete\r\n";
$data .= "$record_id,$fname,$lname,$title,$school,$facultystafftrainee,$email,$phone,$status";
$args = array(
'content' => 'record',
'type' => 'flat',
'format' => 'csv',
'token' => $token,
'data' => $data
);
# create a new API request object
$request = new RestCallRequest($url, 'POST', $args);
# initiate the API request
$request->execute();
$result = $request->getResponseBody();
if($result == '1'){
return 1;
}
}
Any help is greatly appreciated. Thank you
When resetting the form values, you have input:email and input:phone, javascript throws a syntax error as you do not need these values, When you remove them your code should work.... Here is the complete working code
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function resetStudyInfo() {
$('form#directory-create').find('input:text, input:radio').val('');
return true;
}
$('form#directory-create').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray();
createRecord(data);
});
function createRecord(data) {
var myData = JSON.stringify(data);
$.ajax({
type: "POST",
url: "directory-create-record.php",
data: {
user_data: myData
},
success: function () {
showSuccess('Study created successfully, you may now add more participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
Related
I am trying to use Ajax that will keep
the inputs that the user has entered but for some reason, it isn't working.
In case of an error, my controller redirects the view with the data of errors,
however, after the page is uploading the form is empty.
I am using the MVC model of Codeigniter.
$("#save").click(function () {
var tnum1 = $("#tnum1").val();
var tnum2 = $("#tnum2").val();
var tnum3 = $("#tnum3").val();
var loc = $("#loc").val();
var dine = $("#dine").val();
var date = $("#date").val();
var time = $("#time").val();
var phone = $("#phone").val();
var fullname = $("#fullname").val();
$.ajax({
type: 'POST',
url: "<?php echo site_url(); ?>" + "/hosting/create",
data: {tnum1:tnum1, tnum2:tnum2, tnum3:tnum3, loc:loc, dine:dine,
date:date, time:time, phone:phone, fullname: fullname},
error: function () {
alert( "Load was performed.");
},
success: function (data) {
if (data === "") {
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else {
$("#error").html(data);
}
}
});
});
Controller
public function create() {
$newDate = date("Y-m-d",strtotime($this->input->post('re_date')));
$newTime = date("H:i", strtotime($this->input->post('re_time')));
$data = array(
'num' => $this->input->post('num'),
'location' => $this->input->post('location'),
'diners' => $this->input->post('diners'),
're_date' => $newDate,
're_time' => $newTime,
'phonenumber' => $this->input->post('phonenumber'),
);
$dataclient = array(
'fullname' => $this->input->post('fullname'),
'phonenumber' => $this->input->post('phonenumber'),
);
$error = $this->validation($data,$dataclient);
if ($error) {
$data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.'');
redirect(base_url("/hosting/tableMap"));
} else {
$this->Hosting_model->form_insert($data, $dataclient);
}
}
If you redirect the controller then it will not retain the previous values. Instead save the error in a variable and return it to ajax function.
That is the whole point of ajax - to not redirect or reload a page ie do the task asynchronously.
remove this line-
redirect(base_url("/hosting/tableMap")); // redirecting on error
then in your controller
if ($error) {
// data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.''); // remove this as page will not reload, flashdata wouldn't work
// redirect(base_url("/hosting/tableMap"));
$ajax_data['error'] = 1; // if error exists then value
$ajax_data['validation_error'] = $error;
} else {
$this->Hosting_model->form_insert($data, $dataclient);
$ajax_data['error'] = 0; // if error doesn't exist then value
}
return json_encode($ajax_data); // or echo json_encode($ajax_data);
Now, to prevent default action of form submission that is to redirect page use
$("#save").click(function (e) {
e.preventDefault();
// rest of your code
then in your ajax success:
if (data.error == 0) { // no error
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else { // error
$("#error").html(data); // do whatever you want to do with error
// errors can be retrieved from "data.validation_error" -- it will be an array probably sp you'll have to loop through each element
}
I'm trying to populate my form with the server copy of my json array, but it seems to be pulling from the local copy. Right now I have a function that populates the form when I click on a rectangle (each of which represents a json object in the array).
For example, if I change the select option attributeName on the form and submit, it saves the change correctly to the server in the json array, but when I click on a different rectangle and come back to the rectangle with the change, it doesn't populate the form field with the change (doesn't pull from the server json array).
If I load a different array, or if I refresh the page, then it works...how can I get my local copy of the array to reflect the change without refreshing?
Here is the function:
$(function() {
function populateForm() {
var matchingWidth = $('#canvas-overlay > .rectangle.targeted').width();
$(".rectangle.null").each(function() {
if ($(this).width() === matchingWidth) {
var ID_clicked = $(this).attr('id');
// populate form function
function populate(frm, data) {
$.each(data, function(key, value){
var ctrl = $('[name='+key+']', frm);
switch(ctrl.prop("type")) {
case "radio": case "checkbox":
ctrl.each(function() {
if($(this).attr('value') == value) {
$(this).prop("checked", true);
$("#attribute-form .ui.radio.checkbox").removeClass('checked');
$(this).parent().addClass('checked');
}
});
break;
default:
ctrl.val(value);
}
});
}
var selection = $('#templateSelection > option:selected').text();
// create variable for and expose JSON
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'server/php/data/' + selection,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
// search json for index value that matches id clicked
// and populate form with associated object
json.some(function(e) {
if (e.ID === ID_clicked) {
var values = json.map(function(e) { return e.ID; });
var index = json.map(function(e) { return e.ID; }).indexOf(ID_clicked);
var data = JSON.stringify(json[index]);
populate('#attribute-form', $.parseJSON(data));
return true; // stops the "loop"
}
});
}
});
}
$(document).on('click', '#canvas-overlay > .rectangle', function() {
$('#canvas-overlay > .rectangle').removeClass('targeted');
$(this).addClass('targeted');
populateForm();
});
});
and for reference here is process.php which is the action when submitting:
<?php
$filename = $_POST['store-template-name'];
$myFile = "data/" . $filename;
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'ID'=> $_POST['ID'],
'attributeName'=> $_POST['attributeName']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
$updateKey = null;
foreach ($arr_data as $k => $v) {
if ($v['ID'] == $formdata['ID']) {
$updateKey = $k;
}
}
if ($updateKey === null) {
array_push($arr_data,$formdata);
} else {
$arr_data[$updateKey] = $formdata;
}
$jsondata = json_encode($arr_data);
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
get requests are cached, either have serverside set proper no cache headers or set cache to false in jQuery.
$.ajax({
'async': false,
'global': false,
cache: false,
'url': 'server/php/data/' + selection,
'dataType': "json",
'success': function (data) {
json = data;
}
});
And do yourself a favor and refactor your code to not by synchronous. Synchronous calls are a bad idea. The code after the json code should live in the success callback or use done which is the recommended way with jQuery.
I have more than 4 forms which has different name and id in my page and i create loop function to post every form with ajax.and loop work every form posting ın order.
Problems:
1-gives me error like
"Uncaught TypeError: Cannot read property 'location' of null"
2-sometimes window.close work at first click(usually on local computer) sometimes not (usually at remoteserver) probably ajax calls interrupt closing
This is my script
<script name="ajax fonksiyonları" type="text/javascript">
function validate(form){
var formID = form.id;
var formDetails = $('#'+formID);
$.ajax({
type: "POST",
url: 'ajax.php',
data: formDetails.serialize(),
success: function (data) {
console.log(data);
window.opener.location.reload();
window.close()
},
error: function(jqXHR, text, error){
// Displaying if there are any errors
console.log(error);
}
});
return false;
}
function submitAll(){
for(var i=0, n=document.forms.length; i<n; i++){
validate(document.forms[i]);
}
}
This is ajax.php
FUNCTION mysql_update_array($table, $data, $id_field, $id_value) {
$data=data_cleaner($data);
FOREACH ($data AS $field=>$value) {
$fields[] = SPRINTF("`%s` = '%s'", $field, MYSQL_REAL_ESCAPE_STRING($value));
}
$field_list = JOIN(',', $fields);
$query = SPRINTF("UPDATE `%s` SET %s WHERE `%s` = %s", $table, $field_list, $id_field, INTVAL($id_value));
if( mysql_query($query) ) {
return array( "mysql_error" => false,
"mysql_insert_id" => mysql_insert_id(),
"mysql_affected_rows" => mysql_affected_rows(),
"mysql_info" => mysql_info()
);
} else {
return array( "mysql_error" => mysql_error() );
}
}
if (isset($_POST['hupdate'])) {
$result=mysql_update_array("customers", $_POST, "c_id", $_POST['c_id']);
}
I am making a LIVE UPDATE in CodeIgniter and it is almost working.
Just one little issue: When I click the button it also appears my navigation inside the "responds" box which is very strange.
And when I refresh the page it is removed and the record is there.
Here is an image to explain what I mean
Here is the JavaScript:
<script type="text/javascript">
$(document).ready(function() {
//##### Add record when Add Record Button is click #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val() ==='')
{
alert("Please enter some text!");
return false;
}
var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure
jQuery.ajax({
type: "POST", // Post / Get method
url: "<?php echo site_url('admin/dashboard/index'); ?>", //Where form data is sent on submission
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response) {
$("#responds").append(response);
},
error:function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
});
</script>
EDIT:
HERE IS THE CONTROLER
class Dashboard extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load libraries
$this->load->library('ion_auth');
$this->load->library('parser');
// Load models
$this->load->model('note_model');
// Load helpers
$this->load->helper('date');
// Set error delimiters
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
}
public function index()
{
// Check if user is loged in
if (!$this->ion_auth->logged_in())
{
redirect('auth/login');
}
else
{
// Create notes object
$notes = new Note_model();
// Order the notes by date post
$notes->order_by('date_post', 'desc')->get();
$recent_notes = array();
foreach ($notes as $note)
{
$single_note = array
(
'id' => $note->id,
'note_text' => $note->note_text,
'date_post' => $note->date_post,
);
array_push($recent_notes, $single_note);
}
// Get the user id as an object
$getinfo = $this->ion_auth->user($this->session->userdata('user_id'))->row();
// Create a new note
$createNote = new Note_model();
$createNote->note_text = $this->input->post('content_txt');
$created = date('Y-m-d H:i:s');
$createNote->date_post = $created;
// Validation rules
$rules = $this->note_model->rules;
$this->form_validation->set_rules($rules);
$data = array
(
'admin_content' => 'admin/dashboard',
'notes' => $recent_notes,
'username' => $getinfo->{'first_name'} . ' ' . $getinfo->{'last_name'},
);
if ($this->form_validation->run() == FALSE)
{
$this->parser->parse('admin/template_admin', $data);
}
else
{
$createNote->save();
redirect('admin/dashboard');
}
}
}
The problem is the action you are calling.
It seems admin/dashboard/index outputs the navigation as well as the data you want to display.
You should post to an action that ONLY displays the data you require, and nothing else
I'm trying to send data from an html data attribute on a span element and receive it with Ajax and then process it with php and mysql and return the new value to my data attribute in html, but I'm getting a error that says "$.parseJSON unexpected character", can someone please look over my code to see if I'm processing the data correctly as I'm new to working with JSON.
HTML / PHP
<span data-object=
'{"art_id":"<?php echo $row['art_id'];?>",
"art_featured":"<?php echo $row['art_featured'];?>"}'
class="icon-small star-color"></span>
<!-- art_id and art_featured are both int and art_featured will be either 1 or 0 -->
jQuery / Ajax
$("span[class*='star']").on('click', function () {
var data = $.parseJSON($(this).data('object'));
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', JSON.stringify( data ));
});
});
PHP / mySQL
if($_POST['art_featured']==1) {
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 0 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 0);
echo json_encode($result);
}
else if($_POST['art_featured']==0){
$sql_articles = "UPDATE `app_articles` SET `art_featured` = 1 WHERE `art_id` =".$_POST['art_id'];
$result = array('art_id' => $_POST['art_id'], 'art_featured' => 1);
echo json_encode($result);
}
if(query($sql_articles)) {
}
else {
}
You don't need to use $.parseJSON, jQuery does that for you.
$("span[class*='star']").on('click', function () {
var data = $(this).data('object');
var $this = $(this);
$.ajax({
type: "POST",
url : "ajax-feature.php",
data: {art_id: data.art_id,art_featured: data.art_featured}
}).done(function(result) {
data.art_featured = result;
$this.data('object', data);
});
});
You also don't need to stringify it later.