Passing Javascript variable to AJAX call does not work - javascript

When i am passing a variable to AJAX it works if i just create a variable with some string values e.g. var userid = "test" and var passwd = "test1" but not when the variable contains var userid = form.userid.value and var passwd = form.passwrd.value. Why does form.userid.value and form.passwrd.value not work?
Here is the HTML:
<html>
<head>
<title>
Login page
</title>
<script src="login.js"></script>
<!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<!-- jQuery -->
<script src="./jquery.rest.min.js"></script>
<script src="./webtoolkit.base64.js"></script>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="checkLogin(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</body>
</html>
Here is the javascript which does not work (login.js):
function checkLogin(form) {
var auth_token = localStorage.getItem("token");
//the variables which do not correctly pass through to AJAX call
var userid = form.userid.value;
var passwd = form.pswrd.value;
if(auth_token == null) {
$.ajax({
type: 'POST',
data: {
username: userid,
password: passwd
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
var tok = res.token
localStorage.setItem("token", JSON.stringify(tok));
}});
} else {
$.ajax({
type: 'POST',
headers: {
'Authorization':'token ' + JSON.parse(auth_token)
},
data: {
quote_text: "Test Javascript with variable token pt 2",
tags: '["test", "javascript"]'
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
}
});
};
};
However this will work where i have hard coded the username and password (login.js):
function checkLogin(form) {
var auth_token = localStorage.getItem("token");
//hard coded variable content which works.
var userid = "test";
var passwd = "test1";
if(auth_token == null) {
$.ajax({
type: 'POST',
data: {
username: userid,
password: passwd
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
var tok = res.token
localStorage.setItem("token", JSON.stringify(tok));
}});
} else {
$.ajax({
type: 'POST',
headers: {
'Authorization':'token ' + JSON.parse(auth_token)
},
data: {
quote_text: "Test Javascript with variable token pt 2",
tags: '["test", "javascript"]'
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
}
});
};
};

Closed and reopened browser. No idea why that was necessary.

Related

I am trying to send data to my PHP page from html page using ajax POST method but it give error ,Notice: Undefined index:

<head>
<title>Document</title>
<script>
$(document).ready(function () {
$("#search").on("keyup", function () {
var search_term = $(this).val();
console.log('value--', search_term)
$.ajax({
url: "ajax-live-search.php",
type: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});
});
});
</script>
</head>
<body>
<div id="search-bar">
<label>Search</label>
<input type="text" id="search" autocomplete="off">
</div>
<div id="table-data">
</div>
</body>
PHP page
$search_input = $_POST["search"];
echo $search_input;
error
Notice: Undefined index: search in C:\xampp\htdocs\ajax\ajax-live-search.php on line 3
Change "type" to "method" as below:
$.ajax({
url: "ajax-live-search.php",
method: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});

Submit login with Jquery

When I press the Login button I get a 500 Internal server error in the console. What's the right way to get POST using jQuery? Can you help me?
<button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
$(function() {
$("#Login").click(function() {
var username_val = $("#username").val();
var password_val = $("#password").val();
var info_creds = 'username=' + username_val + '&password=' + password_val;
if (username_val == '' || password_val == '') {
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Devi inserire username e password!</p>");
$("#alert_response_ko").fadeOut(8000);
} else {
$.ajax({
type: "POST",
url: "login.php",
data: info_creds,
cache: false,
success: function(response) {
if (response == 'wrong!') {
console.log('ko');
$("#alert_response_ko").show();
$("#alert_response_ko").html("<p>Username e/o Password Errati!</p>");
$("#alert_response_ko").fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
}
}
});
}
return false;
})
});
The 500 Internal Server Error is a "server-side" error, meaning the problem is not with your PC or Internet connection but instead is a problem with the web site's server.
If you want to use Post, you have to send data as Object Change your
Ajax Function to...
$.ajax({
type: 'POST',
url: 'login.php',
data: {
username: username_val,
password: password_val,
},
cache: false,
success: function (response) {
if (response == 'wrong!') {
console.log('ko');
$('#alert_response_ko').show();
$('#alert_response_ko').html(
'<p>Username e/o Password Errati!</p>'
);
$('#alert_response_ko').fadeOut(8000);
}
if (response == 'login_ok!') {
console.log('ok');
window.setTimeout(function () {
window.location.href = './homepage.php';
}, 10);
}
},
});
Consider the following code.
$(function() {
function showAlert(msg) {
console.log(msg);
$("#alert_response_ko").html("<p>" + msg + "</p>").show().fadeOut(8000);
}
function login(page, user, pass) {
$.ajax({
url: page,
data: {
username: user,
password: pass
},
cache: false,
success: function(results) {
if (results == 'login_ok!') {
console.log('Login Successful');
window.setTimeout(function() {
window.location.href = './homepage.php';
}, 10);
} else {
showAlert("Username e/o Password Errati!");
}
},
error: function(x, e, n) {
showAlert("Username e/o Password Errati! " + e + ", " + n);
}
});
}
$("#Login").closest("form").submit(function(e) {
e.preventDefault();
var username_val = $("#username").val();
var password_val = $("#password").val();
if (username_val == '' || password_val == '') {
showAlert("Devi inserire username e password!");
} else {
login("login.php", username_val, password_val);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" id="username" placeholder="User" /> <input type="password" id="password" placeholder="Password" /> <button class="login100-form-btn" type="submit" name="login" value="login" id="Login">
Login
</button>
</form>
<div id="alert_response_ko"></div>
This might help identify issues. As was suggested, the 500 status is a general Web Server failure. It means that the Web Server encountered an error and may be configured to suppress the error message itself.
Check your PHP Logs and Error handling settings. Better to reveal errors while testing and then hide them when in production.

No data receive in Jquery from php json_encode

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>
Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];
Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>
A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

SharePoint 2013 Send Email from Contact Us Form via REST/JS

and thanks in advance for your answers.
I am trying to send an email from a contact us form. It appears to work but I don't receive any emails. I don't have any experience with REST and would like someone who does to see if they can spot any problems.
This is on a SharePoint 2013 Enterprise Publishing Site.
I have changed some variables and IDs for privacy purposes.
The HTML is in a custom page layout, and the JS is being called successfully in the same page layout after jQuery.
JS:
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
function submitForm() {
var toAddress = "email#domain.com";
var fromAddress ="email#domain.com";
var emSubject = "Public Contact Us Form Entry";
var lblName = "Name: ";
var valName = document.getElementById('form-name').value;
var lblEmail = "Email: ";
var valEmail = document.getElementById('form-email').value;
var lblMessage = "Message: ";
var valMessage = document.getElementById('form-message').value;
var emBody = lblName.concat(valName,lblEmail,valEmail,lblMessage,valMessage);
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: toAddress,
Body: emBody,
Subject: emSubject
}
}
var urlTemplate = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('User(s) notified')
},
error: function (err) {
alert("Unable to send email -- " + JSON.stringify(err));
}
});
}
});
HTML:
<div class="label">Name</div>
<input name="Name" type="text" id="form-name" size="40">
<div class="label">Email</div>
<input name="E-mail" type="text" id="form-email" size="40">
<div class="label">Message</div>
<textarea name="Message" cols="55" rows="5" id="form-message"></textarea>
<div class="form-button">
<button onclick='submitForm()'>Submit</button>
</div>
You code has one mistake:
I changed To: toAddress to To: { 'results': [toAddress] }.
Now every thing is working fine and I am also getting the emails.
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: { 'results': [toAddress] } ,
Body: emBody,
Subject: emSubject
}
}

Ajax query to my webservices is returning xml in my json - Part 2

It's me again (previous question) I am still having problems with json and xml being returned from an ajax call.
I have written a webservice in MonoDevelop version 2.2 to return my json.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getLocationJ(){}
Which returns:-
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(bigPM);
return json;
If I test my webservice I get:-
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"placeName":"XXXX","address":"Some Address","lat":12121,"lng":12121}]</string>
Which is exactly what I am pulling in when I make my ajax calls. My json is still wrapped in XML and therefore cannot be read.
This is my ajax call:-
$.ajax({
type: "GET",
url: theURL,
async: true,
data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
cache: false,
dataType: "jsonp",
contentType: "application/xml; charset=utf-8",
success: function (data) {
alert('in here');
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
alert(xhr.statusText);
}
});
If I do just json I get 500 Internal server error, if I do a POST I get 403 forbidden error.
This morning I tried doing:-
$.getJSON(theURL, {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat}, function(data) {
);
});
Only I get the exact same problems.
If I could just remove the xml from my json then I could move forward but right now I am dead in the water and I think I am drowning in ajax!
Please help
Cheryl
Instead of returning a string in your WebMethod, return void and use:
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(YOUR_STRING_TO_OUTPUT));
A quick and dirty fix is to extract your json from the xml in the success function.
$.ajax({
type: "GET",
url: theURL,
async: true,
data: {minLong:minLon, maxLong:maxLon, minLat:minLat, maxLat:maxLat},
cache: false,
dataType: "jsonp",
contentType: "application/xml; charset=utf-8",
success: function (data) {
data = extractJsonFromXml(data);
//you have to write extractJsonFromXml function in js, you could use substring, or a regex replace.
}
change
contentType: "application/xml; charset=utf-8",
to
contentType: "application/json; charset=utf-8",
Complete example:
/* in this case I am using */
<script src="Js/json2.js" type="text/javascript"></script>
// available at: http://www.json.org/js.html
function jsonObject()
{
};
var phoneListObject = new jsonObject();
function SaveJsonObject()
{
phoneListObject.Control = new jsonObject();
phoneListObject.Control.CustomerId = $("#CustomerId").val();
phoneListObject.Control.CustomerName = $("#CustomerName").val();
phoneListObject.ListBody.PhonesBlock = new jsonObject();
phoneListObject.ListBody.PhonesBlock.Phone = new Array();
$('#PhonesBlock .Phone').each(function(myindex)
{
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneNumber = $(".PhoneNumber input", this).val();
phoneListObject.ListBody.PhonesBlock.Phone[myindex].PhoneName = $(".PhoneName input", this).val();
});
};
$(function()
{
function SaveCurrentList()
{
SaveJsonObject();
var currentSet = phoneListObject;
var formData = { FormData: currentSet };
phoneListJSON = JSON.stringify(formData);
var FormData = "{ FormData:" + JSON.stringify(phoneListJSON) + "}";
SavePhoneListData(FormData);
};
function SavePhoneListData(phonesData)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: phonesData,
dataFilter: function(data)
{
var msg;
if ((typeof (JSON) !== 'undefined') &&
(typeof (JSON.parse) === 'function'))
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "../../WebServices/ManagePhones.asmx/SaveJson",
success: function(msg)
{
SaveSuccess(msg);/* the JSON is in the msg, create this function to do what you want with it. */
},
complete: function(xhr, textresponse)
{
var err = eval("(" + xhr.responseText + ")");
},
error: function(msg)
{
},
failure: function(msg)
{
}
});
};
$('#btnSave').click(function()
{
SaveCurrentList();
});
});
/* json data snip */
{"FormData":{"Control":{"CustomerId":"12345y6","CustomerName":"Joe Customer"},"PhonesBlock":{"Phone":[{"PhoneNumber":"234-233-2322","PhoneName":"son harry"},{"PhoneNumber":"234-233-2323","PhoneName":"son frank"},{"PhoneNumber":"234-233-2320","PhoneName":"momk"}]}}}
/*XML of the form data:*/
<FormData>
<Control>
<CustomerId>12345y6</CustomerId>
<CustomerName>Joe Customer</CustomerName>
</Control>
<PhonesBlock>
<Phone>
<PhoneNumber>234-233-2322</PhoneNumber>
<PhoneName>son harry</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2323</PhoneNumber>
<PhoneName>son frank</PhoneName>
</Phone>
<Phone>
<PhoneNumber>234-233-2321</PhoneNumber>
<PhoneName>momk</PhoneName>
</Phone>
</PhonesBlock>
</FormData>
/* form layout snip */
<div class="control">
<div class="customer">
<input typeof="text" id="CutomerId" />
<input typeof="text" id="CutomerName" />
</div>
<div class="phoneslist" id="PhonesBlock">
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
<div class="Phone">
<input typeof="text" class="PhoneNumber" />
<input typeof="text" class="PhoneName" />
</div>
</div>
</div>
<input id="buttonSave" class="myButton" type="button" value="Save" />
signature of the web service method:
[WebMethod(EnableSession = true)]
public string SaveJson(string FormData)
{
}
Make sure your service class has [ScriptService] attribute. This attribute is not added by default.

Categories

Resources