Tried to get answer, but returns 0.
JS in the head:
q = new XMLHttpRequest();
q.open('POST', ajaxUrl);
q.onreadystatechange = function () {
if (q.readyState === 4) {
console.log(q.response);
}
};
var data = {
'action': 'check_email'
};
q.send(JSON.stringify(data));
ajaxUrl links to admin_url('admin-ajax.php');
Code in the function.php:
function check_email() {
echo 'true or false';
die();
}
add_action('wp_ajax_check_email', 'check_email');
add_action('wp_ajax_nopriv_check_email', 'check_email');
Assuming a json request is valid, set the content-type to json
q.setRequestHeader('Content-Type', 'application/json');
if it isn't send application/x-www-form-urlencoded instead
q.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
...
q.send('action=check_email');
q.responseText is what you're looking for.
Related
I am trying to send the post request to my PHP file but it is saying undefined index.
my js code -
document.getElementById("btn1").addEventListener('click', xh );
function xh(){
xhr = new XMLHttpRequest();
//xhr.open('GET', 'req.php?msg=hello bro', true);
xhr.open('POST', 'req.php');
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
xhr.onprogress = function () {
// document.getElementById("loading").classList.remove("dis");
}
xhr.onload = function () {
console.log(this.responseText);
}
xhr.send("msg=hello");
}
my PHP code -
<?php
if(isset($_POST['msg'])){
echo "set";
}
else{
echo "not set";
}
?>
I also tried the server request method but it didn't work
it is showing not set, and if I try to echo the $_POST['msg']; it says undefined index 'msg'
Instead of
xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
you want to set the request header
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Read more about XHR. The present approach it to use fetch() though.
fetch("req.php", {
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: "msg=hello"
}).then(response => response.text())
.then(console.log)
I am creating a login form and I need to redirect the user to his/her profile page! I am using AJAX Requests so header redirect is not working at all. It just stays on the homepage. So how can I redirect the user to another page in pure javascript PHP ajax call? Please give the answer in pure javascript. I don't like to use jQuery at all!
Javascript:
function ajaxCall(){
var xhttp;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function(){
if(this.readyState === 4 && this.status === 200){
document.getElementById('error').innerHTML = this.responseText;
}
};
var parameters = 'email='+document.getElementById('email')+'&password='+document.getElementById('password');
xhttp.open('POST', 'login.php', true);
xhttp.setRequestHeader('Content-type', 'application/x-www/form/urlencoded');
xhttp.send(parameters);
}
Login.php(PHP)
<?php
if(isset($_POST['email']) && isset($_POST['password'])){
$ema = $_POST['email'];
$pass = $_POST['password'];
if(!empty($ema) && !empty($pass)){
if($ema === 'Bill' && $pass === 'Cool'){
header('Location: https://www.google.com');
}
}
}
Make an ajax call.
<?php
header('Content-Type: application/json');
echo json_encode(['location'=>'/user/profile/']);
exit;
?>
The ajax response will return something like
{'location':'/user/profile/'}
In your ajax success javascript function
xhr.onreadystatechange = function () {
if (xhr.status >= 200 && xhr.status <= 299)
{
var response = JSON.parse(xhr.responseText);
if(response.location){
window.location.href = response.location;
}
}
}
I landed here looking for an Ajax solution, nevertheless MontrealDevOne's answer provided useful. If anyone else is curious about the ajax method too, here you go:
$('body').on('submit', '#form_register', function (e) {
var form = $(this);
$.ajax({
type: 'POST',
url: 'form_submissions.php',
data: form.serialize() + "&submit",
dataType:"json",
success: function (data) {
if(data.location){
window.location.href = data.location;
}
},
error: function(data) {
alert("Error!");
}
});
e.preventDefault();
});
Just my 2 cents, hope it helps :)
try this bill if its works.
window.location.replace("http://www.google.com");
I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.
Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax
I've been looking for a simple example of how to send POST data in a cross domain request in IE (with the XDomainRequest object).
I've been able to make a simple POST request, but haven't been able to add POST data to it.
Any help is appreciated, thanks!
Try something like this:
var xdr;
function err() {
alert('Error');
}
function timeo() {
alert('Time off');
}
function loadd() {
alert('Response: ' +xdr.responseText);
}
function stopdata() {
xdr.abort();
}
xdr = new XDomainRequest();
if (xdr) {
xdr.onerror = err;
xdr.ontimeout = timeo;
xdr.onload = loadd;
xdr.timeout = 10000;
xdr.open('POST','http://example.com');
xdr.send('foo=12345');
//xdr.send('foo=<?php echo $foo; ?>'); to send php variable
} else {
alert('XDR undefined');
}
Server side (php):
header('Access-Control-Allow-Origin: *');
if(isset($HTTP_RAW_POST_DATA)) {
parse_str($HTTP_RAW_POST_DATA); // here you will get variable $foo
if($foo == 12345) {
echo "Cool!"; // This is response body
}
}