I am using JS to submit data without loading the page and it is working fine, on response i am trying to send JSON which looks like this
{"mes":"<div class=\"alert alert-success\">Your goal has been updated.<\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"}
There are two items in the JSON response mes and graph_data. Now how can i make use of graph_data and mes seperately?
If I do this alert(data); this shows the above JSON response
But if I do the following I cant get them to alert seperately.
alert(data.graph_data);
alert(data.mes);
I will really appreciate if anyone can guide me on how to separate the two.
Update
This is the JS i am using to send and retrieve data on click of a button
$('#goalgraphdatasubmit').click(function () {
$('#goalgraphupdateform').submit();
});
$('#goalgraphupdateform').submit(function (e) {
"use strict";
e.preventDefault();
document.getElementById("goalgraphdatasubmit").innerHTML = "saving..";
var post = $('#goalgraphupdateform').serialize();
var action = $('#goalgraphupdateform').attr('action');
$("#holiday_goal_message").slideUp(350, function () {
$('#holiday_goal_message').hide();
$.post(action, post, function (data) {
$('#holiday_goal_message').html(data);
document.getElementById('holiday_goal_message').innerHTML = data;
$('#holiday_goal_message').slideDown('slow');
document.getElementById("goalgraphdatasubmit").innerHTML = "Submit";
alert(data);
if (data == '<div class="alert alert-success">Your goal has been updated.</div>') {
//$('#divGoal').load('dashboard-goals.php');
$("#holiday_goal_message").hide(2000);
updatetestGraph();
}
});
});
});
Use Like
var data = JSON.parse('{"event1":{"title":"My birthday","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "},"event2":{"title":"My birthday again","start":"12\/27\/2011 10:20 ","end":"12\/27\/2011 00:00 "}}');
arr = []
for(var event in data){
var dataCopy = data[event]
for(key in dataCopy){
if(key == "start" || key == "end"){
// needs more specific method to manipulate date to your needs
dataCopy[key] = new Date(dataCopy[key])
}
}
arr.push(dataCopy)
}
alert( JSON.stringify(arr) )
Demo1
Demo2
Sorry cannot comment so have to answer
I have taken your JSON string in a variable here and it gives me proper result
See here
var d = {"mes":"<div class=\"alert alert-success\">Your goal has been updated. <\/div>","graph_data":"[['07\/9\/2014',500],['07\/8\/2014',900],['07\/7\/2014',1200],['07\/6\/2014',500],['07\/5\/2014',500],['07\/4\/2014',500],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000],['07\/11\/2014',2000]]"};
alert(d.graph_data);
alert(d.mes);
Related
Ok so the scenario is currently I am populating a drop down list from my model with the following code
ViewBag.LeaseCompanyID = new SelectList(ContractModelEntity.system_supplier.Where(x => x.Type == "Lease"), "CompanyID", "Name", data.LeaseCompanyID);
This works perfectly, however on my form I have a button located next to the drop down list which adds another option in the database, using ajax and a modal popup.
The controller code for this is here
[HttpPost]
public JsonResult AddSupplier([Bind(Include="Name,Type")] system_supplier data)
{
if (ModelState.IsValid)
{
ContractModelEntity.system_supplier.Add(data);
ContractModelEntity.SaveChanges();
return Json(0, JsonRequestBehavior.AllowGet);
}
return Json(1, JsonRequestBehavior.AllowGet);
}
When the new option is added into the database I then need to refresh my dropdownlist to get this new data (currently if I refresh the page I can see the new option). I am using minimalect plugin for the drop downs.
Does anybody know a way of updating this minimalect list, there must be a way of building the list through an ajax call which returns some JSON data.
Thanks in advance for your help
OK so after doing a bit of research here is my solution, hopefully it will help other poeple. Someone might even have a cleaner solution.
I first created a jsonresult controller method which looked like this
[HttpGet]
public JsonResult RetreiveSuppliers(string contractType)
{
var supplierData = ContractModelEntity.system_supplier.Where(x => x.Type == contractType);
var result = new List<object>();
foreach (var x in supplierData)
{
result.Add(new { Id = x.CompanyID, Name = x.Name });
}
return Json(result, JsonRequestBehavior.AllowGet);
}
That got me the data from the database. then I created a javascript on the page which looks like this
$("body").on("click", "#btn_InsertNewSupplier", function () {
var supForm = $("#addSupData");
$.ajax({
url: "#Url.Action("AddLeaseSupplier", "Contract")",
data: supForm.serialize(),
type: "POST",
success: function (result) {
if (result === 0) {
var inst = $.remodal.lookup[$('[data-remodal-id=modal_AddSupplier]').data('remodal')];
inst.close();
NotificationAlert("success", "New Supplier Created");
GetNewSupplierList();
} else {
NotificationAlert("error", "Failed Adding New Supplier");
}
}
});
});
function GetNewSupplierList() {
var actionurl = "#Url.Action("RetreiveSuppliers", "Contract", new { contractType = "Lease"})";
$.getJSON(actionurl, tempdata);
}
function tempdata(response) {
if (response != null) {
var html = "";
for (var i = 0; i < response.length; i++) {
html += '<option value="' + response[i].Id + '">' + response[i].Name + '</option>';
}
$("#LeaseCompanyID").html(html);
}
}
So once the ajax call is successful it will trigger the GetNewSupplierList function which calls my controller method and returns some JSON data. Once that is returned it calls tempdata, which builds the new HTML for my select picker, once that is built it updates the html on the selectpicker id.
Works like a charm!!!
Thanks to everyone who took a look at this post.
i have got a html table which is dynamically created by php code taking db data.
the table's last field is a input field for entering a number.
the data from the table has to be sent to another php page for sql insert.
i am new to xml and ajax pls help me out with the above javascript code.
<script>
$(document).ready("enter").click(function(event){
event.preventDefault();
var elementTable = document.getElementById("form_table");
var jObject = [];
for (var i = 0; i < elementTable.rows.length; i++)
{
jObject[i] = [];
jObject[i][0] = elementTable.rows[i].cells[1].innerHTML;
jObject[i][1] = elementTable.rows[i].cells[2].innerHTML;//data from input field
}
console.log(jObject);
var JSONObject = encodeURIComponent(
JSON.stringify(jObject));//GETTING ERROR HERE
var url = "submit.php";
var requestData = "&dtable=" + JSONObject;
var XMLHttpRequestObj = FileResort.Utils.createRequest();
XMLHttpRequestObj.open("POST", url, true);
XMLHttpRequestObj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
XMLHttpRequestObj.send(requestData);
});
</script>
as long as you are using JQuery, adapt this jsfiddle example
$("button").click(function(event){
event.preventDefault();
var tableArray = [];
$("table tbody tr:has(td)").each(function(index,element){
tableArray.push([
$(this).find("td:eq(1)").html(),
$(this).find("td:eq(2)").html()
]);
});
console.log(tableArray);
$("div").text(encodeURIComponent(
JSON.stringify(tableArray)
));
return false;
});
which is mostly what you want for the table serialization minus the ajax call ( which I think should be a POST, but that is my personal opinion )
I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});
So basically I'm making cURL request and getting response that looks like this(var_dump):
string(595) "{"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}}"
What I want is to access it in the JS file like this:
success: function (data) {
alert(data.user_id);
}
But I don't know how to convert(?) it properly.
And my next step(question) after that will be if I can do a for loop for every purchased pack, so I can create button for each one of them
Probably something like this:
var pack;
var packs = data.purchase_packs;
for (pack= 0; pack < packs.length; pack++) {
console.log(packs[pack]);
}
I'm tried to understand your "question"....
In js:
$.post('/some/url',{query: 'somequery'},
function (data) {
try {
data = JSON.parse(data);
} catch (e) {
return false;
}
console.log(data);
});
In PHP:
data = json_decode(rtrim($myJSONEncodedString, "\0"));
if (!empty($data->purchase_packs)
foreach ($data->purchase_packs as $key => $value)
var_dump($value);
After receiving response using cURL, just echo that json string between <script></script> tag.
Then json string will look like:
<script>
var jsondata = {"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}};
</script>
Then, your javascript code between <script></script>. Like this:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
alert(jsondata.user_id); // return user_id value
jQuery.each(jsondata.purchase_packs, function(i, val) {
alert(val.amount); // return amount
var paymentMethod = val.allowed_payment_methods;
jQuery.each(paymentMethod, function() {
alert(this); // will return all payment gateway method
});
});
</script>
Hope will help!
Currently my code is
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
// The example input, doesn't have to be part of the upload form:
var adultinput = $('#adult');
data.formData = {adult: adultinput.val()};
if (!data.formData.adult) {
input.focus();
return false;
}
});
Which works just fine to send a post data with adult value from the html code
However there's another input form called thumbsize which i want to send as well,
I tried
$('#fileupload').bind('fileuploadsubmit', function (e, data) {
// The example input, doesn't have to be part of the upload form:
var adultinput = $('#adult');
var thumbsize = $('#thumbsize');
data.formData = {adult: adultinput.val()};
data.formData = {thumbsize: thumbsize.val()};
if (!data.formData.adult) {
input.focus();
return false;
}
});
But it doesn't seem to work, is there anyway i can go about sending another parameter?
Thanks!
data.formData = {adult: adultinput.val()};
data.formData = {thumbsize: thumbsize.val()};
With the second line you’re overwriting what you assigned in the first one.
Put both values into one object:
data.formData = {adult: adultinput.val(), thumbsize: thumbsize.val()};