how to get parameter for an ajax request in php - php

Edit: I solved my prblem, eveyone. I have linked to a wrong javascript page. thats silly. thank u very much though
I have an ajax request GET with parameter random: yes, but when I use PHP to check for the parameter, the parameter doesn't seem to exits
my code is like this:
for ajax
function fetchData() {
new Ajax.Request("webservice.php", {
method: "get",
parameters: {random: "yes"},
onSuccess: displayData,
onFailure: ajaxFailure,
onException: ajaxFailure
});
}
and I write PHP to check the parameter
if ($_GET["random"] == "yes"){
do something
}else if(isset($_REQUEST["poll"]) && $_SERVER["REQUEST_METHOD"] == "GET"){
//this is b/c i have another ajax request with parameters {poll: "favChar"},
do something
}
I get the error of making ajax request. I have check my PHP code. I enter wwww.domainname.com/webservice.php?random=yes and the page output the results correctly.
Can someone help me? Thank u

The easiest way is adding the parameter in the URL:
new Ajax.Request("webservice.php?random=yes", {
// options
});

Create an AJAX obj first: var http = new XMLHttpRequest();
The GET method:
var url = "webservice.php";
var params = "random=yes&param=value";
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);

According to the documentation, parameters requires a Hash-compatible object, so you might have to convert your plain JavaScript hash, like so:
function fetchData() {
new Ajax.Request("webservice.php", {
method: "get",
parameters: $H({random: "yes"}),
onSuccess: displayData,
onFailure: ajaxFailure,
onException: ajaxFailure
});
}

Related

How to get a variable from PHP file using Ajax?

I just started studying PHP and Ajax and I can't figure out how to bring a single variable from PHP file to my html file using Ajax. Can you please explain me how it works?
So far I understood that you create the request:
var xhttp = new XMLHttpRequest();
And that you send it to the server:
xhttp.open("GET", "demo_get.php", true);
xhttp.send();
Then you get the data from the PHP file using
xhttp.responseText
Now, I only want to send a variable from the server, for example
$name = "John"
How should my php code look like in order to send only that specific variable?
As a beginner, it would be a lot easier to use jQuery for your AJAX requests. I've been in this industry for over half my life and I still use it alot.
getstuff.php
header('Content-type: application/json');
echo json_encode(["FirstName" => "John"]);
exit;
jquery:
$.ajax({
url: '/getstuff.php',
success: function (response) {
console.log(response);
alert(response.FirstName);
}
});
I suggest using JSON as data interchange format, here is the javascript part:
let request = new XMLHttpRequest();
request.open('GET', 'demo_get.php', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success
let parsed_response = JSON.parse(this.response.trim());
console.log(parsed_response.my_var);
} else {
// Error
console.log(this.response);
}
};
request.onerror = function() {
console.log('Connection error!');
};
request.send();
The PHP part then would look like this:
<?php
header('Content-Type: application/json');
$my_response_data = ['my_var' => 'foo'];
echo json_encode($my_response_data);
exit;
... and some useful info about XMLHttpRequest.responseText vs XMLHttpRequest.response

javascript to post to url and

I am writing a javascript which will post hostname of the site to a php page and get back response from it, but I don't know how to assign the hostname to adrs in url and not sure that code is correct or not.And this needs to done across server
javascript:
function ursl()
{
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
success: function (response)
if (response)=='yes';
{
alert("yes");
}
});
}
track.php
$url=$_GET['adrs'];
$sql="SELECT * FROM website_ad where site='$url'";
$res=mysqli_query($link,$sql);
if(mysqli_num_rows($res)==0)
{
echo"no";
}
else
{
echo"yes";
}
Your ajax function should be written thusly:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=' + window.location.hostname,
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
window.location.hostname will give you the host name. You are passing it to the ajax url by concatenating it. Alternatively, as katana314 points out, you could pass the data in a separate parameter. Your ajax call would then look like this:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
data: {adrs: window.location.hostname},
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
I'm not sure what you intend response to be, but this code assumes it is a string and will match true if the string is 'yes'. If response is meant to be something else, you need to set your test accordingly.
$.getScript() will load your external script, but since it's asynchronous you'll have to put any code that is dependent on that in the callback.
In this type of GET request, the variable simply comes after the equals sign in the URL. The most basic way is to write this:
url: 'http://example.com/en/member/track.php?adrs=' + valueToAdd,
Alternatively, JQuery has a more intuitive way of including it.
$.ajax({
url: 'http://example.com/en/member/track.php',
data: { adrs: valueToAdd }
// the rest of the parameters as you had them.
Also note that you can't put a script tag inside a script. You will need some other way to run the Javascript function mentioned; for instance, wrap its contents in a function, load that function first (with a script tag earlier in the HTML), and then call it on success.
And for the final puzzle piece, you can retrieve the current host with window.location.host
You'll need to change this line to look like so:
url: 'http://example.com/en/member/track.php?adrs='+encodeURIComponent(document.URL)
The full success function should look like so:
success: function (response){
if (response==="yes"){
//do your thing here
}
}
That should solve it...

How To Return Data from PHP to Use in jQuery(ajax)?

I have to process a Simple log-in File. In Many Web Tutorials I have read that for any Ajax requests in jquery the callback function is function(data) and the data is returned by the server side script.
Well, my server side script is PHP. I wish to know how can I return data from PHP which will be stored in jquery's data and I can use conditional loops to process them.
Here is my jquery Code:
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, processLI );
function processLI(data) {
if (data == 'success'){
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
}
I am using simple return statement in my php file, which does not seem to work at all. here is the login.php file. I just posted the part necessary here.
$statement = $connection->prepare("SELECT * FROM users WHERE username = '$username'");
$statement->execute(array());
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result['password'] == $safepass) {
setcookie("Login", true);
echo 'success';
}
else
echo "Failure";
Try doing it like this, by placing the function as the parameter, and not by calling the function.
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.post('login.php', querystring, function(data){
if (data == 'success') {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
}
else
alert ('Login Failed');
});
Use the echo statement to output data, if the login is successful echo 'success';
This is an answer about how to debug AJAX requests. First, use Chrome (or Safari, or Firefox with Firebug plugin installed), then open up the developer tools from the settings menu. In the network panel, you can see the request/response. It may not be a direct answer, but please - try to use the Chrome developer tools with the "Net Panel" to see request/response/cookies/headers.
This will save you the trouble of having to guess, it will show you the response verbatim. Then you can solve it next time ;) and the time after
Have you been able to see the request/response? If not, I suggest a simple
alert(JSON.stringify(data))
...from your callback function if you have issues using the Chrome debugger.
Try giving the dataType for post as 'html'
$('#loginform').submit( function() {
var querystring = $(this).serialize();
$.ajax({
url : 'login.php?'+querystring,
cache : false,
success : function(data) {
if(data == "success") {
alert("Successful");
var url = "game.php";
$(location).attr('href',url);
} else if(data == "failure") {
alert("Login Failed");
}
};
});
});

JavaScript Ajax request vs jQuery $.ajax

NOTE: I've pasted more code than just the ajax calls, on the off chance that code is (part of) what's causing the problem. I don't think it is, however, so you're probably better off focussing on the ajax and jAjax functions a bit further down. Also note that, since there's a comment (with upvote) on this question saying my code is hard to decipher, I'd happily clarify what needs clarifying if that could prove to be the key in finding the problem. Thanks.
Here's the thing. I'm trying to ditch jQuery, since the only thing I use is the $.ajax() method, and including an entire lib like jQuery for just 1 feature is IMO crazy. I don't even need the full functionality of the $.ajax method anyway, hence I wrote my own ajax function.
The problem is: it's not working, and I can't seem to figure out why. I'm trying to send objects to the server (specifically: ajaxAction in the controller - using Zend FW). Below is the javascript code, and a summary of what the firebug console tells me.
if (!String.prototype.trim)
{
String.prototype.trim = function()
{
"use strict";
return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};
}
function getUrl(action,controller)
{
var base,uri;
base = window.location.href.replace('http://'+window.location.host,'');
if (base.length > 1)
{
base = base.substring(1,base.length).split('/');
controller = controller || base[0];
base[0] = controller || base[0];
base[1] = action || base[1];
return '/'+base.join('/');
}
controller = controller || 'index';
action = action || 'ajax';
return base+controller+'/'+action;
}
function formalizeObject(obj,recursion)
{
recursion = recursion || false;
if (typeof obj !== 'object')
{
throw new Error('no object provided');
}
var ret = '';
for (var i in obj)
{
if (!obj.hasOwnProperty(i) || typeof obj[i] === 'function')
{
continue;
}
if (recursion)
{
ret +='['+i+']';
}
else
{
ret += (ret.length > 0 ? '&' : '') + i.toString();
}
if (typeof obj[i] === 'object')
{
ret += formalizeObject(obj[i],true);
continue;
}
ret += '='+obj[i].toString();
}
if (recursion)
{
return ret;
}
return encodeURI(ret);
}
function success()
{
if (this.readyState===4 && this.status===200)
{
console.log(this.responseText);
}
}
function ajax(str,url,method,json)
{
var ret;
json = json || false;
str = str || {};
method = method || 'POST';
url = url || getUrl();
str =
str = (typeof str === 'object' ? str : {data:str});
try
{
ret = new XMLHttpRequest();
}
catch (error)
{
try
{
ret= new ActiveXObject('Msxml2.XMLHTTP');
}
catch(error)
{
try
{
ret= new ActiveXObject('Microsoft.XMLHTTP');
}
catch(error)
{
throw new Error('no Ajax support?');
}
}
}
if (typeof ret !== 'object')
{
throw new Error('No Ajax, FFS');
}
ret.open(method, url, true);
ret.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
ret.setRequestHeader('Content-type', (json ? 'application/json' : 'application/x-www-form-urlencode'));
ret.onreadystatechange = success;
ret.send((json ? JSON.stringify(str) : formalizeObject(str)));
return true;
}
function jAjax(str,url)
{
$.ajax(
{
url : url,
data: str,
type: 'POST',
success: function(res)
{
console.log(res);
}
});
}
Four ways in which I've tried to make the Ajax request:
jAjax({data:{foo:'bar'}},getUrl());//1
jAjax({data:{foo:'bar'}},getUrl(),true);//2
ajax({data:{foo:'bar'}},getUrl());//3
ajax({data:{foo:'bar'}},getUrl(),true);//4
jAjax({data:{foo:'bar'}},getUrl());: This works just fine:
[]{"ajax":true,"controller":"index","action":"ajax","module":"default","identity":{},"data":{"foo":"Bar"}}
Parameters: data[foo] 'bar' And Source: data%5Bfoo%5D=Bar (from POST tab in FB console)
Header: application/x-www-form-urlencoded; charset=UTF-8
All of this was sent to the following url: http://www.foo.bar/index/ajax?data%5Bfoo%5D=bar
This doesn't work, however:
[]{"ajax":true,"controller":"index","action":"ajax","module":"default","identity":{}} is the response
POST tab in FB: JSON data: {foo:'Bar'} source: {"data":{"Foo":"Bar"}} (but same url is case 1)
Header: json; charset=UTF-8
This is the big one: the full request url is identical to url from case 1, as are the headers BUT when I look at the POST tab in the FB console (inspect the request) This is the only difference I can find:
case 1: Parameters: data[foo] 'bar' Source: data%5Bfoo%5D=Bar
In this case, I can't see the Parameters section, only: Source: data%5Bfoo%5D=Bar
Identical to case2, except for the url, which I think I forgot to pass through encodeURI. This case is less important for now. I think/hope I'll get this working the moment I figure out what's wrong with case 3.
In all 4 cases, the request is sent, and received. The controller action is as follows:
public function ajaxAction()
{
$this->_helper->layout->disableLayout();
$this->getHelper('viewRenderer')->setNoRender();
$this->_helper->getHelper('AjaxContext')->addActionContext( 'ajax' , 'json' )
->initContext('json');
if($this->getRequest()->isPost() && $this->getRequest()->isXmlHttpRequest())
{
echo json_encode(array_merge(array('ajax'=>true),$this->_getAllParams()));
}
else
{
throw new Exception('no ajax call made??');
}
}
Since I'm receiving a JSON string, I'm sure the request is posted, and has the correct XMLHttpRequest header. Why then, can't I post JSON objects? Even more to the point: why is case 3 not working? What is jQuery doing that I'm not aware of? What is it, that makes case 1 to work, but not case 3?
PS: It might be irrelevant, but in a moment of madness I tried adding this: ret.setRequestHeader('Connection','close'); to the ajax function, but I noticed that, in the header that got sent out, Connection was set to keep-alive all the same. Perhaps this gives someone a clue as to what went wrong?
Thanks in advance
In case anybody wonders what was wrong:
ret.setRequestHeader('Content-type', 'application/x-www-form-urlencode');
Should have been "x-www-form-urlencoded", with a "d" in the end:
ret.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
sending a formalized object is now working, and I can get rid of jQuery :-)

Return xmlhttpRequest if no text present in the asked page

i want to recall the GM_xmlhttpRequest if there is not text answered in the page, like a loop.
GM_xmlhttpRequest({
method: 'POST',
url: 'http://localhost/getcaptcha.php',
data: 'login='+login+'&password='+password,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(responseDetails) {
if(responseDetails.responseText.length==3) {
// do something
}
else{
// i wanna go back to the GM_xmlhttpRequest again while there's no answer with the length==3
}
}
});
How can i do it?
Thanks from now.
Put your request code into a function and simply call it again if the request fails. Something like this:
function sendRequest(attempt)
{
// If the parameter is missing then this is our first attempt
if (typeof attempt == "undefined")
attempt = 1;
GM_xmlhttpRequest({
...
// If request failed and we tried less than three times - try again
if (attempt <= 3)
sendRequest(attempt + 1);
...
});
}
sendRequest();

Categories