It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
$.ajax({
type: "GET",
data: "id="+id+"&id-other="+id-other,
url: "ajax1.php"
}).done(function(data){
$("#div").html(data);
});
I have the code piece above, I search the web but I don't know how to explain what it is for. Is there any tutorials of ajax basics explaining step by step of what
$.ajax() means, what type:Get does, what data:... does etc ?
It is making an ajax (asynchronous) call to a remote page.
type: get
It is a HTTP Get request. The form data will be encoded in the url as query string values.
data: "id="+id+"&id-other="+id-other
This the data being passed to the server page
url: "ajax1.php"
ajax1.php is the server page which handles the ajax request and reponds back,
.done(function(data){
$("#div").html(data);
})
The code which inside the done event will be executed once the ajax call is completed. In this case we will get the response from the ajax call to a variable called data. We are setting that as the innerhtml of some HTML element with an id div.
read this link for more info : http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "GET",
data: "id="+id+"&id-other="+id-other,
url: "ajax1.php"
}).done(function(data){
$("#div").html(data);
Its really simple, we start by declaring AJAX function, then we declare the method(get or post - just like html form), data is used the parameters to be passed through URL. URL is the file which is invoked(just like action in forms). This will invoke your ajax1.php file and return some data, that data is returned in the success function or done function. In your case the data is the data returned from your php file.
Related
I am building an express project, using ejs as a view engine, and AJAX for front-end http calls.
When I post a request such this:
$.ajax({
type: 'POST',
data: {'nickname' : $('#nickname').val()},
contentType: 'application/x-www-form-urlencoded',
url: 'http://localhost:5000/create',
success: function(data) {
$('#message').text("Unkwon error");
},
error: function(data){
$('#message').text('Something went wrong, check connection!');
}
The Ajax keeps waiting for a response, which I am not willing to give, as I just want to render a view as follows :
app.post('/create', urlencodedParser, (req, res)=>{
let code = unique.generate(rooms);
res.render('chat', {'nickname' : req.body.nickname, 'code' : code}
Any ideas how can I work around this?
After some research, I found a way to do it.
Basically, I can just tell the Ajax to attach the document sent from rendering to the html body
$('body').html(data);
Surprisingly, this works event with Ejs dynamic tags.
I know it's not the best way to do it, but it's the only one I found till now.
EDIT 1:
After few months, I realized the solution is simple as just changing the Location using javascript
window.location.replace(`http://localhost:5000/newRequest`);
Now, I could handle this new request separately on the server.
EDIT 2:
After couple years now, I realized a GET request might have solved the problem in a single round trip.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Being a beginner with JavaScript and related frameworks, I'm sorry if my question seems stupid.
Anyway... Are there some native techniques for load and display webpage contents asynchronously with Node.js and Express? Should it be used the XMLHttpRequest object for the purpose or exist better alternatives?
Best regards, Vi.
I can help you with the first section of your question, like #JohnnyHK said, it's to broad issue. What i'm going to explain here is how to load the raw data of a webpage using node.js and express and send it back to the client inside a json object.
Lets start with our request
Our goal is to enter the following URL in the browser and get the raw data (html source) of the page: http://localhost:8080/www.yahoo.com
http://localhost:8080 - Where our node.js/express server is running
www.yahoo.com - The DOMAIN of the site that we want to get the source from - http:// is not needed
And now, to the server code
Note that this is a very simple/basic server, so you better improve it in your side
var http = require('http'); // the http `native` module of node
var express = require('express'); // the express :)
var app = express(); // creating the server...
app.enable("jsonp callback"); // enable jsonp callbacks
app.listen(8080); // listening to port 8080.
app.get('/:domain', function(req, res){ // each request to the pattern `http://localhost:8080/URL_HERE
// building the http `options` param
var options = {
host: req.params.domain, // the host will be the `domain` we sent
port: 80, // the port the website is running on (basically post 80)
path: '/', // the path, now, this is important to pages inside
// the website, if you want the source of
// `http://www.website.com/path/to/page.html` you better
// transfer `/path/to/page.html` as another param to the
// request and put it here
method: 'GET' // well, you know...
}
var buffer = ''; // i'm creating a buffer to hold the data
http.get(options, function(httpres){ // creating the request with a callback function
httpres.setEncoding('utf8'); // setting the encoding for the data...
httpres.on('data', function(chunk){ // listening to the `data` event, each chunk will get into this function
buffer += chunk; // saving the data...
});
httpres.on('end', function(){ // listening to the `end` event will be raised when we got all the raw data
res.json({ // this is it, now we are sending a response to the client as a json
success: true,
data: buffer
});
});
});
});
This is it, mow you can combine this solution with a jsonp and you are good to go...
Client side
Lets use a jQuery jsonp request to get the data:
function loadData (domain) {
$.ajax({
url: 'http://localhost:8080/' + domain
cache: false,
dataType: 'jsonp',
jsonp: 'callback',
data: { },
success: function (response) {
if(response.success) {
console.log(response.data); // `response.data` holds the html
// data from the server, do what you want :)
}
}
});
}
The second part of your question is about how to display the data in the client, my suggestion is to create an iframe and inject the raw data into it, you will have some problems in the way (like relative css and javascript file paths) but I hope you now have a start point...
Cheers :)
UPDATE
One more thing.. this example works only for http protocol websites... if you want to get the data from a https website you need to use the https module instead of the http ( var https = require('https'); ) and in the options, use port 443...
I'm not 100% sure what your question is, but I'm guessing you're looking for a way to get data on the server side for asynchronous requests on the client side.
In express, in your router, after you've retrieved some data, use the following to send back a JSON object that your javascript can use on the client side:
res.send(JSON.stringfy(data));
The best way to learn this is probably to do a google search for an example that uses the technologies you want to use. For instance, I just did a google search for Express Mongoose JSON (where Mongoose is the Data Model for the MongoDB database) and I found this: A simple Node.js web application that uses Mongoose, Express and MongoDB and returns JSON
There are alternative frameworks for Node (other than Express), and there are other databases as well, so there are many ways to accomplish what you're asking for. Also, the client-side has frameworks to make things easier as well, like JQuery.
I am unsure as to how I access variables that I have posted using ajax in my controller. I though it might be something along the lines of:
$this->request->data['post']['varName'];
I don't think that is the correct way to access the variables I have posted as it doesn't seem to work, so my question is: "What is the correct way to access post variables in a CakePHP controller". For completeness I will include an example jQuery ajax call. If you could refer how to access the data with the example below that would be great
$.ajax({ type: "POST",
url: "someURL", // Not an actual URL just placeholder for example
data: {'foo': 5, 'bar': 12},
success: function()
{
alert('Post was successful');
}
});
So how would I access foo and bar in a cakePHP controller?
Also if you know where to find this information in the documentation could you please link me to it as I had a hard time finding the information.
Update!
Found the link to the documentation here.
Is $this->request-data['post']['varName']; a typo? If not, then you have a syntax error after the request property where you need a ->.
I think your problem could be solved by using this though:
echo $this->request->data['foo']; // Should print 5
echo $this->request->data['bar']; // Should print 12
I've been looking around the forums without a solution to my problem. It's pretty simple, really, and I'd appreciate it if you could explain your answer if you would be so kind.
I'm new to AJAX and Javascript, and I need to send one variable from my javascript code and basically "convert" it into php. Here's what I have so far:
var selected = rowData.ID
jQuery.ajax({
url: "test.php",
type: 'POST',
data: { selected },
cache: false
});
I use this selected value further down in the code. I use PHP to display the (value of selected).
"vars": [
"(value of selected)"
],
However, I can't seem to make my ajax request work and send the variable to my PHP file. Here's what my PHP file looks like:
$row = $_POST["selected"];
Thanks in advance for the help.
try replacing your "data:" with this:
data: { 'selected': selected },
So this is very delayed answer, but I was having trouble getting a variable to send too. I'm not using php, but saw loads of examples like vlscanner gave, but who knows why it didn't work.
I stumbled across this explanation of how to send multiple parameters, and it works just as lovely for sending one parameter.
http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods
multiple:
data: JSON.stringify({ Album: album, User: user, UserToken: userToken }),
or just one:
data: JSON.stringify({ Album: album}),
I'm no expert on timing,efficiency and all that, and it's possible that JSON.stringify adds unnecessary bulk and there is possibly some valid reason that sending data without the JSON.stringify didn't work. However, if you are in a bind and need something to work, this might help those of us still asking this question.
I'm suspecting that mine did not work because I was sending it to an asp method that likely requires the parameters to come as a JSON string. I have to research that next. Every step is a new discovery.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Im trying to get the .load method to post to a page and then echo back what was posted to see if it is working, i can't get this to work. I tells me that the variable is undefined, here is what i have:
teachers.php:
<?php
echo $POST['class'];
The JS:
$('#test').load('teacher.php', {class: 'test'});
That is triggered once something is clicked.
#test is a <div> that I want the data to post to.
Thanks for the help.
It's $_POST instead of $POST. Don't know if that was a typo, but that will also create some issues.
Most of the times problems like these are due to the asynchronicity of AJAX.
Everything you load via AJAX (with .post(), .load(), .ajax(), .get()) doesn't "exist" unless the AJAX round trip of request-response has been completed.
Be sure to "use" what you load with AJAX (a HTML bit, a JSON response, ...) in a callback function, that is called on the success of the AJAX request.
For example let's say my page ajax.php returns this string: <div id='ajaxdiv'>hello!</div>, we want to load this (HTML) string in #mydiv:
$("#mydiv").load("ajax.php");
console.log($("#mydiv #ajaxdiv")); <- undefined
It won't work because the code continues regardless of the completion of the request. Instead:
$("#mydiv").load("ajax.php", function () { console.log($("#mydiv #ajaxdiv"));});
works because JQuery makes sure to use the callback function only if the request has been completed.
(You can also add parameters like your {class: test}, just put them between the URL and the callback function).
Edit: use $_POST and not $POST.
if your just trying to post information from jQuery to a PHP file when something with the id of test is clicked then do this:
teachers.php:
<?php
echo $_POST['class'];
?>
The JS:
$('#test').click(function() {
$.post('teacher.php', {class: 'test'},
function(output) {
//output = what is echoed from the php file.
alert(output);
);
});