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...
Related
I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST
I have a php file func.php where I defined many functions let's say :
<? php
function func1($data){
return $data+1;
}
?>
I want to call the function func1 using ajax. thank you for your help
You can't call a PHP function directly from an AJAX call, but you can do this:
PHP:
<? php
function func1($data){
return $data+1;
}
if (isset($_POST['callFunc1'])) {
echo func1($_POST['callFunc1']);
}
?>
JS:
$.ajax({
url: 'myFunctions.php',
type: 'post',
data: { "callFunc1": "1"},
success: function(response) { alert(response); }
});
You should call your php script through an ajax request, using jQuery like:
Javascript:
$.ajax({
url: "script.php",
data: { param1: "value1", param2: "value2" },
type: "GET",
context: document.body
}).done(function() {
// your code goes here
});
You could give your parameters through data property of ajax object.
Php
// you can do isset check before
$param1 = $_GET['param1'];
$param2 = $_GET['param2'];
// validate // sanitize // save to db // blah blah // do something with params
More information you could get from jQuery.ajax() function description from http://api.jquery.com/jQuery.ajax/
It's a bit more complicated, but I will try to shrink it down to the basics.
You will need some kind of interface (a convention, basically) between the caller and your script. Two are the main concerns here:
The way your script understands what needs to be called and with what arguments. Let's say you decide to use a GET request for calling a function. The function name could be in a func field and the arguments in an args one, as a string separated by ;. In other words, calling funcFoo(5,'bar') would be done by requesting func.php?func=func1&args=5;bar.
The way in which the caller receives (and understands) the return value. Since your requirements are js-oriented, a JSON approach would be highly appropriate.
Add the following code along with your functions:
if(isset($_GET['func']))
{
$func=$_GET['func'];
if(function_exists($func))
{
$args=(isset($_GET['args'])?explode(';',$_GET['args']):array());
$result=call_user_func_array($func,$args);
}
else
$result=array('error'=>"Unknown Function $func!");
}
else
$result=array('error'=>"No function name provided!");
echo json_encode($result);
However, your functions should also be changed to meet the new requirements. Since there's no way of telling how many arguments the caller will supply, a function should be designed to accept no mandatory arguments and check for the supplied ones itself. Also, it should always return an array in order to be json_encoded before it is returned to the caller.
Your example function, for instance, should look something like this:
function func1(){
$data=func_get_args();
if(count($data)) // at least one -- rest will be ignored
return $data[0]+1;
else
return array('error'=>__FUNCTION__."() expects an argument!");
}
Be aware though: This is just a skeleton to get you started with the whole concept. A lot more care should be taken for both fault tolerance and security. But that's another topic's subject.
Yes you can !
here my code :
$.ajax({
type: "POST",
url: "ajax.php",
data: { kode: $(this).val(), func: 'my_func' },
success: function(response) {
//any success method here
}
});
and here the code in php to receive what function to call.
$post = (object) $_POST;
if(!$post)
return false;
$func = $post->func;
return $func($post);
function my_func($post) {
$json['any_data'] = false;
if($post->kode == 'ND'){
$json['any_data'] = 'ND-'.date('Y');
}
echo json_encode($json);
}
Hope it help you out bro... :D
So, I am using jquery to make an ajax call to a php script on my server.
For some reason I cannot figure out, however, there is no querystring sent. Using var_dump() on the $_GET object shows that it is an empty string, and Chrome's network activity developer tool indicates no string is sent.
$.ajax({
"url":"../script/content.php",
"settings": {
"dataType":"html",
"type":"GET",
"data":{
"id":$(this).prop('id')
}
}
}).done( function(msg) {
//$('#debug').html(msg);
$('#dialog').html(msg);
$('#dialog').load(function() {
$('#close').click(function() {
$('#over').fadeOut(fadeTime);
});
if ($('#unique') > 0) {
$('#unique').load(function(){
$('#over').fadeIn(fadeTime);
});
}
else {
$('#over').fadeIn(fadeTime);
}
});
});
I had tried the ajax call without the quotes where they weren't necessary before hand, and the result was the same... I just put those in because I thought it might be the problem... though I think that in such notation the quotes don't make a difference unless one of the field values is supposed to be a string.
Is there anything clear in that code which might cause a querystring not to be sent? I guess there is a problem with my syntax... I just can't see it.
The #dialog load callback seems to never be called, either... but I guess that is another question.
Try this
$.ajax({
//The link we are accessing with params
url:'http://example.com/script/content.php'
+ '?id='
+ $(this).prop('id'),
// The type of request.
type: "get",
//The type of data that is getting returned.
dataType: "html",
error: function(){
//something here
},
success: function( strData ){
//something here
}
});
I need to load only new data into my div with ajax. At the moment I'm currently loading all data, because if I delete a record in the database it also removes it from my chat div.
Here is my js code:
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: '/ajax/client.php',
type: 'post',
data: { method: 'fetch', thread: thread},
success: function(data) {
$('.chat_window').html(data);
}
});
}
chat.throwMessage = function (message) {
if ($.trim(message).length != 0) {
$.ajax({
url: '/ajax/client.php',
type: 'post',
data: { method: 'throw', message: message, thread: thread},
success: function(data) {
chat.fetchMessages();
chat.entry.val('');
}
});
}
}
chat.entry = $('.entry');
chat.entry.bind('keydown', function(e) {
if(e.keyCode == 13) {
if($(this).val() == ''){
} else {
chat.throwMessage($(this).val());
e.preventDefault();
}
}
});
chat.interval = setInterval(chat.fetchMessages, 8000);
chat.fetchMessages();
I have had a look around and some say that if you pass a timestamp to the server and load new content that way, but I can't seem to get my head around that. If you need php let me know.
Right, so the timestamp thing makes the most sense. You'll need to do a few things:
On the back end, you need to make client.php accept a timestamp parameter in the querystring. When returning data, instead of just returning all of it, make it return everything since the time stamp, if given. Otherwise return everything.
The very first time you load the chat client, the first thing you should do is make an Ajax call to a new PHP file that returns the current server timestamp. Store the value of that in a Javascript variable as a Number.
During chat.fetchMessages(), increment the value of the timestamp variable by however long it's been since the last fetch (looks like 8000 milliseconds), and feed that to client.php, like url: '/ajax/client.php?timestamp=' + latestFetchTimestamp,
Instead of replacing all HTML content, append instead.
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".
All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
}
});
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
Any code that relies on the response from the AJAX request, must be called inside a callback to the request.
function check_name() {
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function (html) {
$("#checkname").html(html);
// I placed your code here instead.
// Of course you wouldn't need to set and then get the HTML,
// since you could just do a direct comparison.
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml == compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
The reason is that by default, an AJAX request is asynchronous, which means that the code that comes after the request will execute immediately instead of waiting for the response to return.
Another possible issue when comparing HTML to keep in mind is white space. If you're doing a string comparison, it must be exactly the same, so if there's whitespace, you'll need to trim it first. You can use jQuery.trim()(docs) to do this.
You have to put the code inside of you AJAX requests success callback, otherwise it will be called before the AJAX call has completed. Putting it inside the success callback means that the code containing the IF statement will only run after the AJAX call has completed. Try:
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
You could probably solve the problem doing what patrick dw suggested (it's likely that the ajax call has not been completed yet (i.e. div content wasn't updated) and the check returns false), but since string comparison can really bring to many errors (like string not matching because of newlines, trailing spaces, case sensitiveness, etc...) I would suggest you use another comparison method.
For example you could add a class using .addClass() if the car is found, and then checking if that div has the "found" class using .hasClass()
I use .post(). The third argument of post() is the returned data from the file where the data was posted.
I pass to validate.php the inputed email address, validate.php checks it and if it is valid, it returns 1.
$('a.post').click(function() {
$.post('validate.php',{email : $("#email-field").val()},
function(data){
if(data==1)
{
//do something if the email is valid
} else {
//do other thing
});
});
Hope this helps.