jQuery vs. JavaScript ajax 'POST' functions - javascript

This jQuery code is working:
$.ajax({
type: "POST",
url: "file.php",
data: { json: json },
complete: function (data) {
var result = data.responseText;
console.log(result); // logs 'echo' from PHP file
}
});
This JavaScript code is still not working:
var xhr = new XMLHttpRequest();
xhr.open("POST", "file.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log(result); // supposed to log 'echo' from PHP file
}
}
xhr.send(JSON.stringify(json));
Aren't these two approaches equivalent, or am I missing something?
Suppose 'file.php' looks something like this:
if(isset($_POST['json'])){
$obj = json_decode($_POST['json']);
//some php operation
// echo $obj keys and values
}

data : { json: json }
gets serialized to '{ "json": {data} }'
JSON.stringify(json)
gets serialized to '{data}' and there is no "json" key
add your javascript object to a parent wrapper object with a "json" key
JSON.stringify({ json: json });

Related

how to call a service using ajax javascript?

I'm learning programing, could you explain me how to call a service using ajax javascript?
Service information:
Service type: REST
Basic authentication
Estructure: Application/JSON
Url: https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar
User: Admi
Password: admi
Parameter JSON example: {"identificacion":["98122811999"]}
I've tested this service in postman
Service answer:
{
"respuesta": [
{
"estado": "Correcto.",
"identificacion": "98122811999",
"imagen": "return string Base 64 format"
}
]
}
Using JQuery :
$.ajax({
type: 'POST',
url: 'https://osb.urosario.edu.co/uxxi-URO/WsFotografias/proxy/AdministradorFotografiasJsonPS/fotos/consultar',
dataType: 'json',
data:{"identificacion":["98122811999"]}
contentType: "application/json"
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', make_base_auth("admi", "admi"));
},
success: function (data,status) {
//do what you want with the data after success
//in this example the response will be promoted in the browser console
console.log(data);
});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return 'Basic ' + hash;
}
You can call your above RestEndpoint using below:
xmlhttp.open("POST", "/EndpointURI", true);
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
//Use parse() method to convert JSON string to JSON object
var responseJsonObj = JSON.parse(this.responseText);
//use response
}
};
var jsonData = {"name" : "yourData"};
xmlhttp.send( JSON.stringify( jsonData ) );
For Authentication use this:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://EndPointURI", true);
xhr.withCredentials = true;
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('userName:password'));
xhr.onload = function () {
console.log(xhr.responseText);
};
xhr.send();
For authentication part, use JQuery then it will easy for the implementation and as well for understanding. as now aday no body use basic xmlhttp for calling api in javascript, last time i used was a 2003 developed application.

Send AJAX request to Django view with vanilla JS

I'm trying to send a GET AJAX request to a Django view using vanilla JS. is_ajax() passes but I could not retrieve the request object properly.
Here is my JS code. With/out JSON.stringify(data) doesn't work.
document.querySelector('#testForm').onsubmit = () => {
let data = {category : 'music'};
const request = new XMLHttpRequest();
request.open('GET', 'test/', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onload = () => {
const data = JSON.parse(request.responseText);
console.log(data);
}
request.send(data);
return false;
});
And here is my Django view:
def test(request):
if request.is_ajax():
print('Yes!')
data = {'category': request.GET.get('category', None)}
return JsonResponse(data)
else:
raise Http404
It prints Yes! to the terminal but I get back a {category: null} in the console.
This JQuery code works and I get the expected {category: "music"} response:
$.ajax({
url: 'cart/',
type: 'GET',
data: data,
dataType: 'json',
success: function (data) {
console.log(data);
}
});
I'm wondering what I'm missing in the vanilla JS code or in my Django view.
GET requests can't have a body, so the data parameter to request.send is ignored. You should make it part of the URL itself:
request.open('GET', 'test/?category=music', true);

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

How to get "Data" field from xhr.responseText?

I have XMLHttpRequest() function given below
var searchFriendRequests = function (userid) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:6344/api/Registeration/searchFriendrequests?userid=' + userid, false);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = xhr.responseText;
}
}
};
xhr.send(null);
}
where xhr.responseText returns value as
{
"$id": "1",
"ContentEncoding": null,
"ContentType": null,
"Data": [
{
"$id": "2",
"email": "anu#gmail.com"
},
{
"$id": "3",
"email": "anu#gmail.com"
}
],
"JsonRequestBehavior": 1,
"MaxJsonLength": null,
"RecursionLimit": null
}
How can I get the Data field from the responseText?
use JSON.parse(), like:
var data=xhr.responseText;
var jsonResponse = JSON.parse(data);
console.log(jsonResponse["Data"]);
You first need to parse responseText in JSON, for this you should use JSON.parse(). Then you can access it using key.
var json = JSON.parse(xhr.responseText);
var yourData = json.Data; // or json["Data"]
To simply get the email, or any other field, from the Data object, use the following:
data.Data[0].email
WORKING EXAMPLE
For sometime now you can use:
xhr.responseJSON
without any parsing needed. hope it helps
should parse the response to json object first,then get the data field from the response
var responseText = JSON.parse(xhr.responseText),
data = responseText.Data;
When you make your ajax request you can provide dataType option:
dataType: 'json'
For such request when you receive response:
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
you can access your data like:
var data = xhr.responseJSON
Full example:
$ajax.({
dataType: 'json',
success: function( xhr ) {
var yourData = xhr.responseJSON;
console.log( yourData );
},
});
var jsonResponse = JSON.parse(xhr.responseText);
console.log(jsonResponse);

What's wrong with this jQuery Ajax/PHP setup?

I'm building a search app which uses Ajax to retrieve results, but I'm having a bit of trouble in how exactly to implement this.
I have the following code in Javascript:
if (typeof tmpVariable == "object"){
// tmpVariable is based on the query, it's an associative array
// ie: tmpVariable["apple"] = "something" or tmpVariable["orange"] = "something else"
var sendVariables = {};
sendVariables = JSON.stringify(tmpVariable);
fetchData(sendVariables);
}
function fetchData(arg) {
$.ajaxSetup ({
cache: false
});
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
});
}
And within script.php:
<?php
$data = json_decode(stripslashes($_GET['data']));
foreach($data as $d){
echo $d;
}
?>
What is it that I'm doing wrong?
Thanks.
Your PHP script is expecting a GET var called 'data'. With your code you're not sending that.
Try this:
if (typeof tmpVariable == "object"){
var data = {data : JSON.stringify(tmpVariable)}; // Added 'data' as object key
fetchData(data);
}
function fetchData(arg) {
$.ajax ({
type: "GET",
url: "script.php",
data: arg,
success: function(response){
alert(response);
$("body").html(response); // Write the response into the HTML body tag
}
});
}

Categories

Resources