Basic ajax logic - php

Upon suggestion of using Ajax for an html page, I decided to attempt to learn how it works. In my example, I'm just trying to get the response from a php file (which just echoes a simple string as a test) but it doesn't work, in that nothing actually happens.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title> Incident Center </title>
<!--<link rel="stylesheet" href="http://web.njit.edu/~swp5/assignment/style/style.css">-->
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function onsubmit()
{
var sender;
if (window.XMLHttpRequest)
{
sender=new XMLHttpRequest();
}
else
{
sender=new ActiveXObject("Microsoft.XMLHTTP");
}
sender.onreadystatechange=function()
{
if (sender.readyState==4 && sender.status==200)
{
document.getElementById("myDiv").innerHTML=sender.responseText;
}
}
sender.open("GET","proz.php",true);
sender.send();
}
</script>
</head>
<body>
<div class="header">
Incident Center
</div>
<p>
<button onclick="onsubmit()">Test</button>
</p>
<div id="myDiv"></div>
</body>
</html>

As I already mentioned in my comment, you should check the response code of your request to see if something went wrong. Add the following line to the start of your onreadystatechanged function:
alert(sender.readyState + ', ' + sender.status + ', ' + sender.responseText);
Based on this output you can probably determine your error.

Using Opera 11.51 here, it doesn't actually like the fact that you use onsubmit() as a function name. Presumably because onsubmit() is actually already an eventhandler hook of a <button> element itself. I presume other browsers won't like this function name either.
So, first off, rename the function. Let's assume dosubmit() here.
Furthermore, you should wrap a button in a <form> element. And because a default button, acts as a submit button, the form is being submitted, causing the page to reload.
To prevent this, you should let the function return false; and call the function like so onclick="return dosubmit()", if you are going to call it inline like this, or make the button a button of type button, like so: <button type="button" onclick="dosubmit()">

Why don't you use jQuery ? http://www.jquery.com/

Send doesn't actually display anything. Send calls the page and populates two different variables. What send does is populates the "responseXML" and "responseText" properties of the sender. Try after your send:
alert(sender.responseText);
See http://en.wikipedia.org/wiki/XMLHttpRequest

It's much easier to use jQuery to do this as it has a built in AJAX function. Your code would look like this:
jQuery.ajax({
type: 'get',
url: 'proz.php',
error: function(r) {
alert("Something went wrong - "+r);
}
success: function(response) {
alert(response);
}
});
Hope that helps

Related

Ajax is driving me nuts. Why is Jquery post method failing in this specific case?

Ok, so ajax seems to be misbehaving. In other words i'm doing something wrong. I have a simple angular js app. The html looks like this:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="../scripts/form_controllers.js"></script>
</head>
<body ng-app="EditDocApp">
<div ng-controller="EventDetector">
<input ng-model="event">
<button ng-click = "SelectEvent()">Click</button>
</div>
</body>
</html>
form_controllers.js contains a call to the Jquery post method in the EventHandle angular service. This is invoked in the calling of EventHandle.ajaxRequest() in the $scope.SelectEvent method in the EventDetector controller. This is form_controllers.js:
var editDocApp = angular.module("EditDocApp", []);
editDocApp.controller("EventDetector", eventDetector)
.factory("HandleEvents", handleEvents);
function handleEvents() {
var pass_back = {
ajaxLastReturn: "one",
ajaxRequest: function() {
$.post("http://localhost/TrailGuide/Website/Interface/webDataModelBuild/Documentation/scripts/test1.php", {}, function(response) { alert(response); })
.fail(function() { alert("nah"); });
}
}
return pass_back;
}
function eventDetector($scope, HandleEvents) {
$scope.event = "";
$scope.SelectEvent = function() {
$scope.event = "select";
HandleEvents.ajaxRequest();
};
}
The $.post method is failing every time i execute it by calling $scope.SelectEvent() from the button in the view (an alert box with "nah" pops up). I've tested the address passed to $.post by copying and pasting to the browser address box and it runs fine. I've tried the $.post method with and without data, no dice. I've tried jquery.ajax, still no dice. The php file, test1.php, is as follows:
<?php
echo "I am here!";
?>
Can somebody please point out what i am missing here? Is there some setting in php.ini that could be effecting this? Btw, this is my very first post on stack overflow so go easy on me! I'll get the hang of it. Thanks a bunch!

AJAX isn't triggering PHP script

I cannot for the life of me figure out what is going on here. I'll open a different browser to check if what I changed works, and maybe my other browser cached something, and it will work! But then I do it again and it doesn't seem to. I'm going crazy.
On my website, syllableapp.com, I created a MySQL database I could connect to. I made a PHP script that connects to it, adds a simple entry to it, and is done. It's called register_email.php, and it's available to access here. Accessing it manually via that URL will add the entry. Its code is as follows:
<?php
$db = new mysqli("localhost", "username", "password", "table");
if ($db->connect_error) {
echo "Could not connect to database.";
exit;
}
else {
$db->query("INSERT INTO emails (email) VALUES ('weird')");
echo 1;
}
?>
If I check, it gets added.
However, I want it to be added from a form. I have an HTML file at http://syllableapp.com/test/index.html that looks like this:
<html>
<head>
<title>Syllable - iPhone Speed Reader</title>
<link rel="stylesheet" href="styles/style.css">
<script type="text/javascript" src="scripts/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.23.min.js"></script>
</head>
<body>
<div class="content">
<img src="images/app-icon.png" alt="App icon">
<h1>Syllable</h1>
<p>Speed reading app for iPhone. Devour all your Instapaper and Pocket articles, and learn to read much faster in the process.</p>
<form method="post" action="">
<input type="email" class="email" placeholder="Email me when it's live">
<input type="submit" class="submit" value="Send">
</form>
</div>
</body>
</html>
So when the user submits the form, the JavaScript file I linked to at the top intercepts the submit button press, and calls an AJAX function to submit it to the PHP form. The jQuery for that looks like:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var email = $.trim($('.email').val());
var emailRegEx = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (email == "" || !emailRegEx.test(email)) {
event.preventDefault();
$(this).effect("shake", { times:2 }, 75);
}
else {
$.ajax({
type: "POST",
url: "http://syllableapp.com/test/register_email.php",
data: { "message": "hi" },
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
});
});
Which basically just checks if it's a valid email address, then if so, calls the PHP file.
However, every time I click submit, it says failure. Why on earth is this happening? Why can I access it directly, but it won't let me use AJAX?
Just a guess, but in your AJAX block change the URL line to this:
url: "register_email.php",
Also, as a test,
(1) change your alert command in the AJAX success function to:
alert(data);
and (2) insert this line immediately following the <?php directive in the file "register_email.php":
die('Made it to here');
A few things:
1) You're form needs an action or else it's not proper HTML. You can set it to a value like "#"
2) When you click the submit button, you want the form submitted using custom ajax, and not through the standard way. Your ajax handler for the click event should be something like:
$('input[type="submit"]').click(function(event) {
event.preventDefault();
//...
});
You have event.preventDefault in your code, but the event variable isn't being passed to the function. And I think you want event.preventDefault called every time, not just in the case of input validation failure.
3) Instead of using alerts, try using console.log and monitoring your javascript console to see if you get any errors. Add those errors to your question to help us with your issue.

pass query string variables without refresh page

My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.

Ajax call to a PHP page always returns nothing even though the PHP page echoes something

I am calling a very simple PHP page with some equally simple AJAX, but the call always returns nothing, even though the PHP is fine. That is, you can go to the URL of the PHP page and see that it echoes "Hello World" but when it is called with JS, it returns nothing.
Below is the HTML Page with the Javascript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......<br />
Enter your email: <input id="email" type="text" />
<input type="button" onclick="setXMLHttpRequest()" value="Go!" />
<script type='text/javascript'/>
var http;
function setXMLHttpRequest()
{
if(window.XMLHttpRequest)
http = new XMLHttpRequest();
else if(window.ActiveXObject)
http = new ActiveXObject("Microsoft.XMLHTTP");
url = "http://www.convolutedconstruct.com /Ajax/checkemail.php?email=" +
document.getElementById('email').value;
http.onreadystatechange = display;
http.open("GET", url, true);
http.send(null);
}
function display()
{
if (http.readyState == 4)
{
infostr = http.responseText;
alert("From the PHP: " + infostr);
}
}
</script></body></html>
Here is the content of the PHP page
Click here for the live PHP page
<?php
$email = $_GET['email'];
echo "Hello World!";
?>
Why does this return nothing to the JS, even though the PHP page echoes the text correctly?
As has been suggested above, AJAX request will only work usually when both the caller and called are on same domain, You have to ensure that your html code, which contains the javascript, resides on same domain http://www.convolutedconstruct.com.
If that is not the case you can use CORS to allow your ajax to receive input from your php page by sending this header in your php output
<?php
header("Access-Control-Allow-Origin: *");
//rest of your code
?>
See: http://enable-cors.org/
i dont like using the XMLHTTP request. instead i use jQuery's method $.ajax({}); method. it always works for me!
$.ajax({
type: "POST", // or 'GET'
url: "your-url.php", // url that you are passing the data to
data: {
dataName: 'data to pass' // string, variable, object, array, etc
},
success: function(output) { // output is what the url is 'echoing' back to the jQuery
// do something when the ajax method is complete.
}
});
dont forget to import the jQuery source code - http://code.jquery.com/jquery-1.7.2.min.js
these are the most common of the components that are used in ajax.
I'll be glad to help you out some more if you would like it.
If you want to know more just check the documentation on it: http://api.jquery.com/jQuery.ajax/

How to insert javascript value into the php session variable

I want to insert javascript value into the php session variable but inside the javascript function.
Here is what I have tried and it is not working:
function languageChange()
{
var lang = $('#websites1 option:selected').val();
<?php $_SESSION['SESS_LANGUAGE']?> = lang;
alert(<?php echo $_SESSION['SESS_LANGUAGE']?>);
}
You cannot access it directly (the way you are doing). However, it can be done using AJAX.
Here is the perfectly working solution.
Here is the HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label for="websites1">Websites</label>
<select name="websites1" id="websites1">
<option value="Design">Design</option>
<option value="Dev">Dev</option>
<option value="Ecom">Ecom</option>
</select>
</form>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function languageChange()
{
var lang = $('#websites1 option:selected').val();
return lang;
}
$('#websites1').change(function(e) {
var lang = languageChange();
var dataString = 'lang=' + lang;
$.ajax({
type: "POST",
url: "pass_value.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(response) {
alert(response.message);
}
});
return false;
});
});
</script>
</body>
</html>
Here is the AJAX part:
//pass_value.php
<?php session_start();
$_SESSION['SESS_LANGUAGE'] = $_POST['lang'];
$_SESSION['SESS_LANGUAGE'] = 'This is my PHP session var --->'.$_SESSION['SESS_LANGUAGE'];
print json_encode(array('message' => $_SESSION['SESS_LANGUAGE']));
die();
?>
EDIT 1:
Once you run the code, simply select any of the other options from the dropdown menu and you will receive an alert that gives you the value of the php session variable along with the custom text that I added to it.
EDIT 2:
If you want to run my solution on your end, make sure you point to core jQuery js file correctly. My jquery code points to src="js/jquery_1.7.1_min.js". Make sure you update this.
Javascript does not have access to PHP-variables. The client (web browser/javascript) only has access to the Cookie or Cookieless ID (Querystring) associated with the session.
Sessions are used this way for the purpose of not letting the client modify settings associated with the session without going through the server. The less "secure" way is to use cookies for all settings. Something like language-setting might be a good idea to store in a cookie rather than the session.
In order to solve this, you could make a page which takes a session property name (like your "SESS_LANGUAGE") and a value which puts it in the session using php. I strongly advise against this because any user could then set any session variable.
The best way I can imagine is that you send an AJAX-call to a page saying that you want to change the language.
The called URL would be something like this:
changelanguage.php?lang=en_US
And the php-code for changelaguange.php:
$_SESSION['SESS_LANGUAGE'] = $_GET['lang'];

Categories