update database using AJAX - mysql

I'm trying to update my database using AJAX, but somehow it doesn't work. I have already done the part of getting the data from the database into the input fields.
I have an input field "name":
<form method="post" ACTION="update.php">
<input maxlength="250" NAME="name" id="name" value="SomeName" SIZE="50">
<INPUT TYPE="submit" NAME="submit" id="submit" VALUE="submit">
<span id="error" style="display:none"> Please Enter Valid Data! Did you fill in all the fields?</span>
<span id="success" style="display:none"> the name has been updated successfully!</span>
</form>
And using this code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#submit").click(function() {
var name = encodeURIComponent($.trim($("#name").val()));
var dataString = "name =" + name;
if(name == "")
{
$("#success").fadeOut(2).hide();
$("#error").fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType:'json',
success: function(data)
{
if(!data.error)
{
$("#success").fadeIn(200).show();
$("#error").fadeOut(200).hide();
}
else
{
alert(data.error);
}
}
});
}
return false;
});
});
I'm passing the name to update.php, which is:
<?php
$con = mysql_connect('localhost', 'someUsername', 'somePassword');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("someDatabase", $con);
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$query="UPDATE SOMETABLE SET name ='$name'";
$result = mysql_query($query) or die (mysql_error);
}
else
{
echo "Something wrong with the POST";
}
mysql_close($con);
exit;
?>
I'm getting the error: "Something wrong with the POST";
Thanks in advance.
UPDATE: the problem is not "name" instead of "name =" (which I already have edited). That was just a typing error on here.

var dataString = "name" + name;
this line should be changed to this;
var dataString = "name=" + name;

You use the datatype "json" in the jquery ajax request. And you give only a String to this method.
Change your dataString value to this:
var dataString = {'name':name};
This should work fine ;)

Unless you use turn off the option "processData" you need to pass in an object as data.
See this snippet from the jQuery API:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
http://api.jquery.com/jQuery.ajax/

Your data should be passed as an array (reference), try changing your post to the following:
$.ajax({
type: "POST",
url: "update.php",
data: {
name: name
},
dataType:'json',
success: function(data)
{
if(!data.error)
{
$("#success").fadeIn(200).show();
$("#error").fadeOut(200).hide();
}
else
{
alert(data.error);
}
}
});

Related

Ajax call returning [object object] on json data type

I am trying to insert the data of ck-editor in to a Mysql table using ajax call. The data type of the column in the Mysql table is text and the table has just one column named disclaimer.
The file index.php has a ck-editor and a button for On-click ajax call.
index.php
<html>
<script type="text/javascript">
function disclaimerData() {
var disclaimer=$("#disclaimer").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "disclaimer-data.php",
data: {disclaimer:disclaimer},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
<body>
<textarea id="js-ckeditor" class="disclaimer" name="disclaimer"> </textarea>
<button type="button" class="btn btn-square btn-secondary" name="insert-data" id="insert-data" onclick="disclaimerData()" style="background-color:#8C489F;color: white;cursor: pointer; ">Save</button>
</body>
</html>
The file disclaimer-data has the PDO script to insert data into table.
disclaimer-data.php
<?php
include('../includes/config.php');
$disclaimer = $_POST['disclaimer'];
$stmt = $db->prepare("INSERT INTO disclaimer(disclaimer) VALUES(:disclaimer)");
$stmt->bindparam(':disclaimer');
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
?>
The problem in above code is it returns [Object Object] on ajax call.
Edit your html code to:
<?php
include('../includes/config.php');
$disclaimer = $_POST['disclaimer'];
$stmt = $db->prepare("INSERT INTO disclaimer(disclaimer) VALUES(:disclaimer)");
$stmt->bindparam(':disclaimer');
$res = array();
if($stmt->execute())
{
$res['msg']="Data Inserted Successfully:";
$res['err'] = 0;
}
else
{
$res['msg']="Not Inserted,Some Probelm occur.";
$res['err'] = 1;
}
echo json_encode($res);
?>
And edit your script to:
$.ajax({
type: "POST",
url: "disclaimer-data.php",
data: {disclaimer:disclaimer},
dataType: "JSON",
success: function(data) {
if(data.err==0){
$("#message").html(data.msg);
$("p").addClass("alert alert-success");
}
else{
alert(data.msg);
}
}
});

How can I use JSON to link my html form to update a sharepoint list?

At the moment I'm just trying to add name to the list. I'll add more when I get that working.
I'm currently getting errors in the debugger with the following :
var siteurl = _spPageContextInfo.webAbsoluteUrl;
Also, I've more than one column in the list, could that be it?
What I have:
$('#submitdata').click(function () {
//this gets the value from your name input
var name = $('#name').val();
var data = {
__metadata: { 'type': 'SP.Data.ProjectsListItem' },
"name": name,
};
$.ajax({
var siteurl = _spPageContextInfo.webAbsoluteUrl;
$.ajax({
url: siteurl + "/mysite/Lists/getbytitle('ChangeOfAddressList')/items",
method: "POST",
data: JSON.stringify(data),
headers: { "Accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('Item added successfully');
},
error: function (error) {
alert("Error: "+ JSON.stringify(error));
}
});
});
HTML:
<body>
<form id="COA_Form" name="myForm" method="post" action="" >
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit' />
</form>
</body>
To test your code, change the line
var siteurl = _spPageContextInfo.webAbsoluteUrl;
to
var siteurl = 'https://spsitedomain';.
Of course you would want to use your actual SharePoint site domain instead of 'spsitedomain'.
You can open the console and see what the _spPageContextInfo object yields. In my browser, I either get undefined or I get an object that does not have a webAbsoluteUrl property (depending on the page I am viewing), so your mileage may vary when using this object.

JSON issue in Codeigniter File Upload

I am having the below code in view for the file upload form:
<form method="post" action="<?=site_url('api/do_upload')?>" enctype="multipart/form-data" id="upload_photo" />
<input type="file" name="userfile" size="20" class="btn btn-primary" /><br />
<input type="submit" value="upload" class="btn btn-warning btn-xs" />
</form>
The event captures in JS:
$("#upload_photo").submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var postData = $(this).serialize();
$.post(url, postData, function(o){
if(o.result == 1) {
Display.success(o.output);
}
else
{
Display.error(o.error);
}
},'json');
});
Model, where I am processing the file upload:
public function do_upload()
{
$this->_require_login();
$this->output->set_content_type('application_json');
$config['upload_path'] = 'C:\xampp2\htdocs\kedb\public\img\profile';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = $this->session->userdata('user_id');
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$this->output->set_output(json_encode([
'result' => '0',
'output' => $this->upload->display_errors()
]));
}
else
{
$this->output->set_output(json_encode([
'result' => '1',
'output' => 'File Uploaded Successfully'
]));
return false;
//$data = array('upload_data' => $this->upload->data());
//$this->load->view('upload_success', $data);
}
}
When I click the "upload" button, it getting the below error:
{"result":"0","output":"<p>You did not select a file to upload.<\/p>"}
If I remove id="upload_photo" in <form> tag, it is working. It gives error only when I add id attribute in <form>.
I might have missed something or did anything wrong. Could someone please me out?
I resolved the same issue by adding "text/plain" to the json type in the config/mimes.php file. So now this line looks like this (it's 117-th line in the file in the CI version I use):
'json' => array('application/json', 'text/json', 'text/plain'),
.serialize() returns a string of all the form values. You cannot upload files by using .serialize().
If you want to upload via AJAX, then you'll need to create a FormData object. You'll also need to use $.ajax, so you can tweak a few of the settings.
var url = $(this).attr('action');
var postData = new FormData(this);
$.ajax({
url: url,
data: postData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(o){
if(o.result == 1) {
Display.success(o.output);
}
else{
Display.error(o.error);
}
}
});
I haven't been using codeigniter long but I would think this might be because of the way your are implementing the form. Use form_open();
https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
To add the attributes, do this
<?echo form_open('api/do_upload',array('id'=>'upload_photo'));?>
The Second error I can see is in your AJAX.
$(this).serialize();
You want to pass an object into postdata like so
data:{file:$(this).children('input[type="file"]').val()},
Also! When sending files with AJAX you need to use formData();
formData=new formData();
$file=$(this).children('input[type="file"]');
formData.append('file',$file.files[0],$file.files[0].name);
In case I've got anything wrong:
http://blog.teamtreehouse.com/uploading-files-ajax

Knockout applyBindings does not applyBinding

I have just started to use knockout.js and am stuck when trying to show JSON data.
My HTML is
<p>Dealer Location: <input id="dealerlocation" data-bind="value: DealerLocation" /></p>
<p>Contact Report Date: <input id="crdate" data-bind="value: CRDate" /></p>
My Script Block is
function viewAction() {
var self = this;
self.DealerLocation = ko.observable("");
self.CRDate = ko.observable("");
};
var viewActionModel = new viewAction();
function GetActionByID() {
$.ajax({
type: "POST",
url: "/ws/someservice.asmx/GetAction",
data: "{pacid: '" + $('input[id$=hidActionID]').val() + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (response) {
var action = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$.each(action, function (index, axn) {
viewActionModel.DealerLocation = axn.DealerLocation;
viewActionModel.CRDate = axn.CRDate;
});
}
});
}
$(document).ready(function () {
GetActionByID();
//alert(viewActionModel.DealerLocation);
ko.applyBindings(viewActionModel);
});
Note: If I uncomment alert then applyBinding works otherwise it does not.
What is missing here???
Ragards.
This is a wrong way to assign observables.
viewActionModel.DealerLocation = axn.DealerLocation;
viewActionModel.CRDate = axn.CRDate;
Do it like this.
viewActionModel.DealerLocation(axn.DealerLocation);
viewActionModel.CRDate(axn.CRDate);
By doing what you do now you are replacing observables with regular variable. It was working with alert because this replacement took place before binding and knockout just picked up your regular variables. Read more about observables.

How to access JSON object property from data returned by AJAX call?

I'm making an AJAX call to this php file:
<?php
$result = array('error' => "Please enter a valid name");
echo json_encode($result)
?>
In my javascript file, I have:
$.ajax({
type:"POST",
url:"/controller/common/review_processing.php",
data:dataString,
success:function (data) {
var returned_data = data;
console.log(returned_data); <---This outputs {"error":"Please enter a valid name"}
console.log(returned_data.error); <---This outputs undefined
}
});
My data seems to be encoded as a JSON object correctly but when I try to access a specific property, I get an undefined result.
What I want is for console.log(returned_data.error) to output:
Please enter a valid name
What am I doing wrong?
Please try :
$.ajax({
type:"POST",
url:"/controller/common/review_processing.php",
data:dataString,
dataType: "json", <--response itself will be handled as JSON
success:function (data) {
var returned_data = data;
console.log(returned_data); <---This outputs {"error":"Please enter a valid name"}
console.log(returned_data.error);
}
});
Try using this...
$.map(data.d, function (item) {
console.log(item.error);
});