jQuery send more then one formdata - javascript

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()};

Related

Post multiple data items through redirectPost() function to .cshtml page

I found the following code at: Send POST data on redirect with JavaScript/jQuery?
$.extend(
{
redirectPost: function (location, args) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", location);
$.each(args, function (key, value) {
var field = $('<input></input>');
//Change the following back to hidden
field.attr("type", "hidden");
//field.attr("type", "text");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
$(form).appendTo('body').submit();
}
});
I call this redirect from jquery with the following:
var redirect = 'ListDatabaseDetails.cshtml?id=999999';
$.redirectPost(redirect, { 'ServerID': '1', 'DBID': '23' });
Can this be done with a .cshrml target page? If so, how do I retrieve the two values: ServerID and DBID on the target page?
I have tried the following JavaScript on the target .cshtml page with no success-the fields aren't there:
function load_data() {
var ServerID = document.getElementById("ServerID").value;
var DBID = document.getElementById("DBID").value;
}
Thanks for any help.
I was able to figure this out using c# razor code, with the values posted in from jquery in the sending page. In the target .cshtml page, I added:
#{
var serverID = Request["ServerID"];
var dbID = Request["DBID"];
}
This stored the values in the serverID and dbID variables which were populated with the data from the sending page. yay!

Converting a html table into a json object and sending it to a php page ,the table has a input field

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 )

asynchronous HTTP (ajax) request works in script tag but not in js file

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');
};
});

alert part of AJAX response

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);

YUI Dialog using ajax request - want to execute javascript returned from Java but out of scope

I have a YUI dialog that submits a form to a Java servlet. The servlet returns html and javascript. I take the response and put it into a div on the page and then eval the javascript that is within the div.
My problem is that I get an error in the firebug console saying "YAHOO is not defined" as soon as the servlet returns.
I do not include the YUI js files in the servlet as I didn't think I would need them, I would expect the files included in the head of the main page would be sufficient.
If I remove all references to YUI from the javascript returned by my servlet then everything works well.
What should I do to stop getting this error as soon as my servlet returns?
My Servlet returns something along the lines of:
<div id="features">some html to display</div>
<script id="ipadJS" type='text/javascript'>
var editButton1 = new YAHOO.widget.Button('editButton1', { onclick: { fn: editButtonClick, obj: {id: '469155', name : 'name 1'} } });
var editButton2 = new YAHOO.widget.Button('editButton2', { onclick: { fn: editButtonClick, obj: {id: '84889', name : 'name 2'} } });
</script>
Here is the code that I used to create the dialog, i use the handleSuccess function to put my response from my servlet into the page (note that even though im not actively putting the javascript into the page it still throws the 'YAHOO not defined' error.):
YAHOO.namespace("ipad");
YAHOO.util.Event.onDOMReady(function () {
// Remove progressively enhanced content class, just before creating the module
YAHOO.util.Dom.removeClass("createNewFeature", "yui-pe-content");
// Define various event handlers for Dialog
var handleSubmit = function() {
this.submit();
};
var handleCancel = function() {
this.cancel();
};
var handleSuccess = function(o) {
var response = o.responseText;
var div = YAHOO.util.Dom.get('features');
div.innerHTML = response;
};
var handleFailure = function(o) {
alert("Submission failed: " + o.status);
};
// Instantiate the Dialog
YAHOO.ipad.createNewFeature = new YAHOO.widget.Dialog("createNewFeature",
{ width : "450px",
fixedcenter : true,
visible : false,
constraintoviewport : true,
buttons : [ { text:"Submit", handler:handleSubmit, isDefault:true },
{ text:"Cancel", handler:handleCancel } ]
});
// Validate the entries in the form to require that both first and last name are entered
YAHOO.ipad.createNewFeature.validate = function() {
var data = this.getData();
return true;
};
YAHOO.ipad.createNewFeature.callback = { success: handleSuccess,
failure: handleFailure,
upload: handleSuccess };
// Render the Dialog
YAHOO.ipad.createNewFeature.render();
var createNewFeatureShowButton = new YAHOO.widget.Button('createNewFeatureShow');
YAHOO.util.Event.addListener("createNewFeatureShow", "click", YAHOO.ipad.clearFeatureValues, YAHOO.ipad.clearFeatureValues, true);
var manager = new YAHOO.widget.OverlayManager();
manager.register(YAHOO.ipad.createNewFeature);
});
I don't know your use case exactly, but if you just need to create some buttons on the fly based on server response, than it would IMO be better to return JSON or XML data with the variable data and then create the buttons. Something like
var reply = eval('(' + o.responseText + ')');
var editButton1 = new YAHOO.widget.Button('editButton1',
{ onclick: { fn: editButtonClick,
obj: {id: reply[id], name : reply[name]}
} })
And if you really want to append a script node, then the following approach should work:
var response = o.responseText;
var snode = document.createElement("script");
snode.innerHTML = response;
document.body.appendChild(snode);

Categories