I am not expert in jQuery, consider me fresher. Here is my code which one not responsible for jQuery JSON data submission by Request Body.
<!doctype html>
<html lang="en">
<head>
<title>jQuery Data submitted by JSON Body Request</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$.ajax({
url : "/",
type: "POST",
data: [
{id: 1, name: "Shahed"},
{id: 2, name: "Hossain"}
],
contentType: "application/json; charset=utf-8",
dataType : "json",
success : function(){
console.log("Pure jQuery Pure JS object");
}
});
</script>
</head>
<body>
<p>
Example of submission JS Object by JSON Body Request<br/>
Its could submitted mass amount of data by Message body<br/>
It's secured and faster than any data submission .
</p>
</body>
</html>
Post Source appeared:
Shahed=undefined&Hossain=undefined
But desired Post Source is:
[{"id":1,"name":"Shahed"},{"id":2,"name":"Hossain"}]
How do I get the desired Post Source for each Request Body?
Here is the right code for your desired out put.
$.ajax({
url : "/",
type: "POST",
data: JSON.stringify([
{id: 1, name: "Shahed"},
{id: 2, name: "Hossain"}
]),
contentType: "application/json; charset=utf-8",
dataType : "json",
success : function(){
console.log("Pure jQuery Pure JS object");
}
});
Your must convert JS Object to String and JSON.stringify(JSObject) is the method responsible for that.
Related
I'm trying to send an object in JSon format to my Java backend by AJAX, but I was unsuccessful.
I wonder if the syntax is properly correct.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scripts/jquery.min.js.download"></script>
<script src="scripts/jquery.imagemapster.js.download"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var myJSon = {"name":"Jo","age":30,"city":"Ny"};
$.ajax({
type: "POST",
url: 'http://localhost:8080/Servidor/server',
//contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify(myJSon),
success: function (data){
alert('Sucess');
},
error: function () {
alert('Error');
}
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
When the line contentType: "application/json;charset=utf-8" is not commented out, I get the following error in the backend: INFO: Could not find grammar element for class java.lang.String
Is the syntax correct? Can the error be from the backend itself?
P.S.: Sorry for my bad english
Your code is good, you just misspelled "success" on the AJAX call (you need 2 letter c's instead of 1). So replace sucess: function(data){...} with success: function(data){...} https://jsfiddle.net/stephentillman/aow5pah2/
Im new at JS and JSON. So I need to send a JSON massive to Google API using POST, and get the answer and show it via alert. I wrote this page, but this code has no result.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Redericting</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
type: "POST",
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=KEY',
data: '{wifiAccessPoints:["macAddress", "signalStrength"], cellTowers:["cellId", "locationAreaCode", "mobileCountryCode", "mobileNetworkCode"]}',
dataType: "json",
success: function(response) {
alert(response);
}
});
</script>
</body>
</html>
When using AJAX you require to set the content-type of the information you are sending. By default this value is set to application/x-www-form-urlencoded; charset=UTF-8.
$.ajax({
type: "POST",
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=KEY',
data: JSON.stringify({wifiAccessPoints:["macAddress", "signalStrength"], cellTowers:["cellId", "locationAreaCode", "mobileCountryCode", "mobileNetworkCode"]}),
contentType: "json",
success: function(response) {
alert(response);
}
});
Are you sending the response in JSON format? datatype property refers to the type that you're returning from the server. And if that doesn't match, control will go the error callback. Remove or update the datatype property to match the response type. Make the below changes and try
$.ajax({
type: "POST",
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=KEY',
data: '{wifiAccessPoints:["macAddress", "signalStrength"], cellTowers:["cellId", "locationAreaCode", "mobileCountryCode", "mobileNetworkCode"]}',
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error");
}
});
I want to upload file to server using AJAX and PHP. Here is what I've tried so far but it is not working for me.
The server throws this error:-
Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 3
Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 7
Notice: Undefined index: file in C:\xampp\htdocs\authentication\test.php on line 7
Client side code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
<script type="text/javascript">
function valid(){
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'test.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
$('#result').html(data); // display response from the PHP script, if any
}
});
}
</script>
</head>
<body>
<div id='result'></div>
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick='valid()'>Upload</button>
</body>
</html>
And here is client side code, test.php:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name'])){
echo "file uploaded";
}
}
?>
These two lines are wrong:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-2.1.4.js"></script>
Use only one version of jQuery: 1.5.1 or 2.1.4 (I suggest the last one)!
As the error message is telling you, there is no 'file' member to the $_FILES associative array in PHP. I think you want 'name'.
Use jQuery File Upload Plugin, It has many cool feature which will save more time and avoid re-inventing the wheel again.
Library:
https://blueimp.github.io/jQuery-File-Upload/
PHP Setup Guide:
https://github.com/blueimp/jQuery-File-Upload/wiki/Setup
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'server/php/'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 999000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
This works for me always:
function valid(){
var formData = new FormData();
formData.append('file', $("#sortpicture")[0].files[0]);
$.ajax({
url: "test.php",
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: formData,
success: function(data){
// Process response here. May be preview image?
},
error: function(r){
// Handle errors
},
});
}
I am trying to send a json object through ajax post in javascript as follows:
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {json: cond},
dataType: 'json',
success: function(response) {
alert(response["json"]);
}
});
cond represents the json object which is something like this(converted with JSON.stringify):
[{"field":"name","condition":"<","value":"John"}]
on testPost.php file I have the following:
<?php
$return=$_POST["json"];
$decoded_json=json_decode($return);
$reply["json"]=$decoded_json;
print_r ( json_encode($reply));
?>
My problem is that Json_decode is returning null.
I have checked the encoding(UTF-8), and also checked that the json witch i send to the php file has no slashes or anything.
Can anyone help me?
header('Content-Type: application/json');
You need to add this line in PHP before echo.
Then
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {json: cond},
dataType: 'json',
success: function(response) {
alert(response.field);
alert(response.condition);
alert(response.value);
}
});
Your Ajax data converted to
[{json : {"field":"name","condition":"<","value":"John"}}]
It's not valid because of json : side.
Convert your Jquery to
$.ajax({
type: 'POST',
url: 'testPost.php',
data: {"json": cond},
dataType: 'json',
success: function(response) {
alert(response["json"]);
}
});
And There is works example here,
<?php
if(count($_POST) > 0){
print_r($_POST);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<script>
$(function(){
var cond = [{"field":"name","condition":"<","value":"John"}];
$.ajax({
type: 'POST',
url: 'a.php',
data: {"json" : cond},
dataType: 'text',
complete: function(response) {
$("body").html(response.responseText);
}
});
})
</script>
</head>
<body>
</body>
</html>
try using stripslashes() then json_decode()
$decoded_json = json_decode(stripslashes($return));
I am trying to make an AJAX Request through JQuery
The below is my code .
But when i debugged through Mozilla Firebug i observed that ,there is no Request hitting to the Server .
Could anybody please tell me where i am doing wrong .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JQuery Example</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'ajax/balances',
processData: false,
timeout: 10000,
type: "POST",
contentType: "application/xml",
dataType: "json",
data: '<MyReq user="' + User + '" katha="' + ivalitiKatha + '" />',
success: function(data) {
},
error : function() {
alert("Sorry, The requested property could not be found.");
}
});
});
</script>
</body>
</html>
This is my web.xml on server side
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/ajax/*</url-pattern>
</servlet-mapping>
Maybe adding <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> to the head instead of the body helps!
First of all I would recommend moving the CDN JQuery into the head section of the website.
Secondly I have tested the code above and the issue looks to lie with the (data) you are posting in the JSON / AJAX request.
If you remove it or amend to JSON the request returns a result e.g.
$.ajax({
url: 'test',
processData: false,
timeout: 10000,
type: "POST",
contentType: "application/json",
dataType: "json",
data: '{"foo": "bar"}',
success: function(data) {
alert('Success');
},
error : function() {
alert("Sorry, The requested property could not be found.");
}
});
You will need to format the data as a JSON request
data: '{"foo": "bar"}',
Hope this helps