how to make a post call in jquery - javascript

I wrote this jquery code:
$(document).ready(function () {
$("#testDiv").load("http://localhost:7908/ToLoadAjax.aspx");
});
It seems it is a Get http request.
How to make it a post call please?

$(document).ready(function () {
$.post('http://localhost:7908/ToLoadAjax.aspx', function(data) {
$("#testDiv").html(data);
});
});

Use $.post() see the documentation for more informations.

Since you asked:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Btw, read the documentation! https://api.jquery.com/jQuery.post/
But it doesn't make any difference do either a GET or a POST unless you are really sending in any data.

Related

JSON issue with jQuery (JSONP)

I have a strange issue using jQuery and JSON, especially JSONP.
My goal is to simply GET JSON data, but I always end up with the following error:
Uncaught SyntaxError: Unexpected token
Here is the code:
<script type="text/javascript">
$(document).ready(function() {
var myurl = "someurl";
$.ajax({
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType : 'jsonp',
success: function(result){
//Do something with JSON result
}
});
</script>
And of course the JSON (raw format):
{"result":[{"targetView":"powerUsage","myData":{"someItems":["9","5","8"],"someItems2":[{"text":"protoText","currentRecord":"45.38","absolute":100}]}}]}
I tried the webservice with the Advanced Rest Client App in Google Chrome and it is working perfectly. I have no clue why this simple example gets this syntax error message.
Your Ajax code looks like fine. I think you are trying to make a Cross domain call as JSONP is a hack for dealing cross domain ajax call. If you Server code if ready for dealing with JSONP request then you must have send a callback parameter like
?callback=my_callback_method
than you service will return result with a callback see below links for more details:
https://learn.jquery.com/ajax/working-with-jsonp/
http://stackoverflow.com/questions/11736431/make-cross-domain-ajax-jsonp-request-with-jquery
You missed to put ready function close, that is }); at the last before script tag close:
<script type="text/javascript">
$(document).ready(function()
{
var myurl = "someurl";
$.ajax(
{
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType: 'jsonp',
success: function(result)
{
//Do something with JSON result
}
});
});
</script>

Sending Information to a PHP Script using Ajax

I would like to send an ajax command to a php script each time when a button is clicked. The divs are called r, l, t, b for the different directions. So far I have tried using the code below. But somehow it doesn't work. I have not a lot of experience in jquery and that's why I am asking here for a simple solution. I could write 4 times the same function but this is certainly not what I am looking for.
$(document).ready(function(){
function control(id){
$.ajax({
type: "POST",
url: "control.php",
data: {id: "1"},
success: function(data){
alert(data);
}
});
}
$('#r').mousedown(function(){
control($(this).attr('id'));
});
});
Well first...
Just give all your divs a class
<div id="r" class="direction"></div>
<div id="l" class="direction"></div>
<div id="t" class="direction"></div>
<div id="b" class="direction"></div>
Then rewrite your jquery
$(document).ready(function(){
$('.direction').mousedown(function(){
$.post("control.php",{id: $(this).attr('id')},function(msg){
alert(msg);
});
});
});
If you happen to be receiving JSON from the servers....
You must specify the dataType as 'json' or 'jsonp' for cross domain json and use $.ajax
function control(theid){
$.ajax({
type: "POST",
url: "control.php",
data: {id: theid},
dataType: 'json',
success: function(msg){
alert(msg);
}
});
}
Or if you wanna keep it simple like the above $.post example.....use getJSON
$(document).ready(function(){
$('.direction').mousedown(function(){
$.getJSON("control.php",{id: $(this).attr('id')},function(msg){
alert(msg);
});
});
});
It's hard to know exactly what you are asking, but basically you want a multipurpose click event for multiple divs.
in jQuery, you can add multiple selectors by separating the selectors with commas
like so:
$('#id, .class, element')
Here is an example that uses less code to provide the same functionality, if I understood your question correctly.
$(function(){
$('#r,#l,#t,#b').mousedown(function(){
$.post('control.php',{id: $(this).attr('id')},function(data){
//handle data callback
alert(data);
});
});
});
I used $.post instead of $.ajax , but bear in mind if you use the simpler methods like post, get, or getJSON, you will not be able to assign an error callback as far as I'm aware. Hopefully this changes in future releases of jQuery.
function control(my_id){
$.ajax({
type: "POST",
url: "control.php",
data: {id: my_id},
success: function(data){
alert(data);
}
});
}
Using $_POST['id']; you should get the information you are looking for.

JSONP via getJson not working?

I have getJson like this:
$.getJSON(userUrl+'scanp?callback=?', { 'someparametar': 100 }, function(data){
console.log(data);
});
and I do get a response from my url, and it looks like this:
'"jQuery1110010384737118147314_1401820556204({'hasWon':'false','code':'120580e9fce67a4921f31af7ffa358cc10c83b10','defaultReward':'{\"secure_url\":\"https://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"url\":\"http://res.cloudinary.com/deh0vdgzd/image/upload/v1401318096/k6jrm2pehwycmehrkicz.png\",\"resource_type\":\"image\",\"format\":\"png\",\"height\":960,\"width\":640,\"signature\":\"a8ca9bb867e0a3d99e1666b7891e8f918d81e627\",\"version\":1401318096,\"public_id\":\"k6jrm2pehwycmehrkicz\"}''}"'
Any idea why I don't get any response when I console.log it?
With 'callback' in your querystring, JQuery wraps the response with a randomly generated method name. To get JSON (without method name), remove 'callback=?' from querystring.
If your server supports JSONP, you can make a call like this :
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(JSON.stringify(json));
},
error: function(e) {
console.log(e.message);
}
});
Hope this helps.
Well I figured it out, the request I wrote was perfectly fine. The thing that was causing the the problem was response I was getting from server.
It was JSON stringified before return.

jquery jsonp not working

$(document).ready(function() {
$.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?', function(data) {
console.log("success");
});
});
Why this code is not working? Its not giving error also in browser. But a project file is being downloaded as script in Chrome as shown by Inspect Element tool. How can I get data from the file?
It looks like Atlassian use jsonp-callback instead of callback as the parameter in a query string for JSONP callbacks.
See here.
I would suggest you configure your JSONP-call with the jQuery.ajax API like:
$(function() {
$.ajax({
type: "GET",
url: "https://jira.atlassian.com/rest/api/latest/project",
dataType: "jsonp",
jsonp: "jsonp-callback",
data: { /* additional parameters go here */ }
}).done(function(data) {
console.log("success");
});
});
The option jsonp renames the JSONP-callback parameter as #mccannf suggested from the API.
Also, for future reference, you might consider using the jqXHR object to add error-handling functionality, so you can tell if the JSON request is failing. See jQuery's reference (http://api.jquery.com/jQuery.getJSON/)
$(document).ready(function() {
var jq = $.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?',
function(data) {
console.log("success");
})
.error(function() { console.log("error occurred"); });
});

Real-time load result (ajax)

I dont know how write this script. I need load results with some URL (eg: localhost/index.php?action=get&type=29) and this result to give a variable for further processing. I need create this on Jquery. Thanks.
There are features in jQuery that can be used, you have either a quick load using the simple .load() function that will parse the HTML into an element. Usage:
$('#element').load('http://www.urlgoeshere.com/');
With processing events with AJAX with further writing options, you have many options to choose from:
http://api.jquery.com/jQuery.ajax/
These options below are using the .ajax() function but makes the writing easier:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
EDIT: With your "refresh", you can use the setTimeout function to repeat the ajax call:
setTimeout(function()
{
$.ajax({
type: "POST",
url: "some.php",
data: "action=get&type=29",
success: function(arg){
// do something
}
});
}, 1000); // This will "refresh" every 1 second
$.ajax({
type: "POST",
url: "some.php",
data: "action=get&type=29",
success: function(arg){
// do something
}
});
you can use
$.ajax({
url: "localhost/index.php",
data: "action=get&type=29",
success: function(data, status, xhr){
// data is the response from the server, status is the http status code,
// xhr is the actual xhr
},
error: function(){
},
...
});
to get the results.
Be sure to define the success and error callbacks to process the data when it is returned.
Look here http://api.jquery.com/jQuery.ajax/ to get started.

Categories