Sending values of a form with ajax via post - javascript

im trying to send values in a form via POST in ajax, how do i capture them in send them, this is wat i have now while in GET
function test(ans_field_uuid){
var result = "";
var url="ajax_pages/remove_answer_field_ajax.php"
url += '?uuid=' + ans_field_uuid;
$.get(
url,
function (data) {
result = data;
}
)
.success(function () {
if (result != "") {
addTableRow('tb_add_field', result);
$('#ajaaxDiv').html(result);
}
})
.complete(function () {
$('#img_create_subcat').hide();
$('#dialog').dialog('close');
})
.error(function () {
alert('An error has occurred.');
});
return false;
}

since you already use jQuery
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
data: name and location are your POST variable.
You can fetch the POST variable in this example in some.php with
$_POST["name"]
which equals "John"
If you want to receive something then like "Hello".
Inside your some.php
echo "Hello";
and it will be send to your ajax function as response in your done function as variable msg

Documentation for jQuery post
// ...
var url = "ajax_pages/remove_answer_field_ajax.php";
$.post( url, "uuid=" + ans_field_uuid, function (data) {
result = data;
}
// ...

Related

AJAX Callback Not Showing Success Message - ASP.NET MVC C#

I have some AJAX code in my JavaScript which is not showing any success or failure alert.
function AttemptHouseViewingAppointment(house) {
var imgOfHouse = $(house).attr("value");
$.ajax({
type: "POST",
url: '#Url.Action("AttemptHouseViewingAppointment", "Viewing")',
dataType: "json",
data: ({
userId: #Model.UserId,
appointmentKey: '#Model.Key',
chosenHouse: imgOfHouse
}),
success: function (data) {
alert(data);
if (data.success) {
alert(data.message);
} else { alert(data.Message) }
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
The above function is called when I click an image on the screen. This part works fine as I have set a breakpoint on my ASP controller and I can see the relevant action being called. C# code below:
public ActionResult AttemptHouseViewingAppointment(int userId, string appointmentKey, int chosenHouse)
{
string selecteHouseName = $"./house-code-icons/{chosenHouse}.png";
var house =
_ctx.houses.Where(x => x.HouseID == userId && x.Icon == chosenHouse)
.FirstOrDefault() ?? null;
if(house != null)
{
var member = _ctx.User.FirstOrDefault(x => x.Id.Equals(userId));
_ctx.Appointments.Add(new ViewingModel
{
House = chosenHouse,
UserId = userId
});
_ctx.SaveChanges();
return Json(new { success = true, message = "Appointment Confirmed!" });
}
else
{
return Json(new { success = false, message = "Sorry, a booking has already been made!" });
}
}
Even though, the return Json lines are being hit and returned to the page, there is no alert popup on my page to let user know if success or not. Please let me know if any questions.
Thanks
Add the done function to the end of Ajax
$.ajax({
.
.
.
}).done(function( response ) {
alert(response);
...
});

Why e.status is getting as undefined in success function of ajax request?

I am getting my reponse as {"status":true}. But when I do console.log(e.status) I am getting as undefined.
When I do console.log(e) I get {"status":true}
This is my ajax request
$("#msgfrm").on("submit", function(e) {
event.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.ajax({
url: 'ajaxinsert.php',
method: 'POST',
data: {
name: name,
email: email
},
success: function(e) {
console.log(e);
console.log(e.status);
if (e.status === 'true') {
alert("success");
} else {
alert("Fail");
}
}
});
});
Please tell me what is my error??
It is because you are getting result as string. Try parsing it before using it.
success:function(e){
var obj=jQuery.parseJSON(e);
alert(obj);
alert(obj.status);
}

How to pass hidden field value via ajax to codeigniter controller

I have a view file which contains a button (link):
<a href id="savebutton" class="btn btn-warning">Save</a>
Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.
echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));
These hidden fields translate to:
<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">
Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.
My JS file looks like this:
$(function() {
var postData = {
"userid" : $("input.userid").val(),
"vacancyid" : $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
cache: false,
type: 'POST',
url: "<?php echo base_url();?>dashboard/vacancy/saveVacancy",
contentType: 'application/json',
dataType: 'text'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function(data) {
alert(data); // plausible [Object object]
//alert(data[0]); // plausible data
console.log(data); // debug as an object
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
And my controller looks like this (it is not doing much because it doesn't return anything):
public function saveVacancy() {
//$this->load->model('user/usersavedvacancies_model');
/*$data = array(
'userid' => $this->input->post('userid'),
'vacancyid'=>$this->input->post('vacancyid')
);*/
echo $this->input->post('userid');
}
Minor changes to javascript
$(function () {
var postData = {
"userid": $("input.userid").val(),
"vacancyid": $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
type: 'POST',
url: "<?php echo base_url('dashboard/vacancy/saveVacancy);?>",
dataType: 'json'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function (data) {
console.log(data); // debug as an object
if (data.result === 'success') {
alert("Yeah, it saved userid " + data.userid + " to vacancy id " + data.vacancyid);
}
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
});
In the controller
public function saveVacancy()
{
//assigning a more useable object name to the model during load
$this->load->model('user/usersavedvacancies_model', 'save_vacancy');
$data = array(
'userid' => $this->input->post('userid'),
'vacancyid' => $this->input->post('vacancyid')
);
//send data to model and model returns true or false for success or failure
$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it
$result = $saved ? "success" : "failed";
echo json_encode(array('result' => $result, 'userid' => $data['userid'], 'vacancyid' => $data['vacancyid']));
}
You need to understand that $.ajax takes two methods i.e GET and POST and from the documentation you can see that default method is GET so Since you have not defined method as GET/POST probably the method is taken GET so first change define ajax method to POST as well as you need to be clear about dataType of ajax it may be one of JSON/html and default is json.
$.ajax({
method: "POST",
url: url,
data: data,
dataType:'html'
});
I guess this helped you can learn detail from
Learn more.

How to redirect in ajax after successfully post of data

I am submitting form data using Ajax and they are successfully saved in the database and I am able to alert the response data. I now want to use the returned data as response to call another function using Ajax and pass them as parameters so that to the called function they can be used to fetch data and and display them on the web page.
The problem is that when the data have been alerted, the function I call using Ajax is not responding even when I use some functions like window.location.href, window.location.replace, window.location.reload they are not executed
Here is the sample code
submitHandler: function(form) {
/*errorHandler.hide(); */
var el = $(div);
el.block({
overlayCSS: {
backgroundColor: '#fff'
},
message: '<i class="fa fa-refresh fa-spin"></i>',
css: {
border: 'none',
color: '#333',
background: 'none'
}
});
/*Set off for database validation */
$('#name1').removeClass('has-error');
$('#name1 .help-block').empty();
$('#date1').removeClass('has-error');
$('#date1 .help-block').empty();
/*end database validation */
/*ajax options */
var options = {
/*target: '#output2', target element(s) to be updated with server response */
success: function(data, textStatus, XMLHttpRequest) {
el.unblock();
if (!data.success) {
/*append error message on the form for each control and database validation*/
console.log(data);
if (data.errors.name1) {
$('#name1').addClass('has-error');
$('#name1 .help-block').html(data.errors.name1);
}
} else {
var business_id = data.business_id;
var bnm_app_id = data.bnm_app_id;
var name = data.name;
var doc = data.doc;
alert(business_id);
alert(bnm_app_id);
alert(name);
alert(doc);
if (window.XMLHttpRequest) {
myObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
myObject = new ActiveXObject('Micrsoft.XMLHTTP');
myObject.overrideMimeType('text/xml');
}
myObject.onreadystatechange = function() {
data = myObject.responseText;
if (myObject.readyState == 4) {
//document.getElementById('step-2').innerHTML = data;
window.location.reload(true);
}
}; //specify name of function that will handle server response........
myObject.open('GET', '<?php echo base_url()."bn_application/register";?>?bnm_app_id=' + bnm_app_id + '&doc=' + doc + '&business_id=' + business_id + '&name=' + name, true);
myObject.send();
}
},
error: function(xhr, textStatus, errorThrown) {
el.unblock();
if (xhr.responseText === undefined) {
$.gritter.add({
/* (string | mandatory) the heading of the notification */
title: 'Connection timed out',
class_name: 'gritter-black'
});
} else {
var myWindow = window.open("Error", "MsgWindow", "width=900, height=400");
myWindow.document.write(xhr.responseText);
}
/*clear controls that do not need to keep its previous info */
},
url: home + 'bn_application/save_clearance_name',
/* override for form's 'action' attribute*/
data: {
name1_percent: name1_percent
},
type: 'post',
/* 'get' or 'post', override for form's 'method' attribute*/
dataType: 'json',
/* 'xml', 'script', or 'json' (expected server response type)*/
beforeSend: function() {
},
uploadProgress: function(event, position, total, percentComplete) {
},
complete: function() {
}
};
/*submit form via ajax */
$('#bn_clearance').ajaxSubmit(options);
}
If i understand you right , you need something like this ?
$.ajax({
type: "GET",
url: baseUrl + 'api/cars',
success: function (firstResponse) {
$.ajax({
type: "GET",
url: baseUrl + 'api/cars/' + firstResponse[0].Id,
success: function (secondResponse) {
window.location.href = secondResponse[0].Make;
}
});
}
});
You can use window.open function
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
window.open("http://www.w3schools.com", "_self");
}});
});
You should put your redirecting url in success function of ajax. (if you are using jQuery). Because javascript runs codes asynchronously and probably your code tries to run before you get response from request.

How do I get the right $.ajax data type

could you please help with this. I have the following javascript:
$('form').click(function (e)
{
if (e.target.getAttribute('id') === 'SubmitAddLevel')
{
var parent = $('#' + e.target.getAttribute('attr')),
var Data = [];
parent.find('.input').children().each(function (i, e)
{
Data.push(e.getAttribute('id') + ":" + e.value);
console.log(Data);
});
$.ajax({
type: "POST",
url: 'AjaxControls.aspx/CreateUserLevel',
//data: Data, //.join(','),
dataType: "text",
contentType: "application/json; charset=utf-8",
//error: function (er) { alert(er); },
success: function (response)
{
if (response.d === "true")
{
$("#ErrorDivAddLevel").html('Level created successfully!').fadeIn('slow');
}
else
{
$("#SuccessDivAddLevel").html('Level creation failed!').fadeIn('slow');
}
},
});
}
The result of 'Data' I got on the console is :["LevelNameAddLevel:Admin", "PriviledgeIDAddLevels:|1|2|3|4|5|6|7|"]. How do I convert this to what ajax will pass to my web menthod?
Here is the web method
<WebMethod(EnableSession:=True)>
Public Shared Function CreateUserLevel(userLevel As String, userPriviledges As String) As String
return "true"
end function
I think your Data should look something more like this:
[{"LevelNameAddLevel":"Admin"}, {"PriviledgeIDAddLevels":"|1|2|3|4|5|6|7|"}]
So you have key / value pairs inside of an array. In the request, you should then be able to fetch the data via the keys in the request.
But I'm not quite sure what this is supposed to mean : "|1|2|3|4|5|6|7|"

Categories

Resources