cannot post $('#myid').val() via ajax post method - javascript

I cannot send the value of input type email via ajax post.i obtain the input value by
var email = $('#myid').val()
which is somemail#gmail.com.I can successfully alert this value but cannnot post the value.when i remove '#' from email,it successfully posts the value..
please check my code below.
<script type="text/javascript">
function forgotfunction(){
var email=$('#forgetpass').val();
alert(email);
$.post("forgetpass.php",
{
email:email
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
$('#modalLink').trigger("click");
});
}
</script>

Try instead this way:
function forgotfunction(){
var email=$('#forgetpass').val();
alert(email);
$.ajax({
type: "POST",
url: "forgetpass.php",
data: { email: email },
error: function(){ alert('Could not post email'); }
});
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
$('#modalLink').trigger("click");
});
}

Related

Ajax character encoding changed after send to server

I have an ajax like this:
$.ajax('../EditUser?userId=' + editingId + '&full_name=' + name + '&position=' + position + '&office=' + office
+ '&office_address=' + office_address + '&age=' + age + '&user_login_name=' + user_login_name + '&email=' + email
+ '&user_type=' + usertype + '&password=' + password + '&meetingIds=' + selectedmeetingid, {
type: 'POST',
success: function (data) {
if (data.indexOf('error://') < 0) {
$('#tbl_meetings').html(data);
} else {
$('#errorMessage').html(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error " + errorThrown);
alert("error " + textStatus);
alert("error " + jqXHR.status);
}
}
);
and my server received data with wrong encoding,example: "Hà Thị Minh Thắng" became "H? Th? Minh Th?ng" after received on server side.I tried adding
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
and
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
}
to my ajax but it didn't works. So, anyone know how to fix this?
Try specifying content type to the ajax request & you have to add header to the server side to receive the charset.
$.ajax({
data: parameters,
type: "POST",
url: your-url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
dataType: 'json',
success: callback
});
// Server Side... (This is an example in php which I have used in my app)
header('Content-Type: text/html; charset=ISO-8859-1');
Hope this helps you!

Ajax unable to parse JSON data

I know there are many questions out there on the same topic and I've read all of them but they don't help my case.
I am trying to parse some JSON data returned from my serverside PHP script. I've used JSONLint to verify that the PHP output is a valid JSON string.
I have the following ajax code:
$(document).ready(function(){
$('#update-stats-submit').on("click", function(){
if (requestRunning) { // don't do anything if an AJAX request is pending
return;
}
$.ajax({
type: "GET",
url: "calculate.php",
data: "q="+$("#table-info").val(),
dataType: "json",
success: function(data){
$("#update-result").animate({ opacity: 100 });
$("#update-result").html(data.output_msg);
$("#update-result").delay(3000).animate({ opacity: 0 });
setTimeout(function() {
$("#update-result").empty();
}, 4000);
alert(data.avg + "\n" + data.var + "\n" + data.count + "\n" + data.est + "\n" + data.min + "\n" + data.max);
},
error: function(xhr, ajaxOptions, thrownError){
$("#update-result").html(xhr.responseText + "\n" + xhr.status + "\n" + thrownError);
}
})
return false;
});
});
I've not gotten this piece of code to execute successfully. Each time the following error is returned.
200 SyntaxError: Unexpected end of input
Sample JSON output returned from calculate.php:
{
"output_msg":"Success!",
"avg":5.79916666667,
"var":4.63505345486,
"n":40,
"est":"1",
"min":"3",
"max":"4"
}
Any tips would be greatly appreciated.
Basically there's nothing wrong with the above ajax script. It appears the bug lied with the serverside PHP code that allowed the script to exit() under certain GET request conditions.

Display JSON Result Upon Button Click ASP.NET MVC

Hi I have this code in my controller:
[HttpPost]
public JsonResult CalculateAndSaveToDB(BMICalculation CalculateModel)
{
if (ModelState.IsValid)
{
CalculateModel.Id = User.Identity.GetUserId();
CalculateModel.Date = System.DateTime.Now;
CalculateModel.BMICalc = CalculateModel.CalculateMyBMI(CalculateModel.Weight, CalculateModel.Height);
CalculateModel.BMIMeaning = CalculateModel.BMIInfo(CalculateModel.BMICalc);
db.BMICalculations.Add(CalculateModel);
db.SaveChanges();
}
return Json(new {CalculatedBMI = CalculateModel.BMICalc.ToString(), CalculatedBMIMeaning = CalculateModel.BMIMeaning.ToString() }, JsonRequestBehavior.AllowGet);
}
I would like to display CalculatedModel.BMICalc and CalculatedModel.BMIMeaning on the page using this JavaScript:
$('#good').click(function () {
var request = new BMICalculation();
$.ajax({
url: "CalculateAndSaveToDB",
dataType: 'json',
contentType: "application/json",
type: "POST",
data: JSON.stringify(request),
success: function (response) {
var div = $('#ajaxDiv');
div.html("<br/> " + "<b>" + "Your BMI Calculations: " + "</b>");
printBMI(div, response);
},
});
});
function printBMI(div, data) {
div.append("<br/>" + "You are " + response.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + response.CalculatedBMIMeaning + ".");
};
Nothing happens however when I do the button click. The correct data from form goes correctly into DB. My Chrome debugger says however that CalculateAndSaveToDB isn't found 404 error. Please help.
Try to return false at the end of your click function.
$('#good').click(function () {
//Your code
return false;
});
Also I can see an error in your printBMI function. There is not reference to the variable "response". It should be "data"
function printBMI(div, data) {
div.append("<br/>" + "You are " + data.CalculatedBMI + ".");
div.append("<br/>" + "You exact BMI is: " + data.CalculatedBMIMeaning + ".");
};
There might be several problems:
Your routing is not correct and the post-action cannot be invoked. I dont see any information about routing, so this might be a problem.
You do not return false, as suggested by PraveeReddy. If you dont do so, the browser follows the link of your button.
Just a hint: In such simple scenarios it can be easier to use $.load: http://api.jquery.com/load/

How can i validate recaptcha with ajax?

my function in js have this code:
$.ajax({
url: "ajax.php",
type: 'POST',
data: 'act=newAccount&email=' + email + '&password=' + password + '&first-name=' + firstName + '&last-name=' + lastName + '&company-name=' + companyName,
success: function(data)
{
json = JSON.parse(data);
if (json === true)
{
console.log("data");
$("#new-account-form")[0].reset();
window.location.replace('login.php');
}
else
{
$(".error-message span").html('Your regestry failed. Please, insert valid data.');
$('.error-message').fadeIn('slow', function () {
$('.error-message').delay(5000).fadeOut('slow');
});
}
}
});
now, i want validate recaptha in my ajax.php but i dont know how i do...
thanks you all
You'll need a Captcha images' displayer and some code to validate it. I recommend Securimage, it worked fine for me, and it is so easy to implement. Have a look at it at http://www.phpcaptcha.org/documentation/quickstart-guide/

Ajax post not sending data out

var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
I have checked and made sure that dataString was sending out correct stuff, however, the ajax was just not sending out any data, no error whatsoever. Even when I changed the url to an invalid one it still went to my success function.
You should pass data as an object instead of a string when you are sending via POST
Example:
data = {
'edulevel': edulevel,
'course': course
(.....)
};
I have made some changes and now this is working your callback function was success() and jQuery was trying to find the function, either you can write your function at same place or you can write a stand alone function and assign it to sucess:, if you are still getting problem try to change your url, if your current files location is /files/file.php
then your veriamateur.php must be /files/process/veriamateur.php
var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: function(){ alert('success');},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});

Categories

Resources