I am sending an ajax call to another page. I want to get a value of a variable, lets call it x, back from that page on success. How can I do that. here is my ajax code
$.ajax({
type: 'POST',
url: 'myotherpage.php',
data: 'loginname=' + loginname ,
success: function(success) {
if(success == 1) {
//get the variable value here
} else {
//do nothing
}
}
});
Your other page should return json, which contains a status variable (1 for success, 0 for fail), and the variable or whatever data you need. Here's an example from a file I have here. It won't run of course, but should give you the idea.
Req = $.ajax({
type: 'POST',
data: this.data.filter,
url: this.data.DataURL+"listids",
dataType: 'json',
timeout: 5000,
cache: false,
error: function(){
UserNotify({class:'notify_alert', content:'Your request can\'t be completed at this time.<br />An external error has been encountered. Please wait a moment and try again.'});
},
success: function(o){
if ( 0==o.status ) {
if ( undefined == o.user_msg ) { o.user_msg = '';}
UserNotify({class:'notify_alert', content:'Your request can\'t be completed at this time.<br />'+o.user_msg});
} else {
if ( 0 < o.data.ids.length ) {
tli.data.update.ids = o.data.ids;
}
}
}
});
echo out the variable in your php file instead of "1" and have it return null when something is wrong.
$.ajax({
type: 'POST',
url: 'myotherpage.php',
data: 'loginname=' + loginname ,
success: function(success) {
if(success == '') {
// error alert
alert('Something went wrong. Reload the page and try again.');
} else {
alert(success); // alert the value from what you printed out in myotherpage.php
}
}
});
I don't know what you are trying to do but to give you an idea,
if(success == 1) {
// codes get executed here if myotherpage.php would display 1
// so I'm wondering how would you create a variable there...
// if you put anything other than just '1' in myotherpage.php, codes inside this "if" will not be excuted
//get the variable value here
} else {
//do nothing
}
in this,
success: function(data) {...} // "data" is the data being returned from the server
Related
I have a button on my new and edit views that sends a post request to my Letter controller through an Ajax call. If the Ajax call works perfectly in the new view, it throws a 404 error for my edit view.
Route:
post 'letters/ajax_send_test_botletter', to: 'letters#send_test_botletter', as: 'send_test_botletter'
The form is defined like this:
<%= form_for(letter, :html => {class: "directUpload", remote: true}) do |f| %>
The button triggering the Ajax call in the form:
<button class="cta3" id="send_test_letter">Send a test campaign to yourself</button>
Ajax call:
$('#send_test_letter').on('click', function(){
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: "/letters/ajax_send_test_botletter",
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
if(json['value'] == "No Recipient") {
$('#send_test_letter').css('display', 'none');
$('#save_test_user').css('display', 'block');
} else {
console.log("Success")
$('#confirmation_test_sent').html('Test successfully sent. Check your Messenger.')
}
$('form').unbind('submit');
});
return false; // prevents normal behaviour
});
});
My send_test_botletter method
def send_test_botletter
#message_content = params[:letter]['messages_attributes']['0']['content']
#button_message = params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_text'] if params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_text'] != ''
#button_url = params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_url'] if params[:letter]['messages_attributes']['0']['buttons_attributes']['0']['button_url'] != ''
#cards = params[:letter]['cards_attributes'] if params[:letter]['cards_attributes'].present? == true
#test_segment = Segment.where(core_bot_id: #core_bot_active.id, name: "test").first
#recipients = BotUser.where(core_bot_id: #core_bot_active.id, source: #test_segment.token)
if #recipients.exists?
send_message_onboarding if #message_content != '' and #button_message.present? == false
send_message_button_onboarding if #message_content != '' and #button_message.present? == true and #button_url.present? == true
send_card_onboarding if #cards
respond_to do |format|
format.json { render json: {"value" => "Success"}}
end
else
respond_to do |format|
format.json { render json: {"value" => "No Recipient"}}
end
end
end
I get the following error in the Chrome console for the edit view:
POST http://localhost:3000/letters/ajax_send_test_botletter 404 (Not
Found)
And in my Rails logs:
ActiveRecord::RecordNotFound (Couldn't find Letter with
'id'=ajax_send_test_botletter):
It seems it calls the Update method instead of the send_test_botletter method...
Any idea what's wrong here?
I found the trick. The problem was the PATCH method in the edit form.
I found a plugin in this discussion in order to modify the serialized data and change the method to "post":
$('#send_test_letter').on('click', function(){
$('form').submit(function() {
var valuesToSubmit = $(this).awesomeFormSerializer({
_method: 'post',
});
$.ajax({
type: "POST",
url: "/letters/ajax_send_test_botletter",
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
if(json['value'] == "No Recipient") {
$('#send_test_letter').css('display', 'none');
$('#save_test_user').css('display', 'block');
} else {
console.log("Success")
$('#confirmation_test_sent').html('Test successfully sent. Check your Messenger.')
}
$('form').unbind('submit');
});
return false; // prevents normal behaviour
});
});
(function ( $ ) {
// Pass an object of key/vals to override
$.fn.awesomeFormSerializer = function(overrides) {
// Get the parameters as an array
var newParams = this.serializeArray();
for(var key in overrides) {
var newVal = overrides[key]
// Find and replace `content` if there
for (index = 0; index < newParams.length; ++index) {
if (newParams[index].name == key) {
newParams[index].value = newVal;
break;
}
}
// Add it if it wasn't there
if (index >= newParams.length) {
newParams.push({
name: key,
value: newVal
});
}
}
// Convert to URL-encoded string
return $.param(newParams);
}
}( jQuery ));
form_for(letter... generates a different url and method depending whether or not the instance is persisted, defaulting to create and post or update and patch as appropriate.
When you hit submit, it's trying to hit this endpoint, before your listener kicks in. And in doing so, breaks the remaining js.
However, you can also provide url and method options to form_for. Try providing a blank url option and the correct method (form_for letter, ..., url: '', method: :post).
Alternatively, you could stop the default behaviour / propagation on form submission:
$('form').submit(function(e) {
e.stopPropagation() // Or could simply be `preventDefault()`, depending on your use case
...
// your AJAX
}
Able to test out these approaches?
Update
Your method is actually nesting a submit listener within the click one. Try the following:
$('#send_test_letter').on('click', function(e){
e.stopPropagation()
var $form = $(this).closest('form')
var valuesToSubmit = $form.serialize();
$.ajax({
type: "POST",
url: "/letters/ajax_send_test_botletter",
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
if(json['value'] == "No Recipient") {
$('#send_test_letter').css('display', 'none');
$('#save_test_user').css('display', 'block');
} else {
console.log("Success")
$('#confirmation_test_sent').html('Test successfully sent. Check your Messenger.')
}
return false; // prevents normal behaviour
});
});
I have a problem with populating a Webgrid from an Ajax call.
I have followed the example as showed in the following thread: mvc3 populating bind webgrid from ajax however, that did not yield any results.
When I run the website, I always get the message: "Error: undefined".
when debugging the code, I am quite sure that the problem lies in the fact that the return PartialView is the problem, as my data object in the ajax success method does not get filled with data.
Here are the examples of my code:
Ajax call:
$.fn.getCardResult = function (leerling, kaart) {
$.ajax({
type: "GET",
url: '#Url.Action("GetResults","Kaarten")',
data: { leerlingID: leerling, cardID: kaart },
cache: false,
success: function (data) {
console.log(data);
if (!data.ok) {
window.alert(' error : ' + data.message);
}
else {
$('#card').html(data);
}
}
});
}
Partial View call:
<div class="card-content" id="card">
#{
if(Model.Kaart != null && Model.Kaart.Count > 0)
{
#Html.Partial("_Kaarten")
}
else
{
#: Er zijn geen kaarten beschikbaar.
}
}
</div>
Partial View:
#model List<ProjectCarrousel.Models.KaartenModel>
#{
var grid = new WebGrid(source: Model,ajaxUpdateContainerId: "card",
defaultSort: "Topicname");
grid.GetHtml(
tableStyle: "webgrid",
columns: grid.Columns(
grid.Column("Topicname", "Topic"),
grid.Column("Taskname", "Taken"),
grid.Column("Taskpoints", "Punten"),
grid.Column("Grades", "Resultaat"),
grid.Column("Date", "Datum"),
grid.Column("Teachercode", "Paraaf Docent")
)
);
}
Controller code:
public ActionResult GetResults(int leerlingID, string cardID)
{
try
{
int Ovnumber = leerlingID;
string CardId = cardID;
List<KaartenModel> kaartlijst = new List<KaartenModel>();
IEnumerable<topic> topics = _db.topic.Include("tasks.studenttotask").Where(i => i.CardID == CardId);
foreach (topic topic in topics)
{
foreach (tasks task in topic.tasks)
{
KaartenModel ka = new KaartenModel();
ka.Topicname = task.topic.Topicname;
ka.Taskname = task.Taskname;
ka.Taskpoints = task.Taskpoints;
ka.Ranks = task.Ranks;
ka.Date = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Date).SingleOrDefault();
ka.Grades = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Grades).SingleOrDefault();
ka.Teachercode = task.studenttotask.Where(i => i.Ovnumber == Ovnumber).Select(d => d.Teachercode).SingleOrDefault();
kaartlijst.Add(ka);
}
}
KVM.Kaart = kaartlijst;
return PartialView("_Kaarten", KVM.Kaart);
}
catch (Exception ex)
{
return Json(new { ok = false, message = ex.Message });
}
}
If anyone could help it would be greatly appreciated.
UPDATE
After fiddling about a bit I found a solution that worked for me. Below is a snippet of an updated Ajax Call:
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
The solution I found was too make the Success method in another way. This made sure that the Partial View rendered properly. Below is the Ajax call snippet.
$.ajax({
url: '#Url.Action("GetAjaxCall","Home")',
contentType: 'application/html; charset=utf-8',
type: 'GET',
dataType: 'html',
data: { id: id },
})
.success(function (result) {
$('#sectionContents').html(result);
})
.error(function (xhr, status) {
alert(xhr.responseText);
});
I have a page with two links that open two different modals, the "forgotten password" link opens the "forgotten password" modal and the "tell-a-friend" link opens the "tell-a-friend" modal.
Both modals contain forms that can be submitted.
The problem is if I open the first modal and submit it or close it, I cannot submit the second modal.
I can open the second modal, but I cannot submit it.
Please advise what the problem could be!
Here below is the javascript code that resides in separate javascript file, which is then imported into the HTML file. It is not inline javascript, if that would matter.
[code]
var forgottenPasswordDiv;
var tellAFriendDiv;
function clearErrorMessages() {
$('#errorMessage').text("");
}
function openForgottenPassword() {
forgottenPasswordDiv = $('#forgotten-password');
$('#forgotten-password').load("/Templates/include/new/ajax/modal/forgottenPassword.jsp")
.dialog(
{
autoOpen:false,
modal:true,
position:'left+35% top+20%',
width:'330',
height:'auto'
}
);
$('#forgotten-password').dialog('open');
}
function closeForgottenPassword() {
forgottenPasswordDiv.dialog("close");
}
function submitForgottenPassword() {
clearErrorMessages();
var email = $('#email').val();
if (email == null || email == '') {
$('#errorMessage').text("Please enter your user name or email");
} else {
clearErrorMessages();
/* Ajax Post */
var formData = $("#forgottenPasswordForm").serialize();
$.ajax({
type: "GET",
url: "/Templates/include/new/ajax/forgottenPassword.jsp",
data: formData,
success: function(data) {
if (data.error != null) {
$("#errorMessage").text(data.error);
} else {
$('#forgottenPasswordForm , .info').fadeOut(1000);
$("#successMessage").text(data.success);
$("div").removeClass('display-none');
}
},
dataType: 'json'
});
}
}
function openTellAFriend(gunId) {
tellAFriendDiv = $('#tell-a-friend');
$('#tell-a-friend').load("/Templates/include/new/ajax/modal/tellAFriend.jsp?id=" + gunId)
.dialog(
{
autoOpen:false,
modal:true,
position:'center top+10%',
width:'330',
height:'auto'
}
);
$('#tell-a-friend').dialog('open');
}
function closeTellAFriend() {
tellAFriendDiv.dialog("close");
}
function submitTellAFriend() {
clearErrorMessages();
var yourname = $('#yourname').val();
var errorMessage = "";
if (yourname == null || yourname == '') {
errorMessage += "Please enter your name<br />";
}
if (errorMessage != '') {
$('#errorMessage').html(errorMessage);
} else {
clearErrorMessages();
/* Ajax Post */
var formData = $("#tellAFriendForm").serialize();
$.ajax({
type: "GET",
url: "/Templates/include/new/ajax/tellAFriend.jsp",
data: formData,
success: function(data) {
if (data.error != null) {
$("#errorMessage").text(data.error);
} else {
$("#tellAFriendForm").fadeOut(1000);
$("#successMessage").text(data.success);
$("div").removeClass('display-none');
}
},
dataType: 'json'
});
}
}
[/code]
The ui-dialog widget will stay in the DOM as a hidden element even after the dialog is closed.
So, in order to isolate your two dialog functionalities from each other I'd suggest that you call:
forgottenPasswordDiv.dialog("destroy")
in your "closeForgottenPassword" function and
tellAFriendDiv.dialog("destroy")
in your "closeTellAFriend" function.
This will return the dialog back to its pre-init state (which is not harmful at all because you reinit it in your "open" functions.)
In my controller action i initialize a session of array and inserting values. These values are coming from the client side through ajax, so the page is not refreshed while inserting these values to an array.But suprisingly every time it iniatialize a new session instead of inserting to the same defined session. Here is my code
controller
def receive_tags
parser = Yajl::Parser.new
#hash = parser.parse(request.body.read)
log=Logger.new(STDOUT)
log.error(#hash)
session[:tags]||=[]
session[:tags] << #hash["tag"]
unless session[:tags].empty?
log.error(session[:tags] ) #this keeps printing the current value i was expecting it to print a list of values including the previous
end
render :nothing=>true
end
Ajax
var myobj={tag:"mytag"};
$.ajax({
url: 'ips/receive_tags',
type: 'post',
contentType: 'application/json; charset=UTF-8',
accept: 'application/json',
dataType: 'json',
data:JSON.stringify(myobj),
success: function(res) {
if (res.ImportResponse !== void 0) {
console.log('Success: ' + res);
} else if (res.Fault !== void 0) {
console.log('Fault: ' + res);
}
},
error: function() {
console.error('error!!!!');
}
});
This sounds like the browser isn't saving cookies, which would explain the behavior you are seeing where the session is reinitialized every time. To confirm this, you can do
print "Session ID: #{request.session_options[:id]}"
in your action and see if the session id changes for each request. If it does, check your browser privacy settings and see if it is saving any cookies.
Finally i figured it out, The problem is i wasn't setting the request header for the token before sending ajax call so Rails was receiving data without the token, thus kept assuming it is a new object for every request.You can read more here.To set the request header add
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
Below is my ajax function that works
var myobj={tag:"mytag"};
$.ajax({
url: 'ips/receive_tags',
type: 'post',
contentType: 'application/json; charset=UTF-8',
accept: 'application/json',
dataType: 'json',
data:JSON.stringify(myobj),
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
success: function(res) {
if (res.ImportResponse !== void 0) {
console.log('Success: ' + res);
} else if (res.Fault !== void 0) {
console.log('Fault: ' + res);
}
},
error: function() {
console.error('error!!!!');
}
});
I am trying to make an AJax call to a controller method the parameter is null no matter what I try. I have followed all the similar SO posts but to no avail. Sorry if the answer is there, I cant find it. The code I have is...
Ajax Call
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
type: 'POST',
dataType: 'json',
data: JSON.stringify({guid: sguid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Controller Method
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
List<DeviceSoftware> ldevice = new List<DeviceSoftware>();
Guid i = Guid.Parse(guid);
ReportMethods reportingMethods = new ReportMethods();
ldevice = reportingMethods.GetNonCompliantApplicationReport(CompanyId);
DeviceSoftware ds = ldevice.Find(x => x.Device.Guid == i);
List<DeviceApplication> da = new List<DeviceApplication>();
if (ds != null)
{
da = ds.DeviceApplications;
}
return Json(da, JsonRequestBehavior.AllowGet);
}
The method is being hit its just guid is alway null. sguid does hold the data I am trying to pass.
Can someone tell me what I am missing?
Against everything I read I changed
data: JSON.stringify({guid: sguid}),
To
data: {guid: sguid},
Now working.
Fred,
You need to make GetBlacklistedSoftwareItems a post method....
try this...
[HttpPost]
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
Small changes needs to be done.
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
contentType: "application/json; charset=utf-8" ,//This is very important
type: 'POST',
dataType: 'json',
Data: JSON. stringify ({guild: squid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Add the contentType: "application/json; charset=utf-8" , to the $.Ajax Call.
:)