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
Related
I am a newbie to Ajax, I am trying to fetch data from using Ajax Cross domain functionality. Ajax function is being called from test.php which calls the stats.php to request data
Stats.php
<?php
$data = array();
$data[0]=1;
$data[1]=1;
echo json_encode($data);
?>
Test.php
<html>
<head>
<script src="./lib/jquery.min.js"></script>
<script>
var var0=0;
$(document).ready(setInterval(function() {
$.ajax({
cache: false,
type: "GET",
url: "http://10.0.0.2/dashBoard/stats.php",
data: "",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: 'callback',
contentType: "application/json; charset=utf-8",
success: function(data){
console.log(window.var0 = data[0]);
}
});
}, 1000));
$(document).ready(setInterval(function()
{
document.getElementById("p1").innerHTML = window.var0;
},1000));
</script>
</head>
<body>
<p id="p1"></p>
</body>
</html>
test.php is in 10.0.0.1
stats.php is in 10.0.0.2
Ajax is able to call stats.php and i can see the response json but i am not able to use this response data in test.php. I am not able to assign data[0] value which is 1 according to stats.php to window.var0 in test.php which is a global variable. However this works perfectly fine when stats.php is in 10.0.0.1 along with test.php but my requirement is to load data from stats.php in 10.0.0.2.
Please help.
Thanks in advance.
Your problem is you decoupled the function that brings the data from the server and the function that takes that data and changes the DOM based on the server response. Furthermore, you are executing both functions at the same time. This means the function that changes the DOM will fire before the response from server comes back.
The main purpose of using an $ajax is to know when the response has come back, so you could use that data. By placing $.ajax in a function and what you do with the response in another, you break this "wait for data to come" behavior. The whole purpose of the success function is that it executes when the response has returned successfully. In success you already have the data. So use it to change DOM directly:
Use this instead:
$(document).ready(setInterval(function() {
$.ajax({
cache: false,
type: "GET",
url: "http://10.0.0.2/dashBoard/stats.php",
data: "",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: 'callback',
contentType: "application/json; charset=utf-8",
success: function(data){
document.getElementById("p1").innerHTML = data[0];
}
});
}, 1000));
I can't be sure, since I don't know the context, but most likely, you can safely remove the timeout wrapper now. There's no point in delaying the call for data, right?
var var0;
function updateP1(){
document.getElementById("p1").innerHTML = var0;
}
$(document).ready(function() {
$.ajax({
cache: false,
type: "GET",
url: "http://10.0.0.2/dashBoard/stats.php",
data: "",
dataType: "jsonp",
crossDomain: true,
jsonpCallback: 'callback',
contentType: "application/json; charset=utf-8",
success: function (data) {
var0 = data[0];
updateP1();
}
});
});
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);
}
});
I have my first Ajax code and I am a little bit confused how to get all values from certain
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>My first Ajax</title>
</head>
<body>
<script type="text/javascript">
$(submit).click(function getResults() {
return $.ajax({
type: "GET",
url: "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function(msg) {
// success
},
Error: function(x, e) {
// On Error
}
});
});
}
</script>
<input id="submit" name="submit" type="submit" value="Submit">
</input>
</body>
</html>
url. Following papers I have made code down below, but it does nothing to be honest. I would like to know how can I list certain data from this url?
There's many things you need to change (most of them are reference here: http://api.jquery.com/jquery.ajax/):
Use a newer version of jquery:
http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
JS snipper should come after the element, as there's no element defined when JS executed
$(submit) is invalid. It should be $('#submit') as valid selector.
use evt.preventDefault() to prevent default browser behavior
url: you can't make request on another domain unless that url has enabled CORS (cross origin resource sharing), otherwise the request will work only on the same domain as your page. See an option on how to test locally: Jquery .ajax() local testing
async: true -> that's default so you can ommit
dataType -> that's fine if you expect JSON from server
contentType -> that's fine, but you don't send anything to the server, so it's not really needed
error: starts with lower letter
Here' the code updated:
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>My first Ajax</title>
</head>
<body>
<input id="submit" name="submit" type="submit" value="Submit">
<script type="text/javascript">
$("#submit").click(function(evt) {
evt.preventDefault();
$.ajax({
type: "GET",
url: "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: "false",
success: function(msg) {
// success
},
error: function(x, e) {
// On Error
}
});
});
</script>
</body>
</html>
try this:
$('#submit').click(function() {
$.getJSON(url,function(data){
// Do whatever you need
});
});
First of all, your script should be defined after input tag. Also, make sure you have proper headers to access the url or it will give error related to Access-Control-Allow-Headers.
use loop for-in
$(submit).click(function getResults() {
return $.ajax({
type: "GET",
url:"https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (msg) {
for (var i in data){
// data[i].something, etc
}
},
Error: function (x, e) {
// On Error
}
});
});
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>
I am trying to get some data from an API that provides JSON responses. I am brand new to all this. Can someone look at my code and tell me if there is a syntax reason it won't work? I want to hit the button and have an alert pop up containing the data sent back from the request. I think this is the most basic programming thing you can do, and I cannot seem to get it to work.
<head>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'http://openapi.etsy.com/v2/teams/8787?api_key=********&fields=name',
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
alert(data)
}
})
</script>
</head>
<body>
<button onClick="$.ajax()">Run Code</button>
</body>
</html>
I rewrote your code:
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
function doStuff() {
$.ajax({
type: 'GET',
url: 'http://openapi.etsy.com/v2/teams/8787?api_key=********&fields=name',
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
alert(data)
}
});
}
</script>
</head>
<body>
<button onClick="doStuff()">Run Code</button>
</body>
</html>
Add an event handler unobtrusively with jQuery to button using an id.
<head>
</head>
<body>
<button id="button">Run Code</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$('#button').click(function(e){e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://openapi.etsy.com/v2/teams/8787?api_key=********&fields=name',
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
alert(data)
}
})
});
</script>
</body>
</html>
Yes, there are several problems:
You are using jQuery, but you are not loading it.
You try to invoke the call when the page loads.
The onclick event handler tries to invoke $.ajax() call incorrectly (it does not have any parameters).
This is probably all.