Sending multiple values with JavaScript - javascript

I have two values I want to send but I couldn't figure it out.
Im currently sending 1 value like that:
JS:
req.open('POST', '../Ajax/doc.php?id=' + id, true);
req.send();
PHP:
$id = $_REQUEST["id"];
And now I have another value id2 which I want to send in the same way..
Thanks

Since you are using post, the SEND function accepts the query string as a parameter. Then just replace my var2 with what it is you are trying to send and use POST in PHP to make it easier for you to know the array to use for POST submissions.
const data = {
id: 123,
var2: 987,
foo: 'bar',
}
req.open('POST', '../Ajax/doc.php', true)
req.send(
Object.keys(data)
.map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key]))
.join('&')
)
PHP
$id = $_POST["id"];
$var2 = $_POST["var2"];

You can send multiple value using FormData.
function send() {
var uri = "your_url";
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", uri, true);
fd.append('title', 'Hello World');
fd.append('content', 'Just Hello World');
// Initiate a multipart/form-data upload
xhr.send(fd);
}
window.onload = function () {
btn_send = document.querySelector('#btn-click');
btn_send.addEventListener('click', function () {
send();
})
}

Related

Output PHP already encode to json, and send to javascript to be json, not working

I'm do output with json_encode to sending to javascript, with this code.
<?php
include "Connection.php";
$syntax_query = "select * from product";
$thisExecuter = mysqli_query($conn, $syntax_query);
$result = array();
while($row = mysqli_fetch_assoc($thisExecuter)){
array_push(
$result,
array(
"id" => $row["product_id"],
"name" => $row["product_name"]
)
);
}
echo json_encode($result);
?>
so output show like this,
[{"id":"121353568","name":"Baju Casual - Black"},{"id":"556903232","name":"Tas LV - Red"},{"id":"795953280","name":"Sword - Wood"},{"id":"834032960","name":"Scooter - Iron Plate"}]
and code javascript like this
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var obj = this.responseText;
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
so obj.id its not working, output show undifined.
I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.
If Jquery is imported then ignore the steps
Here are steps,
Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
Import the js file in the HTML file in script tag as shown '
Now, this is the ajax example to call the PHP file and to get a response
function showHint() {
//since you have used GET method I have used here GET but You can use POST also here
$.ajax({
url: 'Download.php',
type: 'get',
//if any value you want to pass then uncomment below line
// data: {'name_to_pass':'value'},
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
success: function(res)
{
// open DevTool console to see results
console.log(JSON.parse(res));
}
});
}
Hope this will help you out, thank you
Maybe you need a JSON.parse in the response, something like JSON.parse(this.responseText).
And also I can see the result is an Array so you will need to iterate obj
obj.forEach(item => {
document.getElement("txtHint").innerHTML = item.id;
});
you should define the response type as json
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
**var obj = this.responseText;**
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
When you get the responseText it's text, not an object.
var obj = this.responseText; should be let obj = JSON.parse(this.responseText);
Then you can access obj.id as a property.

How to remove unwanted characters from JSON request

I am new to javascript.
I am facing this issue where I get [{"_id":1}] as my results.
Does anyone know how can I get 1 as my output?
This is my code, I am calling it from a database.
function getaccountid() {
var accID = new XMLHttpRequest();
accID.open('GET', "http://127.0.0.1:8080/account" + "/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send(JSON.parse);
accID.onload = function () {
sessionStorage.setItem("accountId", accID.response)
}
}
That response type is a JSON formatted string, it's a standard response type, not an issue. To read the value you need to parse the result from a JSON string to an array of objects, then access it.
Also note that you need to remove the JSON.parse reference within the send() call and define the load event handler before you send the request. Try this:
function getaccountid() {
var accID = new XMLHttpRequest();
accID.addEventListener('load', function() {
let responseObject = JSON.parse(this.responseText);
sessionStorage.setItem("accountId", responseObject[0]['_id']);
console.log(responseObject[0]['_id']); // = 1
});
accID.open('GET', "http://127.0.0.1:8080/account/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send();
}

Access response JSON array from XMLHttpRequest

I have a problem. I'm sending file via AJAX (XMLHttpRequest). Anyways. PHP function is returning a response array encoded to JSON. I can catch array in JavaScript but i can't access to specified key in array.
Here is the console log of this array:
{"data":"cos","data1":"cos1"}
I have my JavaScript file:
$('input[name=zdjecie]').on("change",function() {
var inputfile = document.querySelector('#file');
var file = inputfile.files[0];
$('button[type=submit]').addClass('disabled');
var formData = new FormData();
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(e){
var pro = Math.round(e.loaded/e.total * 100);
if(pro == 100) {
$('#upload_progress').css({'width':pro+'%', background:'#00A65A'});
$('button[type=submit]').removeClass('disabled');
}
else {
$('#upload_progress').css({'width':pro+'%', background:'#3C8DBC'});
}
}, false);
formData.append('file', file);
request.open('post', '/admin/ajax/upload-admin-photo');
request.send(formData);
request.onloadend = function() {
var result = request.response;
console.log(result.data);
};
});
Now PHP function that is executing after POST request:
/**
* #Route("/admin/ajax/upload-admin-photo")
*/
public function ajaxUploadAdminPhotoAction(Request $request)
{
$data = $_FILES;
$response = array("data" => 'cos', 'data1' => 'cos1');
return new Response(json_encode($response));
}
Console log of variable result: {"data":"cos","data1":"cos1"}
Console log of variable result.data: undefined
I really need some help. I was trying everything! :(
You need to parse (=decode) the string '{"data":"cos","data1":"cos1"}' to a json first:
var result = JSON.parse(request.response);
// now you can access it's params:
console.log(result.data);
see the manual for more information.

XMLHttpRequest Posting empty body

When I try to post some data to my backend API service I use the XMLHttpRequest object, but when I try to send the data with ajax.send it sent nothing to the server
Code snipper:
ajax = new XMLHttpRequest();
ajax.open("POST", "https://someapi.com",true);
ajax.send({
name: "Name",
phone: "123468375698563897569575863"
});
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};
You need to:
Say you are sending JSON
Convert your JavaScript data structure into JSON
Such:
var data = {
name: "Name",
phone: "123468375698563897569575863"
};
var json = JSON.stringify(data);
var ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(json);
You cannot directly send a JS object over the wire.
You need to convert it to a string first, just like you need to parse it when you're getting it back.
ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.send(
JSON.stringify({
name: "Name",
phone: "123468375698563897569575863"
})
);
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};
The simplest PHP test code on the server side would be:
<?php
echo file_get_contents('php://input');
?>
And here is a slightly more advanced example that will decode it, add a new field and send it back:
<?php
$json = file_get_contents('php://input');
$object = json_decode($json);
$object->id = 123;
echo json_encode($object);
?>

cannot pass a javascript object to php via ajax

I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.
function createArray()
{
var advancedFormVars = new Array();
advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;
advancedFormVars['checkbox2'] =document.getElementById('offerName').value;
AjaxCall(advancedFormVars);
}
function AjaxCall(advancedFormVars){
var json = new Array();
json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty
$.ajax({
url : 'AL_loadForm.php',
type : 'POST',
data : {
json : json
},
dataType:'json',
success : function(data) {
alert(data);
}
...
You are trying to use your array as a hash, so the values are not being set..
Instead of setting
var advancedFormVars = new Array();
Try setting
var advancedFormVars = {};
Example
JS:
var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';
var json = JSON.stringify(advancedFormVars);
console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}
PHP
<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
object(stdClass)#1 (2) {
["checkbox1"]=>
string(6) "valueA"
["checkbox2"]=>
string(6) "valueB"
}
*/
?>
If all you have are two smaller arguments, I'd keep it simple and make an http get request. Encode your arguments if neccessary.
var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}

Categories