View urlCreate code
$ajaxSaveTestGrid = Yii::$app->urlManager->createUrl('testgrid/ajaxsave');
This Is My View Ajax Code
function saveRow(id, index) {
if(id == 'tbl_testGrid') {
save(id, index);
}
}
function save(id, index) {
var testGrid_name = $('#testGrid_name' + index).val();
var testGrid_qty = $('#testGrid_qty' + index).val();
var testGrid_price = $('#testGrid_price' + index).val();
var url = '$ajaxSaveTestGrid';
// alert(testGrid_name+testGrid_qty+testGrid_price);
$.ajax({
type: 'GET',
url: url,
data: {
testGrid_name:testGrid_name,
testGrid_qty:testGrid_qty,
testGrid_price:testGrid_price
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
if(response == 'error') {
alert('Fail to save! Please try again');
} else {
$('#testGrid_name' + index).attr(\"disabled\",true);
$('#testGrid_qty' + index).attr(\"disabled\",true);
$('#testGrid_price' + index).attr(\"disabled\", true);
$('#testGrid_save_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_delete_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_edit_button' + index).attr(\"class\", \"show\");
$('#hid_testGrid_id' + index).val(response[0].testgrid.id);
$('html,body').animate({scrollTop: $('#btn_testGrid').offset().top});
}
}
});
}
This is my Controller
public function actionAjaxsave() {
$result = array();
$testGrid_name = $_GET['testGrid_name'];
$testGrid_qty = $_GET['testGrid_qty'];
$testGrid_price = $_GET['testGrid_price'];
$model = new Testgrid();
$model->name = $testGrid_name;
$model->price = $testGrid_price;
$model->qty = $testGrid_qty;
if ($model->save()) {
array_push($result, ['testgrid' => $model]);
$result = Json::encode($result);
echo $result;
} else {
echo 'error';
}
}
It occurring Internal Server Error
I want to save json Data to model.
Internal Server Error means that your code has fatal errors and error displaying is turned off. If you want to see the error itself, you must enable error displaying.
Check out the following question with its answers: How do I get PHP errors to display?
After you see the error, you can fix it.
PS:
$testGrid_name = $_GET['testGrid_name'];
This is not a recommended way to access GET variables. Use Yii::$app->request->get('testGrid_name') instead
Related
I am trying to upload Image but upon running my application my Image parameter is passing null, and I don't know why it is not picking up the file I attached
but in my browser console when I check my image file object that if it is attached or not, it shows that it does attach
but in my controller its passing null
my ajax code where I am passing the image file object,
$('.empOfficialDetails').click(function (ev) {
ev.preventDefault();
var data = new Object();
data.UserName = $('#username').val();
data.UPassword = $('#userpass').val();
data.OfficialEmailAddress = $('#officialemail').val();
data.Departments = $('#departments :selected').text();
data.Designation = $('#designation :selected').text();
data.RoleID = $('#role').val();
data.Role = $('#role :selected').text();
data.ReportToID = $('#reportToID').val();
data.ReportTo = $('#reportTo :selected').text();
data.JoiningDate = $('#joindate').val();
data.IsAdmin = $('#isAdmin :selected').val() ? 1 : 0;
data.IsActive = $('#isActive :selected').val() ? 1 : 0;
data.IsPermanent = $('#isPermanent :selected').val() ? 1 : 0;
data.DateofPermanancy = $('#permanantdate').val();
data.HiredbyReference = $('#hiredbyRef :selected').val() ? 1 : 0;
data.HiredbyReferenceName = $('#refePersonName').val();
data.BasicSalary = $('#basicSalary').val();
data.CurrentPicURL = $('.picture')[0].files; //this is my image file object
//data.EmpID = $('.HiddenID').val();
if (data.UserName && data.UPassword && data.OfficialEmailAddress && data.Departments && data.Designation && data.Role && data.IsAdmin && data.IsPermanent) {
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(data),
enctype: 'multipart/form-data',
beforeSend: function () {
$("#dvRoomsLoader").show();
},
complete: function () {
$("#dvRoomsLoader").hide();
},
success: function (data) {
var ID = parseInt(data);
if (ID > 0) {
//var id = data;
$(".HiddenID").val(data);
//var id = $(".HiddenID").val();
$('#official').css('display', 'block');
$('#official').html("Employees Official details added successfully...!");
$('#official').fadeOut(25000);
$("#dvRoomsLoader").show();
$('.empOfficialDetails').html("Update <i class='fa fa-angle-right rotate-icon'></i>");
}
else {
$('#official').find("alert alert-success").addClass("alert alert-danger").remove("alert alert-success");
}
},
error: function (ex) {
alert("There was an error while submitting employee data");
alert('Error' + ex.responseXML);
alert('Error' + ex.responseText);
alert('Error' + ex.responseJSON);
alert('Error' + ex.readyState);
alert('Error' + ex.statusText);
}
});
}
return false;
});
but in controller on running the code it passes null
public void EmployeeImage(HttpPostedFileBase file)
{
var allowedExtensions = new[] { ".Jpg", ".png", ".jpg", "jpeg" };
var fileName = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(file.FileName); //getting the extension(ex-.jpg)
byte[] bytes;
using (BinaryReader br = new BinaryReader(file.InputStream))
{
bytes = br.ReadBytes(file.ContentLength);
}
if (allowedExtensions.Contains(ext)) //check what type of extension
{
string name = Path.GetFileNameWithoutExtension(fileName); //getting file name without extension
string myfile = name + "_" + ext; //appending the name with id
var path = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/assets/img/profiles/employeeImages"), myfile); // store the file inside ~/project folder(Img)
file.SaveAs(path);
}
}
public int Emp_OfficialDetails(Employee emp)
{
//SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AmanraHRMS"].ConnectionString);
var con = DB.getDatabaseConnection();
SqlCommand com = new SqlCommand("sp_InsEmpOfficialDetails", con);
com.CommandType = CommandType.StoredProcedure;
#region Employee Official Details Insert Code block
com.Parameters.AddWithValue("#UserName", emp.UserName);
com.Parameters.AddWithValue("#pass", emp.UPassword);
com.Parameters.AddWithValue("#OfficialEmailAddress", emp.OfficialEmailAddress);
com.Parameters.AddWithValue("#Department", emp.Departments);
com.Parameters.AddWithValue("#Role", emp.Role);
com.Parameters.AddWithValue("#IsAdmin", Convert.ToBoolean(emp.IsAdmin));
com.Parameters.AddWithValue("#Designation", emp.Designation);
com.Parameters.AddWithValue("#ReportToID", emp.ReportToID);
com.Parameters.AddWithValue("#ReportTo", emp.ReportTo);
com.Parameters.AddWithValue("#JoiningDate", Convert.ToDateTime(emp.JoiningDate));
com.Parameters.AddWithValue("#IsPermanent", Convert.ToBoolean(emp.IsPermanent));
com.Parameters.AddWithValue("#DateofPermanancy", Convert.ToDateTime(emp.DateofPermanancy));
com.Parameters.AddWithValue("#IsActive", Convert.ToBoolean(emp.IsActive));
com.Parameters.AddWithValue("#HiredbyReference", Convert.ToBoolean(emp.HiredbyReference));
com.Parameters.AddWithValue("#HiredbyReferenceName", emp.HiredbyReferenceName);
com.Parameters.AddWithValue("#BasicSalary", emp.BasicSalary);
com.Parameters.AddWithValue("#CurrentPicURL", emp.CurrentPicURL);
#endregion
var file = emp.CurrentPicURL;
EmployeeImage(file);
var ID = com.ExecuteScalar();
com.Clone();
return Convert.ToInt32(ID);
}
and in my model class my Image datatype is as
public HttpPostedFileBase CurrentPicURL { get; set; }
I have no Idea what I am doing wrong If anyone who knows about this, your help is highly appreciated my friend
You can't use JSON.stringify to upload a file via AJAX. You need to use the FormData class.
Sending files using a FormData object | MDN
const data = new FormData();
data.append("UserName", $('#username').val());
data.append("UPassword", $('#userpass').val());
...
const file = $('.picture')[0].files[0];
data.append("CurrentPicURL", file, file.name);
...
$.ajax({
url: 'http://localhost:1089/api/Employee/EmpOfficialDetails',
type: "POST",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
...
NB: Unless you need to support Internet Explorer, you might want to use the Fetch API instead of AJAX. This can be much simpler, particularly when combined with async and await.
im working on ASP.NET MVC 4 project. well i already insert data into a SQL Server database using jQuery using a post method in .
Now im trying to insert data into 2 tables using the same view, my problem is that i can't passing multiple POST parameters to Web API Controller Method. here is my js function and my controller code, ill apreciate your help
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient},
success: function (data) {
if(data==0) {
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1) {
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
Controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient: dataClient},
success: function (data) {
if(data==0){
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1){
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
//controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
you did not add dataClient: dataClient in ajax.
so please add this.
Hope this will help you.
Im using Parse REST API + AngularJS and Im trying to be able to get more than 1000 items per query. I try to develop a recursive function and concatenate each query until I get all the data. My problem is that I am not able to concatenate the JSON objects successfully. Here is what I have:
$scope.getAllItems = function(queryLimit, querySkip, query) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
query.concat(data.results);
if(query.lenth == queryLimit) {
querySkip += queryLimit;
queryLimit += 100;
$scope.getAllItems(queryLimit, querySkip, query);
} else {
$scope.clients = query;
}
})
.error(function(data, status) {
alert("Error");
});
};
var myQuery = angular.toJson([]); //Am I creating an empty JSON Obj?
$scope.getAllItems(100,0, myQuery);
Is there any better solution to achieve this?
There may be better, more concise ideas available, but this is what I worked out for myself.
In my service ...
fetch : function(page, perpage) {
var query = // build the query
// the whole answer to your question might be this line:
query.limit(perpage).skip(page*perpage);
return query.find();
},
fetchCount : function() {
var query = // build the same query as above
return query.count();
},
In the controller...
$scope.page = 0; // the page we're on
$scope.perpage = 30; // objects per page
MyService.fetchCount().then(function(count) {
var pagesCount = Math.ceil(count / $scope.perpage);
$scope.pages = [];
// pages is just an array of ints to give the view page number buttons
for (var i=0; i<pagesCount; i++) { $scope.pages.push(i); }
fetch();
});
function fetch() {
return MyService.fetch($scope.page, $scope.perpage)).then(function(results) {
$scope.results = results;
});
}
// functions to do page navigation
$scope.nextPage = function() {
$scope.page += 1;
fetch();
};
$scope.prevPage = function() {
$scope.page -= 1;
fetch();
};
$scope.selectedPage = function(p) {
$scope.page = p;
fetch();
};
Then paging buttons and results in my view (bootstrap.css)...
<ul class="pagination">
<li ng-click="prevPage()" ng-class="(page==0)? 'disabled' : ''"><a>«</a></li>
<li ng-repeat="p in pages" ng-click="selectedPage(p)" ng-class="(page==$index)? 'active' : ''"><a>{{p+1}}</a></li>
<li ng-click="nextPage()" ng-class="(page>=pages.length-1)? 'disabled' : ''"><a>»</a></li>
</ul>
<ul><li ng-repeat="result in results"> ... </li></ul>
I fixed my recursive function and now its working. Here it is:
$scope.getAllItems = function(queryLimit, querySkip, query, first) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
if(first) {
query = data.results;
first = !first;
if(query.length == queryLimit) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
} else {
var newQ = data.results;
for (var i = 0 ; i < newQ.length ; i++) {
query.push(newQ[i]);
}
if(query.length == queryLimit + querySkip) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
}
})
.error(function(data, status) {
alert("Error");
});
};
Simply pushed each element to my empty array, also I was mutating queryLimit instead of querySkip in order to iterate through all the elements.
i want to return JSON from my controller and get it in my view .this is my code, when i debug it . goes to my controller and get value but in my j query code nothing happen .when i debug my j query code by firebug it dos not run the function(data). what is wrong in my code ?i want get object of part-booklet from server. its a row of data and add this row to my Telerik mvc grid .thanks in advance
its my contoroller code:
#region dynamic_add_row_to_grid
private PartBooklet GetPartBooklet( int sparepart ) {
return _PartBookletService.GetList().Where(m => m.SparePartCode == sparepart).FirstOrDefault();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetItems( int sparepart ) {
var PartbookletList = this.GetPartBooklet(sparepart);
return Json(PartbookletList, JsonRequestBehavior.AllowGet);
}
#endregion
and its jquery code:
$("#btnadd").button().click( function () {
alert("button");
var sparepartcode = $("#SparePartCode").val();
alert( sparepartcode );
$.getJSON("../Shared/GetItems", { sparepart: sparepartcode }, function( data ) {
alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
}).error( function () {
alert("JSON call failed");
});
$( function () {
$.ajaxSetup({
error: function (jqXHR, exception) {
if ( jqXHR.status === 0 ) {
alert('Not connect.\n Verify Network.');
} else if ( jqXHR.status == 404 ) {
alert('Requested page not found. [404]');
} else if ( jqXHR.status == 500 ) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror' ) {
alert('Requested JSON parse failed.');
} else if ( exception === 'timeout' ) {
alert('Time out error.');
} else if ( exception === 'abort' ) {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});
$("#btnadd").button().click( function () {
//alert("button");
var sparepartcode = $("#SparePartCode").val();
$.ajax({
url: "/Shared/GetItem?sparepart=" + sparepartcode,
type: 'GET',
success: function(a, b, data) {
//alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
},
error: function(jqXHR, textStatus, errorThrown) {
alert("JSON call failed");
},
// other options and setup ...
});
});
Note that in a successful ajax request, it's the 3rd parameter that contains the actual data you need.
Hi I have a small javascript function which dynamically filters my form:
// set up a new XMLHttpRequest variable
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
// if no request then throw up an alert window
if (!request)
alert("Error initializing XMLHttpRequest!");
// this function takes the island group value and sends it to the url as a get variable
function getIslandName(lang) {
var islandGroup = document.getElementById("id_island_group").value;
if (islandGroup == '') {
// if Not Specified re-selected then set data to null and bypass updatePage()
var data = null;
update_select($('select[name=island_name]'), data);
}
else {
var url = "../collections/find_island?island_group=" + escape(islandGroup);
// alert("Ready state is: " + request.readyState);
// alert("url: " + url);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
}
// what to do when http ready state changes
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200) {
// get response array
var data = JSON.parse(request.responseText);
update_select($('select[name=island_name]'), data);
}
// some error checking
else if (request.status == 404) {
alert("Request url does not exist");
}
else {
alert("Error: status code is " + request.status);
}
}
}
function update_select(select, data) {
// find and remove existing options
select.find('option').remove();
var optionText = document.getElementById("lang").innerHTML
select.append($('<option value>' + optionText + '</option>'));
// loop through results and append to select as options
for (var k in data) {
select.append($('<option value="'+data[k]+'">'+data[k]+'</option>'));
}
}
And my forms:
class SearchForm(forms.Form):
...
island_group = forms.ModelChoiceField(
required=False,
label=ugettext_lazy('Island Group'),
initial=None,
queryset=Localityonline.objects.values_list('islandgroup', flat=True).distinct('islandgroup').exclude(islandgroup=None).order_by('islandgroup'),
empty_label=ugettext_lazy("Not Specified"),
widget=forms.Select(attrs={"class":'searchfield', "onChange":'getIslandName()'})
)
island_name = forms.ChoiceField(
required=False,
label=ugettext_lazy('Island Name'),
initial=None,
choices=DEFAULT_CHOICES,
#queryset = Localitymayor.objects.values_list('islandname', flat=True).distinct('islandname').exclude(islandname="n/a").order_by('islandname'),
#empty_label=ugettext_lazy("Not Specified"),
)
...
The problem is, if the value of islandGroup is something like 'Española' (i.e latin characters) I get a status 500 error and the following Django error:
OperationalError: (1267, "Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='")
<WSGIRequest
path:/datazone/collections/find_island/,
GET:<QueryDict: {u'island_group': [u'Espa\ufffd']}>,
POST:<QueryDict: {}>,
COOKIES:{'__utma': '173650102.812455619.1337018914.1337629222.1337641044.38',
'__utmb': '173650102.4.10.1337641044',
'__utmc': '173650102',
'__utmz': '173650102.1337613083.36.2.utmcsr=darwinfoundation.org|utmccn=(referral)|utmcmd=referral|utmcct=/datazone/galapagos-research/search/',
'csrftoken': '7cac07481c8ff5762fac33bf0b3590da',
'sessionid': '4becce44a950091a3cf7d306633427b4'},
META:{'CSRF_COOKIE': '7cac07481c8ff5762fac33bf0b3590da',
'DOCUMENT_ROOT': '/home/darwinfo/public_html',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTP_ACCEPT': '*/*',
'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
'HTTP_CONNECTION': 'close',
'HTTP_COOKIE': 'csrftoken=c297f86b353937f52abc36af8b4d595a; csrftoken=7cac07481c8ff5762fac33bf0b3590da; sessionid=4becce44a950091a3cf7d306633427b4; __utma=173650102.812455619.1337018914.1337629222.1337641044.38; __utmb=173650102.4.10.1337641044; __utmc=173650102; __utmz=173650102.1337613083.36.2.utmcsr=darwinfoundation.org|utmccn=
...
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19',
'PATH': '/sbin:/usr/sbin:/bin:/usr/bin',
'PATH_INFO': u'/collections/find_island/',
'PATH_TRANSLATED': '/home/darwinfo/public_html/collections/find_island/',
'QUERY_STRING': 'island_group=Espa%F1ola',
'REDIRECT_QUERY_STRING': 'island_group=Espa%F1ola',
'REDIRECT_STATUS': '200',
'REDIRECT_UNIQUE_ID': 'T7rLMjIWL2YAAGS3N#sAAAET',
'REDIRECT_URL': '/datazone/collections/find_island/',
'REMOTE_ADDR': '157.100.37.112',
'REMOTE_PORT': '35245',
'REQUEST_METHOD': 'GET',
'REQUEST_URI': '/datazone/collections/find_island/?island_group=Espa%F1ola',
'SCRIPT_FILENAME': '/home/darwinfo/public_html/datazone/django.fcgi',
'SCRIPT_NAME': u'/datazone',
'SERVER_ADDR': '50.22.47.102',
'SERVER_PORT': '80',
'SERVER_PROTOCOL': 'HTTP/1.1',,
'SERVER_SOFTWARE': 'Apache',
'UNIQUE_ID': 'T7rLMjIWL2YAAGS3N#sAAAET',
'wsgi.errors': <flup.server.fcgi_base.OutputStream object at 0x1707ab90>,
'wsgi.input': <flup.server.fcgi_base.InputStream object at 0x16f2fad0>,
'wsgi.multiprocess': False,
'wsgi.multithread': True,
'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 0)}>
Any help would be much appreciated.
Check the collation type of each table, and make sure that they have the same collation.
After that check also the collation type of each table field that you have use in operation.
I had encountered the same error, and that tricks works .