JavaScript (To submit a form). Using React.js - javascript

handleCommentSubmit:function(comment)
{
console.log('pohach gaye bhaiyaa');
var request = {
'request':{
'ActorSId':667275,
'ParentPostId':null,
'PostStatus':null,
'Action':'Operate',
'PostRecipients':[],
'PostRecipientsAction':'DonotOperate',
'PostAttributes':[],
'PostAttributesAction':'DonotOperate',
'PostTags':[],
'PostTagsAction':'DonotOperate',
'PostAssetAttachments':[],
'PostAssetAttachmentsAction':'DonotOperate',
'PostContent':[{comment:""}],
'PostContentAction':'DonotOperate'
}
};
$.ajax({
url:'http://kmserver28:3535/Alto/Post/PostWS.asmx/AddKonnectPost',
dataType:'json',
type:'POST',
data:JSON.stringify(request),
success:function(data){
this.state.data.push(data);
this.setState({data:this.state.data})
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
var CommentForm = React.createClass({
myFunction:function(e)
{
console.log('9999999999999999999999');
e.preventDefault();
var comm =(React.findDOMNode(this.refs.text).value.trim());
console.log(comm);
this.props.onCommentSubmit(comm);
**
// i'm trying to call the function handleCommentSubmit() from here and
// it is giving error as : "Object expected". Request structure is in the above function**
},
render:function(){
return(
<form className="commentForm" onSubmit={this.myFunction}>
<input className="inputText1" type="text" placeholder="Please Enter Your Comment Here ...." ref="text" /><br /><br />
<input className="Submit1" type="submit" value="Post" />
</form>
);
}
});

contentType: 'application/json; charset=utf-8',
Adding this line inside the ajax request simply did the trick,
Sorry for inconvenience.

Related

ajax unable to find url c# method

I am unable to find the url in my ajax call. Below is the Html code
<div class='replyDiv1' id='sendmail_form'>
<h2>Reply</h2>
<label>Subject:</label><span class='replySubject'>Reply: #=MessageSubject#</span><br />
<label class='datereply'>Date:</label><span class='replytime'></span><br />
<label>To:</label><span>#=MailFrom#</span><br />
<label class='claimIDReply'>Claim:</label><span>#=ClaimId#</span>
<label>Message:</label><br /><textarea rows='8' style='width:80%;' class='replymessage' placeholder='Reply Here'></textarea><br /><br />
<button class='btn btn-primary' onclick='button1()' id='sendReply'>Send</button><br /><br /><span id='msg' style='color:red;'/>
</div>
Here is the JavaScript Ajax Code, this is inside the View
var dataObject1 = JSON.stringify({
'MailTo': from,
'MailFrom': to,
'ClaimId': claimID,
'CreateDate': time,
'MessageBody': newMessage,
'MessageSubject': subject,
});
$.ajax({
type: "Post",
datatype: "json",
url: '#Url.Action("SendReply1", "MCenterController")',
data: {},
cache: false,
//contentType: 'application/json',
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Fail");
},
});
Below is the C# method
[HttpPost]
[ValidateInput(false)]
public ActionResult SendReply1()
{
return Json(new { success = true, message = "Success" }, JsonRequestBehavior.AllowGet);
}
When I debug the code in Chrome, I get the error that MCenterController/SendReply1 is not found and the ajax call fails. SendReply1 is the name of the method and MCenterController is the name of the controller.
I need the button to refresh the current page.
What am I missing?

reactjs update state after ajax call

I want to update my state when I get errors from my ajax call.
My code:
var EmailForm = React.createClass({
getInitialState: function(){
return {
password:'',
email: '',
errors: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get('/accounts/email-form/', function (result) {
var userInfo = result;
this.setState({
email: userInfo.email
});
}.bind(this));
},
submit: function (e){
var self;
e.preventDefault()
self = this;
console.log(this.state);
var data = {
password: this.state.password,
email: this.state.email,
CSRF: csrftoken
};
// Submit form via jQuery/AJAX
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: 'POST',
url: '/accounts/email-form/',
data: data,
datatype: JSON
})
.done(function(data) {
toastr.success('Profile updated');
})
.error(function(jqXhr) {
var error = jqXhr.responseJSON; //How can I append this errors to my errors state ?
toastr.error('There is some errors in your request');
});
},
passwordChange: function(e){
this.setState({password: e.target.value});
},
emailChange: function(e){
this.setState({email: e.target.value});
},
render: function() {
return (
<form onSubmit={this.submit}>
<div className="form-half">
<label htmlFor="password" className="input-label">Current Password</label>
<BasicInputPassword valChange={this.passwordChange} val={this.state.password}/>
<span className="form-error is-visible">{this.state.errors.password}</span>
</div>
<div className="form-half">
<label htmlFor="email" className="input-label">New email</label>
<BasicInput valChange={this.emailChange} val={this.state.email}/>
<span className="form-error is-visible">{this.state.errors.email}</span>
</div>
<button type="submit" className="button secondary" >Submit</button>
</form>
);
}
});
I have response errors in error variable. How can I update state errors with this json and display for example state.errors.email easy ? Is this possible ?
use this.setState()
var that = this;
$.ajax({
type: 'POST',
url: '/accounts/email-form/',
data: data,
datatype: JSON
})
.done(function(data) {
toastr.success('Profile updated');
})
.fail(function(xhr, status, error) {
that.setState({
//assign error to whatever you want under `state`
});
});
*make sure this is pointing at the right scope. Or use arrow functions for lexical this.
$.get('some.php')
.done(function(msg){ })
.fail(function(xhr, status, error) {
this.setState({});///here <===
}).bind(this);
or
$.ajax({
type: "GET",
url: "test.com",
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
you must use .fail() and you can access to error in .fail() and store in state.
You can do this.
const self = this;
$.get('api-url')
.done(function(msg){
// some work
})
.fail(function(xhr, status, error) {
self.setState({error: xhr.responseJSON });
});
As the this context changes so you can assign it at a variable first to avoid the confusion with the context.

XML request from ajax form

Hello everyone I am newbie in java-script so i hope you can help me with my issue. So I have the form, it look something like this:
<form method="post">
Field1: <input type="text" name="field1"><br>
Field2: <input type="text" name="field2"><br>
<input type="submit" value="Submit">
</form>
I need to take data from the form and make xml request, the xml request should look like this
<root>
<header section>
<section>data</section>
</header section>
<data section>
<field1>data</field2>
<field2>data</field2>
</data section>
</root>
After that i have to display xml response on the page.
I made xml request
<script>
$('.button').click( function() {
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
success: function(xml) {
$(xml).find('root').each(function(){
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
But I don't know how to take data from the form and make request. Can you help me with it? Thanks a lot.
// You can use jQuery to build XML document:
function buildXmlFromForm(form) {
var xml = $('<XMLDocument />');
xml.append (
$('<header-section />').append(
$('<section />').text('data')
)
).append (
$('<data-section />').append(
$('<field1 />').text(form.find("input[name='field1']").val())
).append(
$('<field2 />').text(form.find("input[name='field2']").val())
)
);
return xml.html();
}
// you should use POST or PUT method (not GET) to post xml-data to server side
$( "#form1" ).submit(function(event) {
event.preventDefault();
$("#results").append("<ul></ul>");
var xmlString = buildXmlFromForm($(this));
$("#xmlSrc").val(xmlString);
$.ajax({
type: "POST",
dataType: 'xml',
url: 'response.xml',
data: xmlString,
success: function(respData) {
$("<li></li>").html("ok: "+respData).appendTo("#results ul");
console.log(respData);
},
error: function(errorData) {
$("<li></li>").html("error: "+errorData.statusText).appendTo("#results ul");
console.log(errorData);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="form1">
Field1: <input type="text" name="field1" value="***v1***"><br/>
Field2: <input type="text" name="field2" value="***v2***"><br/><br/>
<input type="submit" value="Submit">
</form>
<hr/>
<textarea id="xmlSrc" cols="70" rows="5"></textarea>
<div id="results"/>
Try this:
serialize will return formData of current form
You must have unique identifier for your form to be used as querySelector
$('#myForm').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$(".results").append("<ul></ul>");
$.ajax({
type: "GET",
dataType: 'xml',
url: 'response.xml',
data: formData,
success: function(xml) {
$(xml).find('root').each(function() {
var sField1 = $(this).find('field1').text();
var sField2 = $(this).find('field2').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo(".results ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="myForm">
Field1:
<input type="text" name="field1">
<br>Field2:
<input type="text" name="field2">
<br>
<input type="submit" value="Submit">
</form>

Ajax not firing on submission

I am trying to create a form that has an action to a URL. But it requires ajax submission first and then it should submit to the action.
It should send me an email (within the newsletter.php).
<script type='text/javascript'>
$(function () {
$("#signup").on('submit', function( e, response ) {
if (response.errors == false) {
$.ajax({
type : 'GET',
url : 'newsletter.php',
data: {
name : $('#os0').val(),
email: $('#os1').val()
},
success : function(data) {
$('#subscribe').submit();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// error handling
}
});
return false;
}
return true;
});
});
</script>
HTML
<form name="signup" id="signup" action="" method="GET">
<input type="text" id="os0" name="Email" />
<input class="text" id="os1" type="text" name="cd_FULLNAME" />
<input type="Submit" name="Submit" id="subscribe" value="Subscribe" />
</form>
<script type='text/javascript'>
$(function () {
$("#signup").on('submit', function( e, response ) {
$.ajax({
type : 'GET',
url : 'newsletter.php',
data: {
name : $('#os0').val(),
email: $('#os1').val()
},
success : function(data) {
$("#signup")[0].submit();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// error handling
}
});
return false;
});
});
</script>
Note the difference between $("#signup")submit(); and $("#signup")[0].submit();.

Reactjs: Uncaught TypeError: undefined is not a function

I am a newbie in the Reactjs, I am trying to perform CRUD operation. But I am having issues when performing Delete event. This is How my screen looks:
![enter image description here][1]
And my code looks like this:
var DALHandler=React.createClass({
getInitialState:function(){
return{data: {objects:[]}} // variable should be created with array
},
DeleteOrganizationFromServer: function(id) { // this is Json Function
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'},
url: 'URL/'+id,
dataType: 'json',
type: 'Delete',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('url='url', status, err.toString());
}.bind(this)
});
},
loadOrganizationFromServer: function() {
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'},
url: 'URL/'+id,
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('url='url', status, err.toString());
}.bind(this)
});
},componentWillMount: function() {
this.loadOrganizationFromServer();
//setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},render: function() {
return (
<div >
<OrganizationAPP onOrganizationSubmit={this.handleOrganizationSubmit} />
<OrganizationList data= {this.state.data} />
<Organization DeleteOrganization= {this.DeleteOrganizationFromServer} />
</div>
);
}
});
var OrganizationList=React.createClass({
render:function(){
var results = this.props.data;
var parsed_results = results.objects;
var organizations = parsed_results.map(function(organization){
return <Organization id={organization.id} name={organization.name} description={organization.description}> </Organization>
});
return(<div>
{organizations}
</div>)
}
});
//var converter = new Showdown.converter();
var Organization = React.createClass({
handleDeleteClick: function (e) {
//alert(this.props.id);
var currentId=this.props.id;
this.props.DeleteOrganization(); // ERROR CAUSES HERE:
},
render: function() {
return (
<div className="row">
<div className="small-2 large-2 columns">{this.props.id} </div>
<div className="small-4 large-4 columns">{this.props.name} </div>
<div className="small-4 large-4 columns">{this.props.description}</div>
<div className="small-2 large-2 columns">
<input type="button" onClick={this.handleDeleteClick} data-order={this.props.id} value="Delete" />
</div>
</div>
);
}
});
I know I am doing some stupid mistake but I don't find help to solve this. Please help me to sort it out.
Thank you in advance.
You create your Organization elements like this:
<Organization id={organization.id}
name={organization.name}
description={organization.description}></Organization>
So inside Organization you will have three props: id, name, and description. You try to call this.props.DeleteOrganization() from inside Organization, which is undefined because it's not one of the three props you're passing to it.
To make it work with OrganizationList, you need to pass the delete function down to it:
<OrganizationList data={this.state.data} onDelete={this.DeleteOrganizationFromServer} />
And inside OrganizationList's render function, you can pass it down again.
<Organization id={organization.id}
name={organization.name}
description={organization.description}
onDelete={this.props.onDelete.bind(null, organization.id}></Organization>
And inside Organization:
handleDeleteClick: function(){
this.props.onDelete()
}
I have managed to the solve problem myslef but this fiddle helped me greatly: http://jsfiddle.net/ammit/wBYHY/5/
So mainly I added one more function in OrganizationList that calls DeleteOrganizationFromServer function, so now my code looks like this:
var OrganizationHandler=React.createClass({
getInitialState:function(){
return{data: {objects:[]}} // variable should be created with array
},
DeleteOrganizationFromServer: function(id) {
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'},
url: 'url/'+id,
dataType: 'json',
type: 'Delete',
success: function(data) {
this.loadOrganizationFromServer();
}.bind(this),
error: function(xhr, status, err) {
console.error('url="url', status, err.toString());
}.bind(this)
});
},
loadOrganizationFromServer: function() {
$.ajax({
headers: { 'Accept': 'application/json',
'Content-Type': 'application/json'},
url: 'url',
dataType: 'json',
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error('url="url', status, err.toString());
}.bind(this)
});
},
componentWillMount: function() {
this.loadOrganizationFromServer();
},render: function() {
return (
<div >
<OrganizationAPP onOrganizationSubmit={this.handleOrganizationSubmit} />
<OrganizationList external_DeleteOrganization={this.DeleteOrganizationFromServer} data= {this.state.data} />
</div>
);
}
});
var OrganizationList=React.createClass({
internal_DeleteOrganization: function(id) {
this.props.external_DeleteOrganization(id);
},
render:function(){
var results = this.props.data;
var parsed_results = results.objects;
var that = this; // Not equally that to this was also causing error,
var organizations = parsed_results.map(function(organization){
return <Organization onDeleteOrganization={that.internal_DeleteOrganization} id={organization.id} name={organization.name} description={organization.description} />
});
return(<div>
{organizations}
</div>)
}
});
var Organization = React.createClass({
handleDeleteClick: function () {
this.props.onDeleteOrganization(this.props.id);
},
});

Categories