I have links like
http://example.com?query1=query1&query2=query2 as href of anchor tag.
I want to do post ajax on href click using data from the query parameter from the link.
I have written code
$("a").bind('click',function(){
$.ajax({type:'post',url:$(this).attr('href'), success: function(data){
alert(data);
}})
return false;
});
but it does not send query parameter inside ajax post request. Request query data length is 0.
how can I change this code to manipulate data from query parameter of link ?
Edit
Sorry my bad but it is not working these are the request
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:0
Query String parameter
action:delete
id:12
So these fields are not going inside request content.
You need to use the value of the href attribute, not just the jQuery object itself.
url:$(this).attr('href').val()
Update
Although you said this answer worked for you, I made a mistake. val is not a valid function of attr however doing it the original way you had it works for me.
See this demo: http://jsfiddle.net/PuyzU/
Update 2
Ok, I see your problem now. It wasn't atall clear from the question what you meant.
Let me rewrite your question here to make sure I'm on the right track.
I want to take the querstring parameters of a URL and use them in my ajax
POST action. How do I do that with jQuery?
In your ajax post method there is a property data where you'll store the data you want to post to the server.
$.ajax({
type: 'post',
url: "http://[...],
data: DataToPostToServerHere
[...]
In this case we can obtain the querysting parameter values as a single string by splitting our URL on the ? and use the first portion of the array as the URL and the second portion as the data we're sending:
var urlFull = $('#myLink').attr('href').split('?');
urlFull[0] // Our URL
urlFull[1] // The data to put into the data property for posting.
Working Example
Related
I am trying to pass a list of subject id's as a query param in an Ajax get-request, so that it only returns data pertaining to the subject id's I passed in. The API is set up to receive a subjectId param as a single number, or string of numbers separated by commas. I have made sure that what I am sending is exactly that -- "13,14,15" -- but when I make the request, the get URL encodes the string so that it looks like this: 13%2C14%2C15%2C.
The URL I want to generate is (I'm just using placeholders for the domain name and session token) https://get-url.com/get-filter-counts?sessionToken=abcdefg&subjectId=13,14,15. When I test this out in the browser, it works.
The URL I'm actually generating is https://get-url.com/get-filter-counts?sessionToken=abcdefg&subjectId=13%2C14%2C15%2C
I've tried researching this issue but I'm not even sure what it is that's happening there. I've looked at a ton of examples of passing strings as query params in an Ajax request, and as far as I can tell I'm doing it correctly. I've hard-coded a string into the params below just to demonstrate:
$.ajax({
type: "GET",
url: getURL,
dataType: "JSON",
data: {
sessionToken: sessionToken,
subjectId: "13,14,15"
},
//process the returned result of the Ajax call
success: (ajaxResult) => {
console.log("subject id list:", subjectId);
console.log("Ajax result:", ajaxResult);
},
In the success method, the console returns the correct subjectId list as well as the data pertaining to those subject id's. But I am unable to get the results in the browser because of this URL issue.
How can I remove the encoding (if that's what's happening?) from the string in the url? Thanks.
The issue is with using commas in-between numbers. The string you are sending from the frontend is getting encoded and hence the URL you see. If you try encodeURIComponent(13,14,15) you'll see the same response.
The solution would be using something other than commas and handling that on the backend or simply sending an array.
Well, I was sending the string of numbers with a trailing comma at the end (I didn't think that would be an issue), and it turns out that's why the server wasn't properly handling the encoded URL. Just sharing in case this is useful for anyone else who looks at this question.
The comment from #Quentin was essentially correct, except the issue was in fact a frontend typo.
If I run a get request like this:
$.ajax({
url: 'http://localhost:8000/api/points/',
contentType:"application/json",
dataType: "json",
data: JSON.stringify({"content_type":content_type,"object_id":object_id}),
type: 'GET',
}).error(function(r){ $(output).text('error') })
.success(function(r){
$(output).text(r.count);
})
Its request goes to:
http://localhost:8000/api/points/?{%22content_type%22:8,%22object_id%22:40}
Obviously that's bad. It works okay if I don't do JSON.stringify(), but why is that?
Curiously if I do a POST request it's the opposite! I have to stringify the data or it won't work. So why the difference?
First of all let's fix your request:
var req = $.ajax({
method: "GET",
url: "http://localhost:8000/api/points/",
dataType: "json", // is you telling jQuery what kind of response to expect.
data : {id : '12345'}
});
req.done(function(data){
// do something with the data
});
req.fail(function(jqXHR, status, err){
// do something in case of failure
throw err;
});
Next get to know what you are dealing with :
data : PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded".
Note: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
At last:
No need for : JSON.stringify({"content_type":content_type,"object_id":object_id}) as it is a wrong way to do it with JSON.stringify just :
{ 'content_type' : 'type', 'object_id' : 'id' }
Urahara's answer contains some useful suggestions, but does not seem to address your question.
Well, it seems that your server side code is expecting to find a json object in the body of the POST request. Why would that be? Because you specify that the content type be "application/json". So in the case of a PUT case, when you use JSON.stringify your data in the $.ajax call is a string that happens to represent a JSON object. This is passed as is and so this works. You end up sending something like
{"content_type":8, "object_id":40}
as the body of your POST request and your server side code is happy to process this. Not sure exactly what your server-side technology is, but presumably it also binds content_type to 8 and object_id to 40, which makes you happy :-)
But when you do not use JSON.stringify to turn the object into a JSON string, you end up passing the object itself to $.ajax having it turn it into a string in the way it knows how. Well, it only knows only one: the good old url-encoding way. So the server, would still be expecting a JSON object but would instead be getting
content_type=8&object_id=40
as the body of the PUT request. It will not be happy. This is not a JSON object like your content-type promised! :-)
Now, moving on to the case of a GET request. Here the content-type is pretty much irrelevant as the message body will be empty. If you use JSON.stringify what you pass as the request data is a weird JSON-object representing string and the monstrosity that you get as a URL
http://localhost:8000/api/points/?{%22content_type%22:8,%22object_id%22:40}
is as you 'd expect not very well received by the server. What the server is happy with is something like
http://localhost:8000/api/points/?content_type=8&object_id=40
Which is exactly what $.ajax produces when you do not use JSON.stringify but rather pass it a nice pair of attribute-value pairs. It just url-encodes them, exactly like it did in the PUT case, and the server is happy.
So $.ajax always url-encodes objects consisting of attribute-value pairs. This is fine in most cases. One way to fix your code to do a POST without using JSON.stringify would be to simply not put a content type parameter in the $.ajax call (in which case the default, 'application/x-www-form-urlencoded; charset=UTF-8' will be used).
But if you want to pass more complex, deeply hierarchical objects, using some object serialisation format you have to set the appropriate content type and pass the data as a string using the corresponding encoding (JSON, XML, etc.) like you did here.
Hope that answers your question :-)
Please also have a look at http://api.jquery.com/jquery.ajax/
I have an HTML file referencing a PHP script to perform various functions. One of the ways the HTML file calls the PHP script is through an HTTP GET. The GET request should pass three parameters and return a list of all saved events as a JSON-encoded response.
So far, I have the following but I'm not sure how to pass the three arguments through the HTTP GET. Also, I'm not sure if I am returning the JSON-encoded response correctly:
if($_SERVER['REQUEST_METHOD'] == 'GET'){
echo json_encode(events.json); }
GET requests are done through the URL... So if you want to pass three GET requests you would do...
http://www.domain.com/target.php?param1=whatever¶m2=whatever¶m3=whatever
target.php represents the PHP script file you want to send the information to. You can have as many variables as you want but just keep in mind that every other GET request has to be separated by an & symbol. The first param simply has to be started off with a ? symbol.
If you want to use Javascript, I would recommend using JQuery. You can do something like this
$.get('target.php?param1='+whatever+'¶m2='+whatever2, function(data) {
alert(data);
});
Or you can use window.location to send a link with the appropriate link above.
If you want to use AJAX specifically, here is a way of doing it with JQuery (there are ways with Javascript that I could update later if necessary:
$.ajax({
type: "GET",
url: "http://www.domain.com/target.php",
data: { param1 : "whatever", param2 : "whatever", param3 : "whatever" },
success: function(result){
//do something with result
}
})
If you want to access the variables, you can call $_GET['param1'] or $_REQUEST['param1'] to get access to them in PHP. Simply change the name in the brackets to the desired variable you want and store it in a variable.
If you want to access the params with Javascript... well the most efficient way is to go and decode the URL that was used and pull them out. See here
Hope this helps!
You can access the parameters from the URL via the $_GET superglobal in PHP.
For example, if your URL is http://example.com/test.php?param1=foo¶m2=bar, then you could access them in PHP like so:
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
See http://www.php.net/manual/en/reserved.variables.get.php for more details.
As for returning a valid JSON response, you can check out this answer. It uses PHP's header function.
in my code i have:
$.ajax({
url: 'http://chapters.zmgc.net',
dataType: 'jsonp',
success: function(d){ // "Type","Name","Link","Contact","Location","Icon"
Tabzilla.zgContacts = d;
var countries = [];
d.rows.forEach(function(row){
if (row[0] == 'Country') countries.push(
{link:row[2], contact:row[3], country: row[4]}
);
});
but i get an error, Uncaught SyntaxError: Unexpected token :
{
"kind": "fusiontables#sqlresponse",
....
if i replace the url with the actual file and remove the dataType, all works as expected!
i have validated the output of http://chapters.zmgc.net at http://jsonlint.com/ and it is ok.
looking at the response headers returned from http://chapters.zmgc.net, it is:
Connection:keep-alive
Content-Type:application/json
Date:Thu, 13 Dec 2012 17:02:27 GMT
Transfer-Encoding:chunked
here is the code https://github.com/tomarcafe/Z-Tabzilla/blob/gh-pages/z-tabzilla.js#L282 i would like to replace the local file with reading the remote data?
what am i missing?
You shouldn't set type to jsonp, That is JSON with padding, in that it is assumed that response is wrapped inside a function call.
callback({payload: values});
and will tried to be executed.
Instead use type: json, or simply $.getJSON which will correctly pass the JSON payload with $.parseJSON.
It's because you're asking for JSONP (JSON with padding) and getting JSON without padding. JSONP is JSON that is padded by a function call, and the only way to get it to work is by adding support for JSONP on the server.
If you don't have access to chapters.zmgc.net you'll have to contact them and ask them to add support for JSONP.
If you do have access you can add ?callback=parseThis to your url and then read that variable on server-side and pad your JSON accordingly:
parseThis(/* put your json in here */);
However, if you don't define your own callback, jQuery will add one automatically that you can use. They will look something like this: jQuery18200710562220774591_1355419375476
As Ajax uses jsonp (json with padding) but your url doesn't seem to be jsonp compatible, so you have to avoid using that.
from jQuery:
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
more here : http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/
.ajax() can send a post request and get data in return where as .load() can get any element in the rendered page. How to create a form when submitted(asynchromously) instead of getting back some data should get the page element of the rendered page that would be generated had there been normal submission instead of ajax submission?
I dont want to write views(Django) for xhr, normal requests separately. So, When I submit a form by ajax I dont want to hijack default action but only want to get some element of the rendered post submission page instead of actually being redirected to that post submission page which would have happened hadn't it been an xhr request.
Update:
load will do a POST rather than a GET if you supply the data to send as an object rather than a string. From the docs:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
So:
$("#target").load("/path/to/resource selector_for_relevant_elements", {});
..should convert the load from GET to POST. Of course, you'd replace {} with the arguments you want to send.
Original answer:
You can do the POST directly with ajax and then process the returned HTML yourself. For instance, to turn this load:
$("#target").load("/path/to/resource selector_for_relevant_elements");
..into a POST:
$.ajax({
url: "/path/to/resource",
method: "POST",
dataType: "html",
success: function(html) {
// Build the elemnts of the result in a disconnected document
var page = $("<div>").append(html); // See note below
// Find the relevant elements and put them in target
$("#target").html(page.find("selector_for_relevant_elements"));
}
});
I've done the wrapper div because that's what jQuery's load function does. You may want to look at the source for load (that line number will rot, of course, but the filename is unlikely to change) to see if there are other tricks you need to replicate.