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
Related
I'm trying to post form data though a POST AJAX call in JavaScript for a chat system I'm creating, how come the following is not working? I tried to get some documentation but I cannot find it.
<div id="view-chat-form">
<input id="message" type="text" name="chat_message" placeholder="write a message..."/>,
<input type="button" value="send" onclick="sendData()"/>
</div>
and using the followin AJAX code to send the request without loading the page with an hashed string to hide the chat id
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>
and the followin php code to insert the message into the messages table
<?php
include "session.php";
include "connection.php";
$id = "";
$hashed_id = mysqli_real_escape_string($connection, $_POST["q"]);
$sql = "SELECT * FROM chats WHERE SHA2(id, 512) = ?";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 's', $hashed_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$count = mysqli_num_rows($result);
if($count > 0){
$row = mysqli_fetch_assoc($result);
$id = $row["id"];
} else {
mysqli_free_result($result);
mysqli_close($connection);
header("Location: chat_error.php");
}
$msg = mysqli_real_escape_string($connection, $_POST["chat_message"]);
$username = $_SESSION["username"];
$date = date("d/m/Y");
$time = date("H:i:s");
$sql = "INSERT INTO chat_messages(chat_id, username, message, date, time) VALUES(?, ?, ?, ?, ?)";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'dssss', $id, $username, $msg, $date, $time);
mysqli_stmt_execute($stmt);
?>
Don't understand why you are using php $_POST in javascript, it will not work. Try using document.getElementById() to grab the chat message.
The correct way is shown below.
<script type="text/javascript">
function sendData(){
var cm = document.getElementById("message").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("q=<?php echo $hashed_id; ?>&chat_message=" + cm);
}
</script>
Also in your PHP code, why using json_decode()? The post is not in JSON format. Correct that also.
Change below code
$data = json_decode(file_get_contents("php://input"));
$hashed_id = $data->q;
$msg = $data->chat_message;
to
$hashed_id = $_POST["q"];
$msg = $_POST["chat_message"];
Do something like this
<script type="text/javascript">
function sendData(){
var id = <?php echo $hashed_id; ?>;
var msg = <?php echo $_POST['chat_message']; ?>;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "chat_form.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(id,msg);
}
</script>
I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.
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 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>';
?>
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.