How to pass multiple variables from AJAX to PHP? - javascript

I have AJAX code here that pass multiple values to PHP. But the problem is that the PHP can't get the value pass by AJAX and nothing is added on the database. However in my submit button I have an onclick event that calls addAnnouncement() and I think it is working because I put an alert in my ajax code and everytime I click that button it says OK.
So I think the part of the problem is in the passing of the variables.
What do you think is the problem in my code?
AJAX CODE:
function addAnnouncement()
{
var subject = document.getElementById("subject").value;
var name = document.getElementById("name").value;
var announcement = document.getElementById("announcement").value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
if(xmlhttp.status==200){
alert("OK");
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
var variables = "subject=SAMPLE&name=HARVEY&announcement=HELLO";
xmlhttp.open("POST", "addAnnouncement.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(variables);
return false;
}
This is the PHP code that gets the values pass by AJAX.
PHP CODE:
<?php
require_once("config.php");
$subject = $_POST['subject'];
$name = $_POST['name'];
$text = $_POST['announcement'];
$dateTimeNow = date("Y-m-d H:i:s");
$query = "INSERT INTO table_announcement(subject, name, text, dateTimePosted)".
"VALUES('$subject', '$name' , '$text', '$dateTimeNow')";
$data = mysql_query($query)or die(mysql_error());
if($data){
echo "ADDED!";
}
else{
echo "ERROR!";
}
?>

Just return false when exiting from the event handler to prevent the default behaviour of the submit button (i.e. submit the form):
function addAnnouncement() {
// …
return false;
}
Also check the status of your XMLHttpRequest when it reaches readyState 4 (it might be something different then 200) and properly encode query string parameters with encodeURIComponent. Last, but not least, your code is open to SQL injection. Fix that by using prepared statements (available in MySQLi and PDO. If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial).

Related

Is it possible to call PHP-Script from JavaScript section of JSP page..?

I have written following script on server-
<?php
//Create an array
$json_response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$status = "In Progress";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$con)
{
die('Could not connect to database: ' . mysql_error());
}
//Query to select pending queries database
$result = mysqli_query($con, "SELECT * FROM tbl_query_master WHERE status='".$status."' ORDER BY query_date DESC");
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row_array['query_id'] = $row['query_id'];
$row_array['sender_mobile_no'] = $row['sender_mobile_no'];
$row_array['sender_name'] = $row['sender_name'];
$row_array['query_string'] = $row['query_string'];
$row_array['action_taken'] = $row['action_taken'];
$row_array['status'] = $row['status'];
$row_array['query_date'] = $row['query_date'];
$row_array['action_date'] = $row['action_date'];
$row_array['view_status'] = $row['view_status'];
$row_array['read_status'] = $row['read_status'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
Above script returns one JSON object which is useful for me in JavaScript section of my JSP page, but I don't know how to call php-script from the java script section, so need your guidance for the same. Hope you understand what I'm saying Thank you..!
Suppose your php script is deployed to a web server (apache with php mod) and is triggered by some URL, e.g. http://localhost/script.php
Then in your javascript you can do POSt request using jquery:
$.getJSON('http://localhost/script.php', function(json) {
// do what you need with your json data
});
Finally I solved it using AJAX as follows, I don't know whether performance wise this method is correct or not, but perfectly worked for me. Write the following code in your JavaScript section.
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function getDataChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether server response came back with no errors.
{
//THE RESPONSE FROM SERVER. DO YOUR STUFF WITH xmlHttp.responseText
alert("Responce= "+xmlHttp.responseText);
//document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function getData()
{
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "http://yourdomain.com/your_script.php"; // URL of server-side resource.
// Using following way you can send parameter to your script.
//url += "?param1=" + param1 + "&param2=" + param2;
xmlHttp.onreadystatechange =getDataChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
And finally create event to call "getData()" function. That's it. Thank you..!

Autocomplete with Ajax XML

I want to make a autocomplete to my input field.
All the data is fetched from my database and handled with my autocomplete.php file - its works fine and is storing all the matching columns in a XML file which is sent back to the server.
Onkeyup i GET send with q= "the typed string" to the autocomplete.
Im having trouble handling the XML file when its received from the server. My plan is to append all the matching results to my datalist, which will work as a autocomplete?
Here is my code:
<input id="showCustomerId" name="customer" type="text" min="1" max="100" list="customerlist" required>
<datalist id="customerlist"></datalist>
script:
$("#showCustomerId").on('keyup', function(){
var str = document.getElementById('showCustomerId').value;
var xmlhttp;
if (str.length===0) {
document.getElementById("customerlist").innerHTML="";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var docroot= xmlhttp.responseXML.documentElement;
var customers = docroot.getElementsByTagName('customer');
for(var i=0; i<customers.length; i=i++){
var option = customers[i].firstChild.nodeValue;
$("#customerlist").append("<option value=\"" +option+ "\">");
}
}
}
xmlhttp.open("GET","ini/search-customers.php?q="+str,true);
xmlhttp.send();
});
autocomplete.php
$q=$_GET['q'];
$result = // do query;
$xml = new SimpleXMLElement('<xml/>');
while($row = mysqli_fetch_assoc($result)){
$xml->addChild("customer",$row['customer_id']);
}
header('Content-type:text/xml');
print($xml->asXML());
Right now my problem is not getting the value, when i alert the result in xml handler function i get the right values, but when i do the code like i have here, my website freezes!
I got the values, but i just cant append them to my datalist the right way?
I guess Easiest way to build autocomplete is by jQuery Autocomplete or Twitter Typehead. So simple jquery is better suited for this situation. Add jQuery Latest version in head
Code is not tested.
$(document).ready(function(){
//Assuming #customerlist is the ID of the text box which you need to see autocomplete
//No need to get value also - by default
$("#customerlist").autoComplete({source:"ini/search-customers.php"});
// Same time autocomplete send term as default GET variable
});
At serverside - search-customers.php
$q=$_GET['term'];
$result = // do query;
$json = new Array();
while($row = mysqli_fetch_assoc($result)){
$json[] = $row['customer_id'];
}
header('Content-type:application/json');
echo json_encode($json);

Clear a variable after proccesing in AJAX

I'm sending a variable from a form using AJAX and this variable is proccess and sends to a PHP file that makes a MySQL query. The value of the input text is setting when I click in a row of one table. When I click the button to send the variable it returns the result of the mysql query. Well, if I click one more time in the button when the value of the input is other the query isn't modify, it returns me the first query. I need to refresh that query and I think that it's possible if I clear the variable.
I put here the code of all. Thanks.
HTML Code
<td><input type="hidden" id="prueba" name="prueba"/></td>
<script type="text/javascript">
var valor=document.getElementById("prueba").value;
</script>
<td><input type="button" name="ver" onclick="load(valor)" value="Ver linea seleccionada"/></td>
AJAX code
function load(str)
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mus").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","mostralle.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+str);
}
PHP Code (mostralle.php)
include"conexion.php";
$q=$_POST['q'];
mysql_connect($servidor, $usuario, $clave)or die (mysql_errno().mysql_error());
mysql_select_db($basedatos)or die (mysql_errno().mysql_error());
$result=mysql_query("SELECT Serie, Numeroas, Numlinea, Codart, Cant, Descripcion, Precio, Tipoiva, Subtotal FROM PRESUP_D WHERE Serie='$q' OR Numeroas='$q'");
while($row=mysql_fetch_row($result)){
echo "<tr>";
for($i=0;$i<mysql_num_fields($result);$i++){
echo "<td>$row[$i]</td>";
}
echo "</tr>";
}
mysql_close();

Progress bar AJAX and PHP

I want to create a progress bar for a server-side task ( written in php )
For learning purposes the example and task would be very simplistic.
I would have a text field on the client page, read a number, pass it to the php script with ajax and make it calculate the sum of all numbers from 0 to number ( simplistic task that would take some time for big numbers, just to simulate some server-side work)
in the .html file I would create a timer that would call a function every n seconds getting the index that my for loop got to and update a progress bar.
My question is :
Is it possible to have in the same php file two functions , and how can I call a specific function with ajax : one that would block looping to number and another one I would call to get the current index the for-loop got to.
The code I have so far :
<!DOCTYPE html>
<html>
<head>
<script>
function myTimer()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("percentageDiv").innerHTML=xmlhttp.response;
alert(xmlhttp.response);
}
}
xmlhttp.open("GET","getter.php",true);
xmlhttp.send();
}
function loop(){
var loop_index = document.getElementById("loop_nr").value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("sumDiv").innerHTML="Total sum = " + xmlhttp.response;
clearInterval(myVar);
}
}
xmlhttp.open("GET","server_side.php?nr="+loop_index,true);
xmlhttp.send();
var myVar=setInterval(function(){myTimer()},1000);
}
</script>
</head>
<body>
<div id="percentageDiv"> Percentage div</div>
<div id="sumDiv"></div>
<input type="text" id="loop_nr">
<input type="submit" onclick="loop()">
</body>
</html>
server_side.php
<?php
session_start();
$index=$_GET["nr"];
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $index; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
?>
getter.php
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
Thank You!
Not only one question in here
Your question would be two:
How can I do AJAX calls to specific functions in PHP?
How can I do a progress bar with AJAX?
How can I do AJAX calls to specific functions in PHP?
Your AJAX code is fine. The only thing you have to do in your PHP is receive this call.
Look at your request. You send a variable nr with your request:
server_side.php?nr="+loop_index
That will help us in the php code to determine that this is an AJAX call to do the sum operation. Now in the PHP:
<?php session_start();
//We look at the GET php variable to see if the "nr" is coming
if(isset($_GET['nr'])) {
//Its coming!. Now we procede to call our function to sum
sum($_GET['nr']);
}
function sum($nr) {
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $nr; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
}
Thats it.
How can I do a progress bar with AJAX?
We need to make other AJAX call to request the progress to PHP.
First, we do another AJAX call to retrieve the progress with a timer!
var timer;
//try to delete duplications. Do a generic function that does the request to php
function makeRequest(toPHP, callback) {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callback(xmlhttp.response);
}
}
xmlhttp.open("GET",toPHP,true);
xmlhttp.send();
}
function loop() {
var loop_index = document.getElementById("loop_nr").value;
makeRequest("server_side.php?nr="+loop_index, function(response) {
document.getElementById("sumDiv").innerHTML="Total sum = " + response;
clearInterval(timer);
});
timer=setInterval(makeRequest("getter.php", function(response) {
document.getElementById("percentageDiv").innerHTML=response;
}),1000);
}
Then in the php side we retrieve this call as we did before and echo the $_SESSION['progress'] (as you already have)
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
And that's it!
Edit: Sessions must not be saved to a file (default PHP behaviour) because if you do that the "progress" AJAX will be blocked. You should store your sessions in a key-value database such as Redis to achieve parallelism and horizontal scalability.
Here is the solution to made progress bar in PHP without javascript only on server side:
echo "<div style=\"float:left;\">Start... </div>";
for ($i = 0; $i<20; $i++){
echo '<div style="float:left;background-color:red;height:20px;width:'.$i.'px"></div>';
ob_flush();
flush();
usleep(100000);
}
echo "<div style=\"float:left\"> Done!</div>.";
ob_end_flush();exit;

Ajax POST request not working in Internet Explorer

I'm building a PHP script that sends an email to people on their birthdays. I also need a small web interface where I can turn the entire program on or off, watch who is celebrating his birthday today and see if any mails could not be send. The php on the server is working, but I'm struggling with the html and javascript interface. Specifically the Ajax request that gets the information from the server. it works fine in firefox, chrome and opera, but in Internet Explorer 8 I don't get a response from the server. The readyState switches to 4, but the status remains 0 and the responseText is empty.
After googling I found out that a lot of people advice JQuery, but I couldn't get that to work in any browser. I want to find out more about it, because it seemed pretty easy, but for now I would like to know how to do this without JQuery.
edit
In response to questions from the comments, switching the if and else statements yields the same results. As does changing the connection from 'open' to 'close', incidentally, it is supposed to be close, I can't remember why I changed it, probably just trying something out of frustration. Finally I added the server side php code. The server sends back string data in case 'action' is switchonoff or, just a header with no text if action is clearlog and a jsonarray if action is initialize. Whatever the request the server's HTTP status is always 0.
<script type="text/javascript">
function loadXMLDoc(action) {
var parameters = "action="+encodeURI(action);
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",'http://mailer.test/App/postscript.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "open");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
if(action == 'switchonoff'){
document.getElementById("onoffbutton").innerHTML=xmlhttp.responseText;
} else if(action == 'initialize'){
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("onoffbutton").innerHTML=response['onoff'];
document.getElementById("birthdays").innerHTML=response['birthdays'];
document.getElementById("errors").innerHTML=response['errors'];
} else if(action == 'clearlog'){
document.getElementById("errors").innerHTML="";
}
}
}
}
window.onload = function() {
loadXMLDoc('initialize');
}
</script>
edit, here's the php script
<?php
include "settingschanger.php";
include "customercsv.php";
if (!isset($_POST['action'])) {
$_POST['action'] = 'dummy';
}
$post = $_POST['action'];
if(strcmp($post, "initialize") == 0) {
$settings = new SettingsChanger();
$onoff = $settings->getOnOff();
$csv = new CustomerCSV();
$csv->openFile((__DIR__).CustomerCSV::FILENAME);
$todaysbirthdays = $csv->getTodaysBirthdays();
$birthdays = "";
foreach ($todaysbirthdays as $row) {
$birthday = "";
foreach ($row as $data) {
$birthday .= $data . " ";
}
$birthdays .= $birthday . "<br />";
}
$errorLogArray = $settings->getErrorLog();
$errors = "";
foreach($errorLogArray as $line) {
$errors .= $line . "<br />";
}
$result = json_encode(array('onoff'=>$onoff, 'birthdays'=>$birthdays, 'errors'=>$errors));
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "switchonoff") == 0) {
$settings = new SettingsChanger();
$result = $settings->changeOnOff();
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "clearlog") == 0) {
$settings = new SettingsChanger();
$settings->clearLog();
header("HTTP/1.1 200 OK");
}
?>
Try with xmlhttp.send(parameters); after xmlhttp.onreadystatechange statement.
I had some issues with the returned content being empty in older versions of IE ( less than v9), but the success-function was triggered.
Then I found out that I was using HTML5 tags, and in IE, for some odd reason, HTML5 output via an AJAX-request doesn't work and returns an empty or no DOM.
Look at the last edit in "jquery .load() not inserting data in ie8 and below".
Well, I got the site to work. Instead of a post request I now use a get request and that seems to work. It's not perfect and I'll continue looking for a way to do it with a post request, but for now it'll work.

Categories