$_GET JavaScript and AJAX... - javascript

I am relatively new to PHP and I am (trying to) developing my first AJAX code...
I am trying to pass an attribute from a select with several options, each option with its very own unique attribute "values" that is a String.
The PHP file GETs the value and does something with it (for instance prints it out). And the generated file is then returned to my main HTML page.
Here is the source code...
Here is my javaScript:
function showUser(myElement) {
var str = myElement.options[myElement.selectedIndex].getAttribute("values");
if (str == "") {
document.getElementById("myResponse").innerHTML = "";
return;
} else {
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("myResponse").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
}
My HTML is as following:
<form>
<select name="users" onchange="showUser(this)">
<option values="">Select a person:</option>
<option values="Rasmus Lerdorf">Creator of PHP</option>
<option values="Linus Torvalds">Developed Linux</option>
<option values="Dennis Ritchie">Developper of C</option>
</select>
</form>
<br>
<div id="myResponse"><b>Person info will be listed here...</b></div>
My PHP is:
<?php
$q = intval($_GET['q']);
echo $q;
?>
I get 0 instead of the text string, what is wrong with my code?

Silly me,
I copied and pasted a basic example from a tutorial and I did not realize that the PHP code was casting the string that was sent over the GET to an integer.
$q = intval($_GET['q']);
The code should be :
$q = $_GET['q'];
On my earlier stage of the development I was indeed passing an integer, so the code was working.
The code returned 0 instead of an error because the intval of a string is 0 on failure.
Writing down the question here I realized the mistake...

Related

Retrieve multiple values using ajax and php, without Jquery

Website coding surely is awesome and I recently rialized that JavaScript and Ajax are really essential elements in order to build a outstanting website. I've done the research on internet, but the results weren't that useful. Every code included Jquery, which I don't comprehend. Also JSON is slightly unclear regarding the objects, etc.
W3schools published a few examples on how to generate an Ajax code that reacts with a PHP file. This data is retrieved through 'resonseText'. However this element only retrieves one unselected PHP string.
Is there a method to select specific variables or values from the PHP file and accordingly send it back to the Javascript (Ajax) file, so I can subsequently utilize them for further Javascript coding.
Thank you in advance. (It would greatly help, since Ajax is such a complex form of JavaScript.)
My Ajax code, to send data to the PHP file
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 (this.readyState == 4 && this.status == 200) {
var XMLResponse = this.responseText ;
document.getElementById("nameInputNote").innerHTML = "Status: " + XMLResponse ;
}
} ;
xmlhttp.open("GET","ajaxIndex.php?rq1="+valueNameInput,true) ;
xmlhttp.send() ;
The PHP code:
<?php
$rq1 = $_GET['rq1'] ;
if (empty($rq1) ) {
} else {
$sql1 = "SELECT userName FROM users WHERE userName = '{$rq1}' " ;
if ($result1 = mysqli_query($connection, $sql1) ) {
$resultsSql1 = mysqli_num_rows($result1) ;
if ($resultsSql1 == 0) {
echo "vacant" ; //select this value with JS
$permission = "true" ; //and select this value separately with JS
} else {
echo "occupied" ; // or in this senario: select this value
$permission = "false" ; // and this value
// In this case the $permission variable is needed to determine whether a form should be submitted or not.
}
}
}
Try with
let src = <?php echo json_encode($yourVar); ?>;
And then use that variable. Other ways you can do that is to use axios, cookie or VueJS and pass data into component. Hope that helps.

xmlhttp.open does not seem to do anything in MVC structure

I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} else {
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("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.

Wordpress and Ajax

I've have created a custom table in mysql. I've entered a bit of test data just to see if I can pull some results. The query was successful when I ran it just in the template, so I know it works. As I have tried to convert it into a Ajax request seems that no data is being passed. I'm not sure what it is I am missing, or possibly an error I have entered somewhere, but it seems when I try to turn it into an Ajax request nothing happens.
Any ideas?
PHP
$q = intval($_GET['q']);
$pull = $wpdb->get_results(
"
SELECT ID, department, contact, forms
FROM referrals
WHERE ID = '$q'
"
);
foreach ( $pull as $requestdata)
{
echo $requestdata->department;
echo '<br />';
echo $requestdata->contact;
echo '<br />';
echo $requestdata->forms;
}
AJAX
<script>
function displayData(str) {
if (str=="") {
document.getElementById("txt").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo content_url(); ?>/themes/child/get-referral.php?q="+str, true);
xmlhttp.send();
}
</script>
HTML
<select name="users" onchange="displayData(this.value)">
<option value="">Select a person:</option>
<option value="1">Test 1</option>
<option value="2"Test 2</option>
</select>
<br>
<div id="txt"></div>
You need to change your ajax request to wp-admin/admin.ajax.php.
If you open that file you will find there is a constant setting named DOING_AJAX. Only the requests to this link can avoid the normal header being sent to browser because of setting DOING_AJAX to ture.
Actually you can debug like this: visit <?php echo content_url(); ?>/themes/child/get-referral.php?q=xx, you will find there are other info sent. thats why that ajax doesnt work.
Switched to this. Hopefully it helps someone else out.
HTML
<select id="mySelect" onchange="pullData()">
<option value="">Select</option>
<option value="options">options</option>
<option value="someother1">someother1</option>
<option value="someother_2">someother_2</option>
</select>
<div id="referral">Test</div>
AJAX / JS
<script>
function pullData() {
var xhttp;
//url variables
var url = "/wp-content/referrals/";
var selectedValueIs = document.getElementById("mySelect").value;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("referral").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url+selectedValueIs+'.txt' , true);
xhttp.send();
}
</script>

How to use json and ajax to create a javascript array from a PHP array?

Trying the create a javaScript array from a PHP array of urls to images using JSON and AJAX. Then I want to display the images on a cordova app. I believe my issue is I'm either I'm receiving or sending the Json messages with automatic html tags. My xmlhttp.response is equal the array of urls but it has html tags which are not present in the PHP file. I think because of these tags my JSON.parse isn't working?
This is my PHP stored on a server. I'm returning the urls in json message.
<?php
include("mysqlconnect.php");
$select_query = "SELECT `ImagesPath` FROM `offerstbl` ORDER by `ImagesId` DESC";
$sql = mysql_query($select_query) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
$data[] = $row['ImagesPath'];
}
echo json_encode($data);
?>
This is my script in my cordova app. I want to covent the JSON message into a javaScript array and display the first image in the array in the div contents. But I think I'm calling a message which includes html tags so I can't parse the message I could be wrong. I currently get three error alerts because the ready state is not correct.
<html>
<script>
var arr = [];
function importJson(str) {
if (str=="") {
document.getElementById("content").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){
alert(xmlhttp.response);
arr = JSON.parse(xmlhttp.response);
//var arr = (array)json.parse(xmlhttp.response);
for (var i = 0; i < arr.length; i++) {
buildImage(arr[i]);
alert(arr[0]);
}
} else {
alert("Error");
}
}
xmlhttp.open("GET","http://server/~name/folder/content.php);
xmlhttp.responseType = "json";
xmlhttp.send();
buildImage=function(src) {
var img = document.createElement('img');
img.src = src;
document.getElementById("content").appendChild(img);
}
}
window.onload = importJson();
</script>
<body>
<div id="content"></div>
At present, your PHP script is outputting a web page, but the javascript is looking for JSON. To output JSON, you need to set the headers in the php script:
header('Content-Type: application/json');
echo json_encode($data);

Javascript AJAX responseText problem in IE

I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:
(AJAX)
function getMessages(messengerid, repeat)
{
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("messages").innerHTML=xmlhttp.responseText;
document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
}
}
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
(PHP/MySql)
<?php
$key = "abcIUETH85i236t246jerst3487Jh";
if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {
include_once("../config.php");
include_once("../class/system.class.php");
$sys = new system($template_name);
if(!$sys->connect($db)) {
exit();
}
$messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
$messenger = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");
$user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
$user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");
$displaynames[$user1[0]['id']] = $user1[0]['displayname'];
$displaynames[$user2[0]['id']] = $user2[0]['displayname'];
foreach($messages AS $key => $message) {
if(is_numeric($key)) {
?>
<div class="message">
<b><?=$displaynames[$message['account_id']];?> (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
<?=nl2br($message['message_content']);?>
</div>
<?php
}
}
}
?>
Any help would be much appreciated!
Thanks in advance.
Best Regards,
Skyfe.
Your response is being cached. One way to fix this is to append a unique parameter in your request URL, such as the current timestamp.
Its a common problem with IE it caches the result.Add some dummy random parameter to your ajax call e.g current timestamp
i dont know about php but in jsp you can add the following code to your jsp page
response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
i know the post is old , i just replied for future viewers :D ;)

Categories

Resources