jQuery Internal Server Error - javascript

This is simple login page created in asp.net but jQuery doesn't work here. I am getting this error again and again, please help me solve this.
This is my HTML markup:
<html>
<body>
<form id="form1" runat="server">
<div>
User Name :<input type="text" name="UserName" placeholder="Enter User Name" /> <br />
Password :<input type="password" name= "Password" placeholder="Enter password" /></br>
<input type="button" value="Login" id="SubmitLogin" />
</div>
</form>
<script type="text/javascript">
$('#SubmitLogin').click(function () {
alert("I am in Submit Button click");
Login_User();
});
Login_User = function () {
postData = {UserName:'UserName1',Password:'Password1'};
debugger;
$.ajax({
//async:'false',
type: 'POST',
url: 'LoginForm.aspx/Login_validate',
datatype: 'json',
data: JSON.stringify({ "dbparameters": postData }),
contentType: 'application/json; charset=utf-8 ',
success: function (outputresult) {
alert("i am in Success " + outputresult + " .");
},
error: function (XMLHttpRequest, status, error) { alert("Error In System : " + status + " " + error); }
})
}
</script>
</body>
</html>
and my code-behind:
[WebMethod]
[ScriptMethod]
public string Login_validate(Dictionary<string, string> dbparameters) {
string UserName, Password;
UserName = dbparameters["UserName"];
Password = dbparameters["Password"];
return UserName + Password + " ";
}

I Have come to an Answer that Data sent in this request is in-coded in Double Cotes, this gives error
data sent as
`{"dbparameters ":{"UserName":"UserName1","Password":"_Password1"}}`
but this should be sent as
{"dbparameters ":{"UserName":UserName1,"Password":_Password1}}
how to do this ? this will solve Internal Server Error.

Related

Submission empty or json decode of submission failed. how to submit textarea inside form

<p><h3>Enter your SQL query below:</h3>
<form method="post" action="http://212.47.247.139/challenge/ajax.php?submission=%7B%7D" id="my-form">
<textarea id='text1' class='sql' name='submission' rows=10 cols=120></textarea>
<input type="submit" id="blogSubmit" onclick="getText()">
<br>
</form>
</p>
<script>
function getText() {
// var str=document.getElementById("text1").value;
// alert(str + "i did it");
$.ajax('ajax.php?submission=%7B%7D', {
data: {submission: $('#text1').val()},
success: function(data) {
success_callback(data);
console.log("success " + data);
},
error: function(xhr, status, error) {
alert(error);
},
type: 'POST'
})
}
</script>
I have a text area inside a form that holds some sql statement. I have a submit button inside the form. What i want to have happen is: when the user clicks the submit button, whatever is inside the textarea gets POSTED to "http://212.47.247.139/challenge/ajax.php?submission=%7B%7D" using ajax.
After submitting, When I look under the network tab, i see the form data has what I enter in, but I get a "Submission empty or json decode of submission failed". I am new to ajax, html, and javascript. In place of the $('#blogSubmit').val(), I have tried many things such as JSON.stringify({ prop: $('#blogSubmit').val()
What i am doing wrong?
UPDATE after implementing changes Barmer suggested
<p><h3>Enter your SQL query below:</h3>
<form method="post" action="http://212.47.247.139/challenge/ajax.php?submission=%7B%7D" id="my-form">
<textarea id='text1' class='sql' name='submission' rows=10 cols=120></textarea>
<input type="button" id="blogSubmit" onclick="getText()">
<br>
</form>
</p>
<script>
function getText() {
// var str=document.getElementById("text1").value;
// alert(str + "i did it");
$.ajax('ajax.php?submission=%7B%7D', {
data: {submission: { prop: JSON.stringify($("#text1").val())}},
success: function(data) {
success_callback(data);
console.log("success " + data);
},
error: function(xhr, status, error) {
alert(error);
},
type: 'POST'
})
}
</script>
Now I get this error: "Warning: json_decode() expects parameter 1 to be string, array given in /var/www/my_website/challenge/ajax.php on line 31
Submission empty or json decode of submission failed"
Why would it say an array is given when I am doing JSON.stringify to convert it to string?
Change the submit button to type="button" so it doesn't submit the form, it just runs your function.
In the AJAX call, convert the value of the textarea to JSON with JSON.stringify().
function getText() {
$.ajax('ajax.php?submission=%7B%7D', {
data: {
submission: JSON.stringify($('#text1').val())
},
success: function(data) {
success_callback(data);
console.log("success " + data);
},
error: function(xhr, status, error) {
alert(error);
},
type: 'POST'
})
}
<p>
<h3>Enter your SQL query below:</h3>
<form method="post" action="http://212.47.247.139/challenge/ajax.php?submission=%7B%7D" id="my-form">
<textarea id='text1' class='sql' name='submission' rows=10 cols=120></textarea>
<input type="button" id="blogSubmit" onclick="getText()">
<br>
</form>
</p>

JS does not detect form submission

$(document).ready(function() {
$("#loginForm").on('submit', function() {
var mail = document.getElementById("mail").value;
var password = document.getElementById("password").value;
req = $.ajax({
url: '/api/login',
type: 'POST',
data: {
email: email,
password: password
}
});
req.done(function(data) {
if (data.result == "failed") {
let messageHandler = document.getElementById("message-handler");
messageHandler.innerHTML = `<h3> username or password incorrect </h3>`;
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST">
<input type="mail" id="mail" name="mail">
<input type="text" id="password" name="password">
<input type="submit" id="loginForm">
</form>
<div id="message-handler">
</div>
When I click the button, it simply says Method not allowed because I am sending a post request from form. The js never detects the on submit event.
Thanks
What happens here in /api/login? Try to point a file like form.php or something else.
req = $.ajax({
**url: '/api/login',**
type: 'POST',
data: {
email: email,
password: password
}
});
Maybe this is the path you need to follow for your answer ;)
Use action='url' Or action='#' this will help to detect your request in browser.

Problems with ajax response in node js?

So, basically I am trying to send a request from my ajax post to my node js backend. Then I am trying to get the response back from the node js and update my view. Now, this is something that happens. Instead of just updating the resulttoken in the view, I can see in the console that whole html is loaded like a page. I am really confused. Please kindly point my error. This is what I tried so far.
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: <%=resulttoken%>;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
server
app.post("/home", function (req, res) {
var s = -1;
var t = -1;
var m = -1;
var phonenumber = req.body.phonenumber;
var review = req.body.review;
console.log(phonenumber);
fd.insertreview(phonenumber,review).then(function(v) {
if(v=="1") {
console.log("Your review has been inserted successfully");
s = md.getRand();
console.log("Unique number is",s);
fd.checkifuniquenumberexists(s).then(function(u){
if(u!="1"){
console.log("Unique number doesnt exist");
fd.inserttoken(s,phonenumber).then(function (p) {
if(p=="1"){
console.log("Token has been inserted successfully");
res.render('trial',{"resulttoken":s});
}
})
}
});
}
});
});
This is what loads on the console log
info <!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: 35055;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
The issue is this line
res.render('trial',{"resulttoken":s});
You're returning the entire page as your response, if you just need the token you can return this as part of a JSON response e.g.
res.status(200).json({ token: s });
then at the client
$.post('/home', { phonenumber, review }, res => {
// use res.token
console.log(`Token: ${res.token}`);
})
.fail(console.error);

Jump to previous page after sending data using ajax

On page A, I use ajax to send data to server. At sever side, after spring controller gets the data, it returns welcome page B. Evergthing works fine on firefox and IE. But on chrome, after ajax call sends data to server successflully, we can get the reponse: the page B I want. But the page B just show for 1 second. Then jump back to page A again. Now idea why? Thanks.
The form html:
<form class="form" id="register-form">
<input id="username" type="text" placeholder="Username" name="username">
<input id="password1" type="password" placeholder="Password" name="password1" >
<input id="password2" type="password" placeholder="Password" name="password2">
<input id="email" type="text" placeholder="Email" name="email">
<input id="phonenumber" type="text" placeholder="Phone Number" name="phonenumber">
<button onclick="register()" id="register-button">Join us!</button>
</form>
Ajax:
$.ajax({
url: "/myporject/user/addUser",
type: 'GET',
dataType: 'text',
contentType: "application/json; charset=utf-8",
async: false,
cache : false,
data: {
username:username,
password:pwd1,
email:email,
phonenumber:phone
},
success : function(response) {
alert("response:" + response);
document.open();
document.write(response);
document.close();
},
error: function(xhr, textStatus, error){
alert("error!!!");
console.log(xhr.statusText);
alert(textStatus);
console.log(error);
}
});
Spring controller:
#RequestMapping(value = "/addUser", method = RequestMethod.GET)
public #ResponseBody ModelAndView addUser(
#RequestParam(value = "username") String username,
#RequestParam(value = "password") String password,
#RequestParam(value = "email") String email,
#RequestParam(value = "phonenumber") String phonenumber) {
User user = userService.createUser(username, password, email, phonenumber,
User.ROLE_CUSTOMER);
ModelAndView myview = new ModelAndView("welcome");
return myview;
}
Add type="button" (e.g. <button type="button" ...>) so that a (standard, non-Ajax) form submit doesn't happen at the same time.
Or bind the click handler with jQuery and use event.preventDefault()

WSDL to SOAP Envelope

I have a WSDL web service http://portal.strongtech.com/i/services/ivos?wsdl and I want to send request to functions using AJAX. I know how to send request using AJAX or JQuery though I am not sure how to write SOAP envelope for the function I want to request for.
Can you please help me writing SOAP envelop for the login function from the given service URL? That would be really appreciated.
check call-soap-xm-web-services-with-jquery-ajax and jQuery Plugin SOAP
here is an example from http://www.icloud.com/wiki/index.php/Getting_started_-_jquery_ajax_guide
<html>
<head>
<script type="text/javascript" src="http://os.icloud.com/live/jqueryloader.js"></script>
<script type="text/javascript">
function printResult(doc, status, xhr) {
var p = document.getElementById("output");
if( status == "error" ) {
p.innerHTML = doc.responseText.replace(/</g, "<");
login("/", "/"); // reset username
} else {
p.innerHTML = xhr.responseText.replace(/</g, "<");
}
}
function createSoapEnvelope(contents) {
return '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' +
'SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<SOAP-ENV:Body>' + contents + '</SOAP-ENV:Body></SOAP-ENV:Envelope>';
}
function login(username, password, callback, errback) {
icloud.ajax({
type: "POST",
async: true,
cache: false,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
processData: false,
url: "http://os.icloud.com/v1/",
username: username,
password: password,
data: createSoapEnvelope("<login/>"),
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "login");
},
success: callback,
error: errback
});
}
function buttonClicked() {
login(document.getElementById("username").value, document.getElementById("password").value, printResult, printResult);
}
initIcloudAPI();
</script>
</head>
<body>
<h2>Login example</h2>
username:<input type="text" name="username" id="username"/>
password:<input type="password" name="password" id="password"/>
<input type="submit" name="login" value="Login" onclick="buttonClicked()"/>
<p id="output"/>
</body>
</html>

Categories