How to post Json by .Ajax? - javascript

i want to post two items into server by using ajax in java-script; based on server-side document the post url is like this
http://example.com/h/{first-item}/{second-item}
this is my java-script code:
$('#add-order').on('click', function() {
var name = $('#name');
var drink = $('#drink');
var order = ?? // my question is this part what should i add
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: 'application/json',
success: function(data) {
console.log("Data added!", data);
}
});
});
and this is my HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="input-group">
<h4>Add a Coffee Order</h4>
<p>name: <input type="text" id="name"></p>
<p>name_space: <input type="text" id="drink"></p>
<button id="add-order">Add!</button>
</div>
<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
</html>
i am a new in ajax, thanks for your help.

You have to set the contentType to application/json in your Ajax request.
i.e as following:
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: "application/json",
dataType: "json",
success: function(data) {
console.log("Data added!", data);
}
});
});
here is an example for creating and encoding a json object.
var myObj = {
"name": $('#name').val(),
"drink": $('#drink').val()
};
var order = JSON.stringify(myObj);

Hard to really understand the post here, but it seems to me you simply forgot to mark the ajax requests contentType as json. See example below.
$.ajax({
type: 'POST',
url: 'http://example.com/h/',
data: order,
contentType: 'application/json'
dataType: 'json',
success: function(data) {
console.log("Data added!", data);
}
});

Related

I need to access to object data ( id - title - body )

I need to access data.data[0].title
while printing
data.data[0]
I get all object data
but while printing
data.data[0].title
i can't access any data
// this is my ajax script
<script>
$.ajax({
url: 'http://127.0.0.1:8000/api/posts',
dataType: 'json',
type: 'GET',
success: function(data) {
$('#test').html( JSON.stringify( data.data[0].title ) );
}
})
</script>
<p id="test" ></p>
You probably don't need JSON.stringify(). #illusion is right! I guess your response Object structure is similar to:
{
"data": [{
"title": "This is the title"
}]
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'https://extendsclass.com/api/json-storage/bin/ebbfccb', //replace this with your api URI
dataType: 'json',
type: 'GET',
success: function(data) {
$('#test').html(data.data[0].title);
}
})
</script>
<p id="test" ></p>

Return resulting json from github API on html file

I have this html code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div id="result" style="color:red"></div>
</div>
</body>
<script>
$(document).ready(function(){
$.ajax({
url: "https://api.github.com/users/Microsoft",
type: 'GET',
dataType: 'json',
success: function(res) {
$('#result').html(res)
}
});
})
</script>
Whenever I try to see the result on my browser it just shows an empty blank page.
I just need to return the API result and show it on html.
Any ideas?
The AJAX callback makes res an object. When you using .html() the argument must be a string. If you want to see the object represented on the page, use JSON.stringify():
$.ajax({
url: "https://api.github.com/users/Microsoft",
type: 'GET',
dataType: 'json',
success: function(res) {
$('#result').html(JSON.stringify(res))
}
});

Send a Json object to server with javascript function

I try to send a json object to a distant server, but I didnt receive success message. please what's wrong with this code:
function sendSMS(){
var input = '{"header":"****","****":*****,"****":"*****"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.stringify(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
// html code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript" src="sendSMS.js"></script>
</head>
<body>
<button onclick="sendSMS()">sendSMS</button>
</body>
</html>
Any help please.
You have to simple change your ajax call to this:
function sendSMS(){
var input = '{"header":"Ooredoo","msisdn":21620117297,"SMS":"Hello"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.parse(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
The main changes are JSON.stringify to JSON.parse this will help you to parse the JSON data into a JSON object, and the second change is the actual payload in which you missed a " at the end, just after Hello.
If you have any other question, just ask :)
Also I would recommend not to send the username and password as querystring parameter, use a POST request with a proper payload and last, if you can go through ssl

jquery ajax isn't working

I am trying to get user information by using twitter api. The jquery code is below :
<script type="text/javascript">
function GetUser() {
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?user_id=id&include_entities=true&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:8000,
success: function (json) {
alert("Successfull");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
}
});
}
</script>
xhr.responseText:undefined
thrownError:[object Error]
And html code :
<input type="submit" value="Submit" onclick="GetUser();" />
First your URL is not correct. Instead of
user_id=id
in your URL you have to use a actual value for id (id is just placeholder in your case). For example:
user_id=82193320
which would give you the data for my twitter user (uwe_guenther) back.
You can easily lookup twitter ids here:
http://mytwitterid.com/
If you just want to lookup user data by screen name you could use:
screen_name=uwe_guenther
instead.
The Twitter API description can you find here:
https://dev.twitter.com/docs/api/1/get/users/show
I have attached a working example for looking up screen_name by user_id and user_id by screen_name here:
The jsFiddle with the following example can be found here: http://jsfiddle.net/uwe_guenther/EvJBu/
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input id='userIdTextField' type='text' placeholder='user_id'/>
<input id='userIdSubmitButton' type="submit" value="Submit"/>
<div id='screenNameResultView'></div>
<br>
<input id='screenNameTextField' type='text' placeholder='screen_name'/>
<input id='screenNameSubmitButton' type="submit" value="Submit"/>
<div id='userIdResultView'></div>
<br>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src='main.js'></script>
</body>
</html>
main.js
$(document).ready(function (){
$('#userIdSubmitButton').click(function (){
var userId = $('#userIdTextField').val();
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?user_id=" + userId + "&include_entities=true&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:1000,
success: function (json) {
alert("Successfull: screen_name=" + json.screen_name);
$('#screenNameResultView').text("screen_name=" + json.screen_name);
console.log(json);
},
error: function () {
alert("No Result");
}
});
});
$('#screenNameSubmitButton').click(function (){
var screenName = $('#screenNameTextField').val();
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?screen_name=" + screenName + "&include_entities=true&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:1000,
success: function (json) {
alert("Successfull: user_id=" + json.id);
$('#userIdResultView').text("user_id=" + json.id);
console.log(json);
},
error: function () {
alert("No Result");
}
});
});
});
Your Url is wrong
<script type="text/javascript">
function GetUser() {
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?user_id=id&include_entities=true&callback=?",//this is wrong
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:8000,
success: function (json) {
alert("Successfull");
},
error: function () {
alert("cant search");
}
});
}
</script>
Here is a workin example http://jsfiddle.net/kMgES/
$.ajax({
url: 'http://api.twitter.com/1/users/lookup.json?screen_name=noradio&callback=?',
type: 'GET',
dataType: 'json',
timeout: 8000,
success: function (data) {
alert(data[0].name);
},
error: function () {
alert("cant search");
}
});
In this example the search is done by screen name. Take a look at https://dev.twitter.com/docs/api/1/get/users/show for all possible options.
Consider using this for error handdling
error: function(XMLHttpRequest, textStatus, errorThrown){
// error handling
}

FormData Object not submitting via jQuery AJAX call

I'm using this script to get all values from a form, in order to prepare it for an ajax request:
function saveDataAjax(){
var fd = new FormData();
var inputs = document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++) {
fd.append(inputs[i].name, inputs[i].value);
}
$.ajax({
url: '/edit.php',
data: fd,
type: 'POST',
dataType: 'html',
success: function(data){
alert(data);
}
});
}
However I'm getting a Type error from jQuery, and if I alert fd['inputname'] I get undefined, so I guess I must be doing something wrong somewhere...
Firefox debuggers tells me this: NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object # http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js:2
Add the following to the AJAX call:
processData: false,
contentType: false,
So it looks like:
$.ajax({
url: '/edit.php',
data: fd,
type: 'POST',
processData: false, //Add this
contentType: false, //Add this
dataType: 'html',
success: function(data){
alert(data);
}
});
This is probably not the reason, but just wanted to point it out: i is global here. The idea in JS is towards global abatement. Should probably be var i=...
this page help you ...:)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous">
</script>
</head>
<body>
<form method="post" id="fileinfo" enctype="multipart/form-data">
file <input type="file" name="slug"><br>
<input type="button" id="uploadBTN" value="Stash the file!"></input>
</form>
<script type="text/javascript">
$(document).ready(function()
{
$('#uploadBTN').on('click', function()
{
var form = $('form').get(0);
console.log(form);
var fd = new FormData(form);
fd.append('user_id',4);
fd.append('user_media_category_id',1);
//console.log(fd);
fd.append("user_", "This is some extra data");
$.ajax({
url: 'http://localhost/yii2/azstudio/project/api/web/v1/user-media/new',
type: 'POST',
data: fd,
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
</body>
</html>

Categories

Resources