I am using codeigniter 3 and I am new for codeigniter. I want to ask that which method is more suitable to pass data from view to controller, using jquery or <form action="controller/method">
I am trying to pass data using jquery but it does not giving any response and no error will be shown. Jquery code is given:
function registration()
{
var txtemail = document.getElementById("email").value;
$.post("<?php echo site_url('Home/registration'); ?>", {checkEmail: txtemail, action: "registerUser"},
function(data) {
var result = data + "";
if (result.lastIndexOf("Success") > -1) {
} else {
var txtUser = document.getElementById("username").value;
var txtContact = document.getElementById("contact").value;
var txtEmail = document.getElementById("email").value;
var txtpincode = document.getElementById("pincode").value;
var txtCity = document.getElementById('city').value;
var txtState = document.getElementById('state').value;
var txtCountry = document.getElementById("country").value;
var txtPackage = document.getElementById("package").value;
var registerMstData = new Array();
registerMstData[0] = txtUser;
registerMstData[1] = txtContact;
registerMstData[2] = txtEmail;
registerMstData[3] = txtpincode;
registerMstData[4] = txtCity;
registerMstData[5] = txtState;
registerMstData[6] = txtCountry;
registerMstData[7] = txtPackage;
$.post("<?php echo site_url('Home/registration') ?>", {pageData: registerMstData, action: "save"},
function(data) {
var result = data + "";
window.alert(result);
})
.fail(function(req, status, err) {
console.error('Error : ' + err + " status : " + status + " request " + req.toString());
alert('Error : ' + err + " status : " + status + " request " + req.toString());
});
}
});
}
What I am doing wrong I don't understand? Please help.
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload.
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
It all depends on how you want it to be
Update
For ajax, you can use
$.ajax({
url: 'your url',
data: {
format: 'json'
},
error: function(err) {
// handle error here
},
data: yourData
success: function(data) {
// handle success here
},
type: 'POST'
});
Related
I have written code in an ASP.NET Core 6 controller and calling this from view. This code gives response to my view but I don't know how to parse the data in view.
Previously I was using JsonrequestBehaviour.Allowget which is now deprecated in .NET 6. Please help me for better appraoch of json call which can return any dynamic object.
Here is my controller code:
public IActionResult GetAccountLevelAndCode(Int32 GroupAccountID, Int32 Companyid)
{
string AccountLevels = ""; string Returnerror; string ReturnBranches;
DataTable AL = new GetDataClass().GetAccountNoAndAndLevels(GroupAccountID, Companyid, out Returnerror);
//a = (GLChartOFAccountModel)AL.Rows[0].ConvertDataRowToObject(a);
string Sql = #"select cab.BranchID from GLChartOFAccount ca inner join GLChartOfAccountBranchDetail cab on ca.GLCAID=cab.GLCAID where cab.GLCAID=" + GroupAccountID;
DataTable dt = new DataTable();
dt = StaticClass.SelectAll(Sql).Tables[0];
AccountLevels = JsonConvert.SerializeObject(AL);
ReturnBranches = JsonConvert.SerializeObject(dt);
Returnerror = JsonConvert.SerializeObject(Returnerror);
return Json(new { AccountLevels, ReturnBranches, Returnerror });
}
Following is my view call and response allocation:
function GetAccountNoandLevel() {
var DATA={"GroupAccountID" : $('#isParent').val(), Companyid : #Model.CompanyID }
var execCode = true;
$.ajax({
async: false,
type: "POST",
url: "/GLChartOFAccount/GetAccountLevelAndCode",
data: DATA,
dataType: "json",
success: function (data) {
try {
var c = JSON.parse(data.AccountLevels)
var b = JSON.parse(data.ReturnBranches)
var er = JSON.parse(data.Returnerror)
if (b.length>0) {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = true;
});
var dataarray = '';
for (var i = 0; i < b.length; i++) {
dataarray += b[i]["BranchID"] + ',';
}
dataarray = dataarray.replace(/,\s*$/, "");
var data = dataarray.split(",");
$("#BrachIDs").val(data);
$("#BrachIDs").change();
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$("#BrachIDs option").filter("[value='" + data[i] + "']").attr('disabled', false);
}
}
}
else {
$("#BrachIDs option").each(function () {
var idParent = $(this).parent().attr("id");
this.disabled = false;
});
$("#BrachIDs option:selected").removeAttr("selected");
}
if (ShowErrorOK(er)) {
$('#GLCode').val('');
}else{
RowToFillValues(c)
}
} catch (e) {
//console.log(e + " GetAccountNoandLevel "); document.getElementById("DisplayErrorMessage").innerText = e.message; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log(e + " GetAccountNoandLevel "); console.log(e.message)
}
},
error: function (err) {
//console.log(err.responseText); document.getElementById("DisplayErrorMessage").innerText = "AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details"; $('#btnTriggerMessage').click(); execCode = false; return false;
console.log("AJAX error in request: " + JSON.stringify(err.statusText + " " + err.status) + " GetAccountNoandLevel::Unable To Get Details")
}
});
if (execCode) {
}
}
The response data is showing undefined...
you don't need serialize and parse manually, it will be done automaticaly
return new JsonResult(new { AccountLevels=AL, ReturnBranches=dt, Returnerror= Returnerror });
and ajax
var c = data.AccountLevels;
var b = data.ReturnBranches;
var er = data.Returnerror;
I am trying to parse Bing Search API Version 7 JSON using the following code, but not sure what I am doing wrong. Would like to parse "name" and "url", my code is below.
Bing JSON Results are at the following URL -> http://52.15.219.114/bing2.php?q=freebsd&s=10&p=0&m=en-us
var e = escape($('#book').val());
var pg = 10;
var limit = 0;
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:pg, p:limit },
success: function(data) {
len = data.webPages.value.length
for (i=0; i<len; i++ ){
results += "<p><a href='" + data.webPages.value[i].url + "'>" + data.webPages.value[i].name + "</a>: " + data.webPages.value[i].snippet + "</p>";
}
$("#bookout").html(results);
},
error: function() {
// console.log(data);
}
});
Below is a fix for parsing the Bing Search JSON API.
var e = escape($('#book').val());
var pg = 10;
var limit = 0;
$.ajax({
url: uri,
method: "GET",
data: { q:e, s:pg, p:limit },
success: function(data) {
var obj = JSON.parse(data)
var ocean = obj.webPages.value; //client prop is an array
for(var i = 0; i < ocean.length; i++){
//alert(ocean[i].name);
//FORMAT RESULTS
var ocean_format = '<div><div>' + '' + ocean[i].name + '</div><div>' + ocean[i].snippet + '</div><div class="text-secondary">' + ocean[i].displayUrl + '</div></div>';
$("#bookout").append(ocean_format);
}//END SEARCH RESULTS
},
error: function() {
// console.log(data);
}
});
I get this JSON from DeviceNewController
public function index(Request $request)
{
$device_new = Device_new::with(['device']);
return Device_new::all()->toJson();
}
And when I wrote AJAX in view blade, it show me data from DB in console.
<script>
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
console.log(newdev.responseText);
};
newdev.send();
</script>
But I need to pass it in Leaflet script and write all data on map (coordinates, markers, device info)
When I set all in one script, there is no data in console, I can not fix it.
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
var coordinates = newdev.responseText;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
};
};
newdev.send();
Did i make a mistake somewhere, is this correct???
You miss understood Ajax. Ajax is a function from JQuery, a JS library.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
You have to add the JQuery library to your source, then you can create a Ajax call.
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({url: "/devices_new", success: function(result){
//result = JSON.parse(result); // If your result is not a json Object.
var coordinates = result;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
}
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
I make it on this way, and its working.
<script>
$(document).ready(function() {
$.ajax({
/* the route pointing to the post function */
url: '/device_new',
type: 'GET',
data: {
message: $(".getinfo").val()
},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function(data) {
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
</script>
I just started using the twitch kraken api and I have a few questions.
Whenever I attempt to get a JSON object there is no response. I am attempting to run this function through Amazon AWS Lambda, and don't have access to a console.
In the code below my callback function will always print out "SUCCESS got streamers ERROR". I am pretty certain right now the "ERROR" comes from my initial setting of result.
How come result does not get changed into the proper JSON?
I have used postman and it returns the proper thing with the query and param, and headers:
function getJSON(callback){
var result = "ERROR";
request.get(url(games[0]),function(error,response,body){
console.log("requested for url: " + url(games[0]));
var d = JSON.parse(body);
result = d.streams[0];//.channel.display_name;
// for(var i = 0; i < limit; i++){
// streamers.push(d.streams[i].channel.display_name)
// }
streamers.push(result);
});
if (streamers.length < 0){
callback("ERROR");
}else{
callback("SUCCESS got streamers " + result);
}
}
function url(game){
return {
url: "https://api.twitch.tv/kraken/streams/",//twitchlimit,
qs : {
'game' : 'overwatch',
'limit' : 2
},
headers: {
'Client-ID': clientID,
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
}
};
}
I think your streamers code
if (streamers.length < 0){
callback("ERROR");
}else{
callback("SUCCESS got streamers " + result);
}
should be included in the request callback because currently it's not waiting for the request to finish, it's just carrying on so therefore the value of result will not change. Also the array length cannot be less than 0 so it will always go to the else and say "SUCCESS got streamers ERROR"
Thank you guys for the suggestions. I did have a few oversights and attempted to fix them.
I have implemented you suggestions and it seems to have worked a bit. I ended up putting the json.parse into a try/catch block, and moved the if/else statements inside the getJSON method. However, now I don't get any output.
This is how I am invoking the getJSON method:
function handleGameResponse(intent,session,callback){
//gets the game
var game = intent.slots.game.value;
if (!games.includes(game)){
var speechOutput = "You asked for: " + intent.slots.game.value;
//var speechOutput = "You asked for: " + games[game] + " That game is currently not an option. These are your current options: " + arrayToString(games)
var repromptText = "Please ask one from the current options.";
var header = "Invalid Game";
}else {
getJSON(function(data){
if(data !== "ERROR"){
var speechOutput = data; //capitalizeFirst(game) + " top three streamers are: " + arrayToString(streamers) + '.';
var repromptText = "Do you want to hear more about games?";
var header = capitalizeFirst(game);
}else{
var speechOutput = "I'm sorry, something went wrong and I could not get the streamers.";
}
//speechOutput = data;
});
//speechOutput = games[0] + " games[0], game= " + game; //this executes so the getJSON isn't executing
}
var shouldEndSession = false;
callback(session.attributes,buildSpeechletResponse(header,speechOutput,repromptText,shouldEndSession));
}
Does the above execute the same way? As in the shouldEndSession and callback execute before the getJSON has time to give a response?
For ref, this is the getJSON method now:
function getJSON(callback){
var result = "ERROR";
request.get(url(games[0]),function(error,response,body){
try{
var d = JSON.parse(body);
} catch (err){
callback("Sorry, something seems to have malfunctioned while getting the streamers");
}
result = d.streams[0].channel.display_name;
// for(var i = 0; i < limit; i++){
// streamers.push(d.streams[i].channel.display_name)
// }
streamers.push(result);
if (streamers.length <= 0){
callback("ERROR");
}else{
callback("SUCCESS got streamers " + result);
}
});
}
I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.
I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>