I feel like I am missing something here.
To start, you have an AJAX call you can do in tag to post data to the backend, which looks something like,
function changeDom(){
console.log('connecting');
$.ajax({
url: '/loadOrders',
method:'POST'
}).done(function(data){
if(data.success){
$('#recentOrders').append(data.message);
changeDom2();
return;
}
}).fail(function(){
console.log('failed');
return;
});
};
And on the backend you receive it with code that looks something like,
app.post('/loadOrders', function(req,response)
{ // code here });
I have seen that it is possible to pass a parameter along an AJAX call, which looks like,
$.ajax({
url: '/loadOrders',
method:'POST',
data: {field1: 'this is data being passed'}
}).done(function(data){}});
But how would I receive that data on the backend? How would that change in syntax look and how would I call the parameter?
You can get it by doing
req.body.field1
Related
I am using ColdFusion 11. I inherited an application which uses the mm_wizard_login ColdFusion feature for their login functionality. Now I have to implement the change password functionality in this application. So if the user logs in and the application finds that this user is logging in for the first time, it should redirect the user to change their initial password.
So I decided to use a jQuery third party modal plugin.
I have added the jQuery plugin functionality in the mm_wizard_login.cfm page. During the authentication process, the scenario where the user needs to change password, the mm_wizard_authenticate.cfc denies the login and redirects them back to the mm_wizard_login.cfm page and then the plugin opens up and allows user to type in their new password. After the user clicks the submit, in jQuery I am intercepting their submit and I am making an AJAX call to another cfc which is accepting the new password and calling a SQL Server stored procedure to change their password. This cfc method returns JSON back to the AJAX call but the returning value is not JSON, it is returning the HTML for the mm_wizard_login.cfm page itself.
Everything is working, except the AJAX call which is expecting JSON.
In Chrome dev tools, I went into the network tab and under response tab, It is returning back the HTML for mm_wizard_login.cfm page. I don't understand this.
Here is my AJAX call below:
var refData = $.ajax({
url: 'testmethod.cfc',
method: 'POST',
dataType: 'json',
data:{
method:'ChangePassword', //Call the method
jsonData: JSON.stringify($(formdata).serializeArray())
}
})
.done (function (d) {
if (d.Result == 'OK')
$("#modal-custom").iziModal('#modal-custom','setTitle', d.message);
$("#modal-custom").iziModal('#modal-custom','close');
else{
changePwd_ErrorHandler(d.message);
}
})
.fail (function (XMLHttpRequest, textStatus, errorThrown) {
changePwd_ErrorHandler(textStatus + '. Please try again');
});
After nothing worked then I just tried a basic AJAX call from my mm_wizard_login.cfm page, here it is below:
var test = $.ajax({
url: 'testmethod.cfc',
method: 'POST',
dataType: 'json',
data:{
method:'MethodTest', //Call the method
}
})
.done (function (d) {
})
.fail (function (XMLHttpRequest, textStatus, errorThrown) {
alert('Unable to change password. Please try again');
});
This is not working either. It is returning the same thing. Not JSON but the HTML content of mm_wizard_login.cfm. Please help.
This is my test cfc function which is being called from the login page.
[Upate] My test cfc method:
<cffunction name="MethodTest" access="remote" output="true" returntype="string" returnformat="json" hint="Adds/Edits User Info .">
<cfset retJSON = '{"Result": "Error","message": "Action Failed", "TotalRecordCount":0}'>
<cfreturn retJSON>
</cffunction>
I need to load some data (A WordPress Menu) from an external REST API into my Shopify template. I'm assuming I need to use an App proxy to do this. I've looked through the documentation but I'm a little confused as to how to go about this.
Can anyone point me in the right direction?
I often use jquery with an ajax call to an api end point that either
sends me back formatted html
send me back json data that I parse and form the html via javascript.
jQuery(window).load(function(){
data = {};
jQuery.ajax({
type: 'GET',
url: 'https://yourapp.herokuapp.com/yourendpoint.json',
data: data,
dataType: 'json',
success: function(data) {
console.log(data);
$.each( data, function(i, item) {
console.log(item);
// do something with your data here
});
}
});
});
I’m using jQuery to make an AJAX call to Node.js to get some JSON. The JSON is actually “built” in a Python child_process called by Node. I see that the JSON is being passed back to the browser, but I can’t seem to parse it—-although I can parse JSONP from YQL queries.
The web page making the call is on the same server as Node, so I don’t believe I need JSONP in this case.
Here is the code:
index.html (snippet)
function getData() {
$.ajax({
url: 'http://127.0.0.1:3000',
dataType: 'json',
success: function(data) {
$("#results").html(data);
alert(data.engineURL); // alerts: undefined
}
});
}
server.js
function run(callBack) {
var spawn = require('child_process').spawn,
child = spawn('python',['test.py']);
var resp = '';
child.stdout.on('data', function(data) {
resp = data.toString();
});
child.on('close', function() {
callBack(resp);
});
}
http.createServer(function(request, response) {
run(function(data) {
response.writeHead(200, {
'Content-Type':
'application/json',
'Access-Control-Allow-Origin' : '*' });
response.write(JSON.stringify(data));
response.end();
});
}).listen(PORT, HOST);
test.py
import json
print json.dumps({'engineName' : 'Google', 'engineURL' : 'http://www.google.com'})
After the AJAX call comes back, I execute the following:
$("#results").html(data);
and it prints the following on the web page:
{“engineURL": "http://www.google.com", "engineName": "Google"}
However, when I try and parse the JSON as follows:
alert(data.engineURL);
I get undefined. I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Could anyone advise if I’m doing something wrong building the JSON in Python, passing the JSON back from Node, or simply not parsing the JSON correctly on the web page?
Thanks.
I’m almost thinking that I’m not actually passing a JSON Object back, but I’m not sure.
Yes, the ajax response is a string. To get an object, you have to parse that JSON string into an object. There are two ways to do that:
data = $.parseJSON(data);
Or, the recommended approach, specify dataType: 'json' in your $.ajax call. This way jQuery will implicitly call $.parseJSON on the response before passing it to the callback. Also, if you're using $.get, you can replace it with $.getJSON.
Also:
child.stdout.on('data', function(data) {
resp = data.toString();
// ^ should be +=
});
The data event's callback receives chunks of data, you should concatenate it with what you've already received. You probably haven't had problems with that yet because your JSON is small and comes in a single chunk most of the time, but do not rely on it, do the proper concatenation to be sure that your data contains all the chunks and not just the last one.
I'm working on jQuery Mobile application which should get the data from the webservice based on the selected item in the form in jQuery mobile.
$("#catalogue").live('click',function(){
$.ajax({
type: "GET",
url: "LifeService\log",
data: "json="+$("prodcat");,
dataType: "json",
success: function (msg) {
alert(msg);
}
});
});
This function doesn't return anything. When I simply run the webservice in browser with the value, I get the success message. Can anyone tell me how to call the webservice from jQuery Mobile?
Where are experiencing a problem? Posting the code you've got so far would help. jQuery offers the getJSON() function you need, and you can then parse the resulting string back into a usable JSON object with parseJSON().
I have a modal dialog (done through jquery UI) that submit a form to a remote controller Action.
This is the jquery function called:
$("fpForm").submit(function() {
$.ajax({
type: "POST",
url: "ForgotPassword",
data: $("#fpForm").serialize(),
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
}
});
});
The action does some verification on the data and then send back a response in JSON format. Let's say, for example, that this is a sample response:
{"result":"NOK","message":"The user is not registered on the system"}
My questions are:
Why the debug alert that I have set in the "success" and "error" block does not are get executed?
How I can write my code to parse the response while remaining in wait for it on the dialog?
How can I write code to block the form elements during the ajax call?
I am sorry if the question could seem stupid for most of you but I am completely new to ajax and I am trying to learn throgh some experienced pattern that I know.
Thank you for your responses
The first error is the usage of $("fpForm").submit instead of $("#fpForm").submit.
If the server sand back JSON data, for example as JsonResult, you should include dataType: "json" to convert result to the object in object. After that you can replace alert(response); to
alert('Result: ' + response.result + ', Message: ' + response.message);
To block the form element I'll recommend you to use jQuery BlockUI Plugin. On the demos you will find different examples of usage and find the way which you like.
My questions are:
Why the debug alert that I have set in the "success" and "error" block
does not are get executed?
How I can write my code to parse the response while remaining in wait
for it on the dialog?
How can I write code to block the form elements during the ajax
call?
If you meant to use the id then you missed the # designator:
$("#fpForm")
Add the sync : true option on the call?
You could either: set the disabled attribute on the form elements AFTER posting the request, or else mask the page with an element (possibly semi-transparent) to divert the inputs.