i need to send array parameter or value using XMLHttpRequest
Something like this
$(document).on('click','.save_edit_class',function(){
var crit_name_text = $('#crit_name_text').val();
var crit_desc = $('#crit_desc_text').val();
var sub_crit_arr = [];
$('.sub_crit_text').each(function(k , v){
sub_crit_arr[k] = $(v).val();
});
var http = new XMLHttpRequest();
var url = "xml_remove_criteria.php";
var params = "crit_name_text="+crit_name_text+"&crit_desc="+crit_desc+"&sub_crit_arr[]="+sub_crit_arr+"";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function(){//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200){
alert(http.responseText);
}
}
http.send(null);
});
How can i send the sub_crit_arr(the array) variable to my xml page as array? I'm trying to send using that, but i got an error invalid argument supplied foreach.
This is my xml page..
<?php
session_start();
include("../global.php");
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
if(isset($_GET['crit_name_text'])){
$criteria_name = $_GET['crit_name_text'];
echo $criteria_name;//testing
if(isset($_GET['crit_desc'])){
$crit_desc = $_GET['crit_desc'];
echo $crit_desc;//testing
}
if(isset($_GET['sub_crit_arr'])){
$sub_crit_arr = $_GET['sub_crit_arr'];
$sub_crit_arrs = array();
$count = 0;
foreach ($sub_crit_arr as $value) {
$sub_crit_arr[$count] = $value;
echo $sub_crit_arr[$count]." - value<br/>";//testing
$count++;
}
}
}
echo '</response>';
?>
Related
since I wrote this code and it turned out that it is not entering the if statement ,My target was to bring the array from php(db) and put it in array in js,what to do?Here is the code ,is the problem that it is located in an extension js file ?Moreover php file getusercatpref.php is returning ["violen","ios","programming","nodjs"].
var arr = new Array();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
arr = myArr;
}
};
xmlhttp.open("GET", "getusercatpref.php", true);
xmlhttp.send();
PHP Code
<?php
$name="root";
$pas="";
$dbname="jobpursuit";
$con=mysqli_connect("localhost", $name, $pas,$dbname);
$arrayCategories = array();
$sql="Select * FROM preferences where username='12' ";
$result=mysqli_query($con,$sql);
$index=0;
while($row = mysqli_fetch_assoc($result)){
$arrayCategories[$index] = $row['categoryname'];
$index=$index+1;
}
echo json_encode($arrayCategories);
?>
I have a js function that calls in an xml request to fetch data from a separate php file. I can get a returned data through echoing it from the separate php file.
Here's my current code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
//On Data Receive
countryHeader.innerHTML = this.responseText;
}
};
xhttp.open("GET", "country.php?c=" + countryName, true);
xhttp.send();
And on my php:
include("conn.php");
$c = htmlentities($_GET["c"]);
$sec_country = mysqli_real_escape_string($con, $c);
//Searches the db
$sql = "SELECT * FROM countries WHERE country_code = '$sec_country' LIMIT 1";
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
if($count == 1)
{
//Get Data
$row = mysqli_fetch_assoc($result);
$countryName = $row['country_name'];
$countryPrice = $row['country_price'];
echo $countryName." is worth $".$countryPrice;
}
else
{
//Invalid Code/No Data
echo "No Country Found";
}
If I send in a country code for example like rus, it would return Russia is worth $1B mainly from the echo $countryName." is worth $".$countryPrice;
But what if I want to separately send $countryName and $countryPrice?
For example responseText.a and responseText.b
You can send JSON response from PHP. Here is a reference -> https://www.w3schools.com/js/js_json_php.asp
I've had a fit for the past few days trying to figure out how to communicate across domains with ajax requests.
I have this file...
<?php
header('Access-Control-Allow-Origin: *');
?>
<script>
function send(user){
var hr = new XMLHttpRequest();
var url = "http://forumchest.com/kb_exchange.php";
var data = "user="+user;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onload = function(){
if(hr.readyState == 4 && hr.status == 200){
var text = hr.responseText;
alert(text);
} else {
alert(hr.readyState + " " + hr.status);
}
}
hr.send(data);
}
</script>
<?php
include_once("conn.php");
$fetch_sites = mysqli_query($conn, "SELECT * FROM sites");
while($row = mysqli_fetch_array($fetch_sites)){
$site_id = $row['id'];
$site_address = $row['address'];
$fetch_subs = mysqli_query($conn, "SELECT * FROM subscriptions WHERE site='$site_id'");
while($row1 = mysqli_fetch_array($fetch_subs)){
$sub_user = $row1['user'];
$sub_username = $row1['username'];
echo "<script>send('$sub_username');</script>";
}
}
mysqli_close($conn);
?>
It is attempting to send an ajax request to the following file hosted on a different server with a different domain name.
<?php
header("Content-Control-Allow-Origin: *");
?>
<script>
function respond(user, posts){
var data = "user="+user+"&posts="+posts;
var hr = new XMLHttpRequest();
hr.open("POST", "http://xenforotest.esy.es/responder.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(data);
}
</script>
<?php
$conn = mysqli_connect("host", "user", "password", "db");
if(!$conn){
echo "this1";
} else {
echo "this2";
}
$user = $_POST['user'];
$fetch_user = "SELECT message_count FROM xf_user WHERE username='$user'";
$query_user = mysqli_query($conn, $fetch_user);
$row = mysqli_fetch_array($query_user);
$message_count = $row['message_count'];
echo "<script>respond('$user', '$message_count');</script>";
mysqli_close($conn);
?>
I am getting two responses from the first file saying "2 200" and "3 200". So I'm getting a readyState of 2 and a status of 200.
Why isn't this working?
It should be
header("Access-Control-Allow-Origin: *");
and not
header("Content-Control-Allow-Origin: *");
Cross domain is not relevant there. Your problem is that you send data as a url string.. POST data should be in formdata object of javascript
I am using AJAX in order to access data from a php file.
I have problem with the format of retrieved data from database, please help.
So, this is my ajax function splice. It retrieves data from find_account.php
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
form_prof.prof_id.value = req.responseText;
form_prof.prof_name.value = req.responseText;
form_prof.prof_username.value = req.responseText;
form_prof.prof_password.value = req.responseText;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
find_account.php
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
echo 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$id = $arr['profs_number'];
$name = $arr['profs_name'];
$username = $arr['profs_username'];
$password = $arr['profs_password'];
}
header("Content-type: text/plain");
echo $id;
echo $name;
echo $username;
echo $password;
?>
and I have 4 input boxes in my HTML from where the req.responseText puts the value
and everytime I search the name in the input field for example:
Search: [ Dorothy Perkins ]
The output goes like [id,name,username,password]:
[20111Dorothy Perkinsdperkins#mail.com123456] [same with 1st field] [same] [same]
Wherein I want it to be like...
[20111] [Dorothy Pekins] [dperkins#mail.com] [123456]
Where [ ] are input fields.
Please help me arrange my format, I am so confused. I am new to this.
You can encode return values in json before sending back.
In PHP
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
$returnValues = 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$returnValues = json_encode($arr);
}
echo $returnValues;
?>
In Javascript
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
req = JSON.parse(reg);
form_prof.prof_id.value = req.id;
form_prof.prof_name.value = req.name;
form_prof.prof_username.value = req.username;
form_prof.prof_password.value = req.password;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
You have to write the data in some format from your PHP code (XML, json, or simply separate the values with a comma), and parse it from your javascript.
For example, in PHP:
echo $id . "," . $name . "," . $username . "," . $password;
And then in the javascript:
values = req.responseText.split(",");
form_prof.prof_id.value = values[0]
form_prof.prof_name.value = values[1];
form_prof.prof_username.value = values[2];
form_prof.prof_password.value = values[3];
Of course you may have to do something more complicated if the values may contain a comma.
You can try this
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query, MYSQLI_STORE_RESULT);
while($arr = $result->fetch_array(MYSQLI_ASSOC)) {
$returnValues = json_encode($arr);
break;
}
echo $returnValues;
Note that column names are used as associative index for $arr
Hope it works.
I have this javascript file that is calling a php file to return a JSON string. Chrome dev tools is throwing the error at line 10 in the javascript code. I know the error relates to a missing bracket but for the life of my and 3 other people who have looked at it the syntax is correct.
var request = new XMLHttpRequest();
var listings = [];
var json;
var url = "getListing.php";
request.open("GET", url, true);
request.send();
request.onreadystatechange = function(e)
{
if(request.readyState == 4){
json = JSON.parse(request.responseText);
for(var x = 0; x < json.length; x++){
var list = new listingInfo();
list.category = json[x].category;
list.date = json[x].dateListed;
list.description = json[x].description;
list.id = json[x].listingID;
list.title = json[x].title;
list.userID = json[x].userID;
listings.push(list);
}
}
console.log(listings);
}
here is the php file
<?php
session_start();
$con = mysql_connect("localhost", "listAdmin", "hermes");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("GregsList", $con)
or die("Unable to select database:" . mysql_error());
$result = mysql_query("SELECT * FROM Listings WHERE userID = '$_SESSION[userID]' ORDER BY dateListed DESC");
#converts to json
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
#If you want to see if correct json is printing use ---> print json_encode($rows);
return json_encode($rows);
?>
request.readyState == 4 is not enough you should add request.status== 200
In your php script replace return json_encode($rows); with print json_encode($rows);