Sending function sent data to php file by ajax - javascript

I am trying to send data to a database.php file by ajax. My Index file has a form which will collect a 4 digit input then sends to a js function which sends the data to my db file. At the moment the Db file is being called because I get a result in the console but the 4 digit key is not being sent. I expect I have done something wrong with the ajax script.
Any help please
function addCode(key) {
var code = document.forms[0].code;
if (code.value.length < 4) {
code.value = code.value + key;
}
if (code.value.length == 4) {
document.getElementById("message").style.display = "block";
setTimeout(alarm, 1000, code.value);
}
}
function alarm(code) {
$.ajax({
method: "POST",
url: "alarm.php",
data: code,
cache: false,
success: function(responseText) {
console.log(responseText) // show returned text in console
}
})
emptyCode();
}
function emptyCode() {
document.forms[0].code.value = "";
}

The issue is because you're just sending the value by itself with no key. To fix this you could provide data with an object that will be form encoded when the request is sent:
data: { code: code },
Then in your PHP code you can retrieve the posted value by its key:
$code = $_POST['code'];

Related

Excel JS - how to get data from a sheet and then send a GET request

I am trying to get a URL in cell A1 in my sheet and send a GET request using that URL using ajax. However I could not make it works, ajax returns empty results.
Excel.run(async function(context) {
var sheet = context.workbook.worksheets.getItem("Sheet1");
var range = sheet.getRange("A1");
range.load("values");
await context.sync().then( function() {
var URL = range.values[0][0]
$.ajax({
type: "GET",
url: URL,
success: function (data) {
console.log(data);
},
error: function(errorMessage) {
console.log(errorMessage);
}
})
})
})
ajax works if I call it outside and before await context.sync().... but I need to put it inside otherwise range.values[0][0] would not be loaded yet and URL would be undefined.

Javascript post request one key and multiple values

I have a script to submit an array of id's to be deleted. The script is not tied to a form.
The data is in the form of {'id': [1,2]}.
When I run the script, the form data is changed to id[]: 1
I have tried $.param(), but that just creates a single string.
I could join 1,2 into a string (i.e. {id: "1,2"}, but would prefer to avoid that. Any suggestions?
function delete_messages(event){
let data = {id: [1,2]};
event.preventDefault();
let parameters = {
url: '/message/delete'
type: "POST",
data: data,
dataType: "html"
};
addcsrf();
$.ajax(parameters).done(function(data){
alert("successfully deleted");
})
.fail(function(data){
alert("failed to delete");
});
}
Flask Code
#bp.route('/message/delete', methods=['POST'])
#login_required
def message_delete():
message_ids = request.form.get('msg_id')
deleted = []
for id in message_ids:
msg = RecipientData.query.get(id)
if msg is not None and msg.user_id == current_user.id:
msg.update(status='trash')
return redirect(url_for('main.view_messages', folder="inbox"))
var ids=[];
ids[0] = 1;
ids[1] = 2;
In the ajax request, change the data as given below:
data: {ids:ids},

JQuery/AJAX call is not hitting Spring MVC controller

I am trying to verify username and other fields while creating a change password page.The problem is AJAX call in Jquery script is not hitting my controller.i tried giving hard coded path also in url field of the ajax request.
Below is my Script
this checkUname function is triggering on onblur event from one of the input field.
<script type="text/javascript">
function checkUname()
{
// get the form values
var uName = $('#username').val();
var secQues = $('#secQues').val();
var secAns = $('#secAns').val();
var dataObject = JSON.stringify({
'uName' : uName,
'secQues': secQues,
'secAns' : secAns
});
$.ajax({
url:"validateCredentials.do" ,
type: "POST" ,
data: dataObject ,
contentType: "application/json; charset=utf-8" ,
dataType : 'json' ,
success: function(response)
{
alert(response);
} ,
error: function()
{
alert('Error fetching record.... Sorry..');
}
});
}
</script>
This is my MVC controller
#Controller
public class ArsController
{
#RequestMapping(value="validateCredentials.do", method = RequestMethod.POST)
public String changePass(#RequestParam("uName") String uName ,#RequestParam("secQues")String secQues,
#RequestParam("secAns") String secAns)
{
System.out.println("AJAX request");
Users dummyUSer = null;
String msg = null;
try
{
dummyUSer = servObj.findUser(uName);
}
catch (ArsException e)
{
System.out.println("error occurred while validating user data during password change");
e.printStackTrace();
}
if(dummyUSer == null)
{
msg = "No user exists with this username";
}
else
{
if(!secQues.equals(dummyUSer.getSecQues()))
{
msg = "Security question is not correct";
}
else
{
if(!secAns.equals(dummyUSer.getSecAns()))
{
msg = "Security answer does not match";
}
}
}
return msg;
}
Instead of using RequestParam in controller, you should use String. Because when we are posting JSON data it will not come as individual parameters in Request, instead it will be received as String in your controller. Once you get the String convert it to JSON object and then get your values accordingly.
try remove content-type and data-type.
You are not sending a json that should be parsed in a object, you are sending controller's parameters.
The way to do that is using an object in the Ajax 's data (as you did) but without the content-type or data-type that saying "I'm sending one json parameter"

Ajax can success() handle two type of return?

Working in a C# ASP.NET project with JavaScript/Jquery/jqGrid.
New task is to have a page to i) accept an Excel input file, ii) use the column ID to look up additional information, and iii) generate a new Excel file using some columns from input file and all columns returned from database.
I have completed that, but just want to do a bit more error handling. In the stored procedure, if everything works fine, it returns a data table (or in Oracle term, a CURSOR). If there is an error, I have added a catch block and return an error message.
I modify the AJAX call. Beside adding dataType as 'text', I expect the return as XML.
$.ajax({
// POST
// URL: url to call that stored procedure
dataType: text,
success: function (response) {
// now the response is XML (don't know why...
// specify dataType as 'text', but get XML...)
// If response contains 'string' tag, report error.
},
failure: ...
})
Here is what I used to do. I don't specify the dataType but somehow that works.
$.ajax({
// POST
// ... rest is same but without the dataType
success: function (response) {
Download( response )
// The file is already and placed in Download directory.
// Call 'Download()' will actually make the download happen
// But here response is just a path to the Download directory +
// download file name.
And Download() is:
function Download(url) {
document.getElementById('my_iframe').src = <%=ResolveUrl("~/")%> +url;
return false
};
How can I have the success function handle both type of response?
(Just for your information: The front-end page is ASP.NET. Button click will call a JavaScript function. The function calls a web service function via $.ajax(). As there are many rows, the web service function calls a function in a database class many times - each time pass in just one ID. The function will in return call stored procedure.)
Edit: Thanks for solution from Mustapha Larhrouch. Here are some points that I have to adjust:
Add dataType.
If response is XML, check if error.
If not XML, just download.
And here is my code:
$.ajax({
// POST
// URL
dataType: "text",
success: function (response) {
if (isXML(response)) {
var xmlDoc = $.parseXML(response);
$xml = $(xmlDoc);
var errMsg = $xml.find("string").text();
if (errMsg != "" ) {
// pop up a dialog box showing errMsg
}
}
else {
Download(response);
}
you can check if the response is an xml if it's parse it, if not the response is a string. and you can use this function to check if the response is an xml :
function isXML(xml){
try {
xmlDoc = $.parseXML(xml); //is valid XML
return true;
} catch (err) {
// was not XML
return false;
}
}
$.ajax({
// POST
// ... rest is same but without the dataType
success: function (response) {
if(isXML(response){
Download( response )
}
else{
//report as error
}

Parse an Array of Javascript Objects using JSON and AJAX

I have an array of Javascript objects, which I convert to a string using JSON.stringify() before processing with AJAX.
On the server side, all I am trying to do is verify that the proper $_POST["flavors"] variable is set, and output it's contents. I have verified (via a simple conditional) that the $_POST["flavors"] is being set, but I don't know how to modify the ajax call (or the PHP) to properly output it's contents.
I have read on here that I (may) need to set the dataType for the $.AJAX call and/or set the header in my PHP script, but I wasn't sure if setting the header would be applicable since it is inside my functions.php file. *
(Array function)
flavors = [];
function wholesaleAJAX() {
var sizeSelect = $('form#wholesale-size-form input:checked');
if (sizeSelect.val() === 'regularBag') {
$('select[name="wholesale-flavors-regular"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-regular-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
} else if (sizeSelect.val() === 'largeBag') {
$('select[name="wholesale-flavors-large"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-large-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
}
(Stringify the array and process AJAX)
stringArray = JSON.stringify(flavors);
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: "returnHash",
flavors: stringArray
},
success:function(data){
$("#ajax").html(data);
}
});
(PHP for processing AJAX in functions.php)
function returnHash() {
if (isset($_POST["flavors"])) {
$flavors = json_decode($_POST["flavors"]);
print_r($flavors);
} else {
echo 'Not Set';
}
die();
}
add_action('wp_ajax_returnHash', 'returnHash');
add_action('wp_ajax_nopriv_returnHash', 'returnHash');

Categories

Resources