XMLHttpRequest is not allowed by Access-Control-Allow-Origin - php

PHP:
<?php
header('Access-Control-Allow-Origin: *');
include_once("db_connect.php");
$username = '';
$video = '';
$rating ='';
if(isset($_GET["u"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
echo "No UserName";
}
if(isset($_GET["v"])){
$video= preg_replace('#[0-9]#i','',$_GET['v']);
} else {
echo "No Video ID";
}
...
?>
JavaScript:
function like(u,v) {
document.getElementById("rating").innerHTML="loading...";
var ajax = ajaxObj("POST","http://www.url.com/ratingphp.php");
ajax.onreadystatechange=function(){
if(ajaxReturn(ajax) === true){
document.getElementById("rating").innerHTML=ajax.responseText;
}
};
ajax.send("u="+u+"&v="+v+"&like");
}
function dislike(u,v) {
document.getElementById("rating").innerHTML="loading...";
var ajax = ajaxObj("POST","http://www.url.com/ratingphp.php");
ajax.onreadystatechange=function(){
if(ajaxReturn(ajax) === true){
document.getElementById("rating").innerHTML=ajax.responseText;
}
};
ajax.send("u="+u+"&v="+v+"&dislike");
}
function ajaxObj(meth,url){
var x= new XMLHttpRequest();
x.open(meth,url,true);
x.setRequestHeader("Content-type","application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
So as you can see I've allowed Access-Control-Allow-Origin in my PHP though I keep getting the error:
XMLHttpRequest cannot load http://www.url.com/ratingphp.php. Origin http://www.url2.com is not allowed by Access-Control-Allow-Origin. h37:1
Am I doing something wrong in my ajaxObj function with the setRequestHeader? First time doing a cross site php code. I'm just trying to figure out why my code is not executing correctly for the ACAO

just add this in PHP ..
header("Access-Control-Allow-Headers : Content-Type");
header("Access-Control-Allow-Methods : POST, OPTIONS");

header('Access-Control-Allow-Origin: *');

Related

form validation in codeigniter with ajax

I want to validate groupname.
I am using ajax but it is not working
This is my view
<?php echo form_input(['name'=>'groupname','class'=>'form-control','placeholder'=>'Enter group name','value'=>'','ng-model'=>'myWelcome[0].groupname','onkeyup'=>'loadValid(this.value)']) ?>
Javascript function
<script type="text/javascript">
function loadValid(v) {
if(v)
{
var url= window.location.href;
var res = url.split("/");
var groupid = res[res.length-1];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", site_url + "admin/Usergroup_controller/store_edit_group_name_ajax/" + groupid + "/" + v, true);
xhttp.send();
}
else
{
document.getElementById("demo").innerHTML = "Group name is required field.";
}
}
</script>
Controller function
public function store_edit_group_name_ajax($groupid,$groupname)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('groupname', 'Group name', 'trim|required|alpha|is_unique[group.groupname]|min_length[3]');
if( $this->form_validation->run() )
{
echo form_error('groupname','<p class="text-danger">','</p>');
}
}
Please help...
Make sure you are creating a response object first.
$response = new stdClass();
if ($this->form_validation->run() == false)
{
$response->status = 'failure';
$response->error = validation_errors('<p class="text-danger">', '</p>');
}
...
return $response;
In Javascript after getting response;
document.getElementById("demo").innerHTML = xhttp.responseText.error;
Just echo-ing ajax results is something you need to leave immediately. Please take it as a friendly advise.

ajax request not posting form data

I have a problem where the values entered (email and password) into my login form are not being parsed to my server php script.
My ajax request:
function signin(){
var loginEmail = gebi("loginEmail").value;
var loginPass = gebi("loginPass").value;
if(loginEmail == "" || loginPass == ""){
gebi("loginEmail").style.borderColor = "red";
gebi("loginPass").style.borderColor = "red";
} else {
gebi("signinBtn").style.display = "none";
//Declare ajax request variables
hr = new XMLHttpRequest();
url = "main.php";
vars = "email="+loginEmail+"&pass="+loginPass;
//Open the PHP file that is receiving the request
hr.open("POST", url, true);
//Set content type header info for sending url ecncoded variable in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Trim string data before sending it
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
//Access the onreadystatechange event for the XMLHttpRequest
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var responseText = hr.responseText.trim();
if (responseText != "signin_failed") {
console.log(responseText);
} else {
console.log(responseText);
gebi("signinBtn").style.display = "block";
gebi("loginEmail").style.borderColor = "red";
gebi("loginPass").style.borderColor = "red";
}
}
}
//Send the data to the PHP file for processing and wait for responseText
hr.send(vars);
}
}
and when the php script returns a value using this code:
if (isset($_POST["email"])) {
echo 'email = '+$_POST["email"];
}
the return value that is logged to the console is '0' even tho there is data present in the forms fields.
What is going wrong?
The problem is in your PHP script. If you are trying to concatenate string in PHP use dot .. + is used to concatenate string in languages like javascript.
echo 'email = ' . $_POST["email"];

What is the value of ajax.responseText when there is no response being sent?

I wrote a javascript function that checks if a username is available in a database. If the username is NOT available the ajax send a text response back which changes some css and adds an error message. When the username is available the ajax doesn't send a response, which is fine but I just need to know what is being returned from ajax.responseText since there is no value. I've tried '' and null.
function _(x) {
return document.getElementById(x);
}
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function verifyEmail(){
var email = _("email").value;
var status = _("estatus");
var emailRegEx = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (document.signupform.email.value.search(emailRegEx) == -1) {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
status.innerHTML = "<br />Please enter a valid email address";
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
status.innerHTML = "";
if (email != "") {
status.innerHTML = "checking. . . ";
var ajax = ajaxObj("POST", "fan_signup_local.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
status.innerHTML = ajax.responseText;
console.log(status.innerHTML);
if (status.innerHTML !== '') {
_("emaildiv").style.border = "1px solid #d33e3e";
_("emaildiv").style.backgroundColor = "#fadede";
console.log(ajax.responseText);
} else {
_("emaildiv").style.border = "";
_("emaildiv").style.backgroundColor = "";
}
}
}
ajax.send("email="+email);
}
}
}
There's always a response, unless the request times out. If the server script exits without printing anything, the response will be an empty string.

Insert mySQL query if checkbox checked/not checked with PHP

During the process of trying to develop an checkbox activated mySQL query based on the value inside a checkbox i've incurred an problem which i can't get past, I've tried the following at the moment
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
The Javascript/Ajax code for the function "updateStatus" is as followed
function updateStatus(id,value) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id + "&checked="+value, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
The PHP function inside functions/ajax.php
if(isset($check) and $check == 'update_status' and isset($_GET['id'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
echo "Checked";
} elseif($checked == false) {
echo "Not checked";
} else {
echo "Invalid response";
}
when using this code it always returned "Checked" any idea why ?
try this (code tested),
<input type="checkbox" name="status" onclick="updateStatus(<? echo $data['id']; ?>,this.checked)">
You will get second parameter as true or false;
function updateStatus(id,checked) {
if (window.XMLHttpRequest) {
http = new XMLHttpRequest()
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP")
} else {
alert("Your browser does not support XMLHTTP!")
}
http.abort();
http.open("GET", "../functions/ajax.php?check=update_status&id=" + id+"checked="+checked, true);
http.onreadystatechange = function () {
if (http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null)
You PHP will be:
if(isset($check) and $check == 'update_status' and isset($_GET['id']) AND isset($_GET['checked'])){
$id = mysql_real_escape_string($_GET['id']);
$checked= mysql_real_escape_string($_GET['checked']);
if($checked == true) {
$query = mysql_query("SELECT * FROM `check_status` WHERE `user_id` = '$_SESSION[userid]' and `id` = '$id'");
else
//some other query
//Then i can insert the query based on if the checkbox checked or not.

PHP and AJAX onclick redirection

I am using Ajax to populate a drop down menu from the database, my question is how do I onclick redirect it to a page along with the CARD_ID i got back from the database?
right now when I click on it it's displaying the card name in the search bar which is part of what I want but now I need the other half the redirection. How can I achieve this?
<?php
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$str = $_GET['content'];
if(strlen($str))
{
$sel = mysqli_query($mysqli, "select CARD_NAME, CARD_ID,CARD_TYPE from cards where CARD_NAME like '".trim($str)."%'");
if(mysqli_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysqli_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysqli_fetch_array($sel))
{
$card_info = str_ireplace($str,"<b>".$str."</b>",($row['CARD_NAME']));
$card_type = str_ireplace($str,"<b>".$str."</b>",($row['CARD_TYPE']));
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\" onClick=\"display('".$row['CARD_NAME']."');\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
the javascript.
subject_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (subject_id != '') {
document.getElementById(subject_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function getScriptPage(div_id,content_id)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
if(content.length>0)
box('1');
else
box('0');
}
function highlight(action,id)
{
if(action)
document.getElementById('word'+id).bgColor = "#C2B8F5";
else
document.getElementById('word'+id).bgColor = "#F8F8F8";
}
function display(word)
{
document.getElementById('text_content').value = word;
document.getElementById('box').style.display = 'none';
document.getElementById('text_content').focus();
}
function box(act)
{
if(act=='0')
{
document.getElementById('box').style.display = 'none';
}
else
document.getElementById('box').style.display = 'block';
}
the html
<div class="ajax-div">
<div class="searchbar">
<input type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content">
</div>
<div id="box"></div>
</div>
I'm not sure what you are trying to do, but it seems you want something like this:
1- Change the way you display your rows so that the ID gets sent to your function as well:
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\"
onClick=\"display('".$row['CARD_NAME']."', " . $row['CARD_ID'] . ");\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
^^^^^^^^^^^^^^^^^^^^^^^^^
2- Change your display function to redirect
function display(word, id)
{
// document.getElementById('text_content').value = word;
// document.getElementById('box').style.display = 'none';
// document.getElementById('text_content').focus();
window.location.href = "some_page.php?card_id=" + id;
}
I have commented out the original lines because there doesn't seem much point in doing stuff on a page you are leaving anyway. You could also completely remove the word parameter if this is the solution you are looking for.

Categories