Pass JSON AJAX reply to PHP - php

I have a script which uses AJAX to connect to a PHP script which queries a database and returns some values. The code of which is below:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxphp.php?ID="+str,true);
xmlhttp.send();
}
</script>
<select id="users" name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<!-- PHP populates this dropdown box -->
</select>
<div id="txtHint"><b>Selected user info will be listed here.</b></div>
Right now the txtHint div will return anything the ajaxphp.php script prints. This isn't very flexible, however. What I want to do is create an array in ajaxphp.php and use json_encode() to pass the results back.
The problem I'm having is I don't know how to get the original script to grab the results so I can do useful things with them. Right now I can make it return a JSON array which will appear in the txtHint div but I've no idea how to get PHP to actually read that information so I can do something with it.

Try using jQuery Ajax...
$.ajax({
url : 'ajaxphp.php?ID='+str,
type: 'get',
dataType:'json',
success : function(data) {
console.log(data);
}
});
Data in success function parameter is your encoded result that you return from php.
echo json_encode($result);
Then you can access it with something like this from javascript.
data.result1
data.result2
data.result3....

Use $_GET method to See what ever the user send you in php see here:
http://php.net/manual/en/reserved.variables.request.php

Maybe the json_decode() php method is the solution of what you want.
http://www.php.net/manual/en/function.json-decode.php
This method takes a JSON encoded string (from the json_encode method for example) and converts it into a PHP variable... so you can use this variable like an object and simply access to its attributes.
Maybe this other post will help you : How to decode a JSON String with several objects in PHP?
Hope this helps ! Bye !

Related

AJAX no data in responsetext

Right up front...I am very new to using Ajax.
I'm working on a web site where I want the results of one Select object to determine the options in the second Select object(from a database query). I'm using PHP and it appears that the only way to do this is to use Ajax. I've written a short html page to test my Ajax knowledge and it seems to work just find on Firefox but not on Chrome or IE. I've done a lot of research and found all sorts of folks with similar problems but no real solution.
I'm making the XMLHTTPRequest call to a local file in the same folder even so I should not be experiencing any cross-domain problems. Any help would be greatly appreciated.
Here's my Javascript function that gets called when the Select box is changed:
...
function getData(str)
{
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("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
alert(xmlhttp.responseText);
}
********ajax_info.php
+++++++++++++++++++++
//this is the php file that runs in response to the xmlhttprequest. It just generates a string of number at this time.
<?php
$str = "";
$i = 0;
for($i; $i<1000; $i++)
{
$str = $str.$i."-";
}
echo $str;
?>
You need to attach an event handler to your xmlhttp object to catch the onreadystatechange event. Note that when you alert your value, the asynchronous ajax call has just fired and has not finished yet (you are not checking for that anyway):
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","ajax_info.php?color=",true);
xmlhttp.setRequestHeader("Content-Type", "text/xml");
xmlhttp.send();
Well in that case you should try jQuery. It will be lot easier for you to make ajax request.
Here is an example for your problem
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// FOR GET REQUEST
$.get("ajax_info.php",{color:'value'},function(data) {
alert(data); // RETRIEVE THE RESULT
});
</script>

XML Request not working properly

I have an XML request in my javascript file that is not transferring my variable correctly to PHP and I cannot figure out why. Could I possibly be missing a reference library of some sort?
Here is the function in question. I do know that the str variable has what I want inside. I am leaving old trial code in comments just in case you want to see what I have tried.
function PHP_Con(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
if(!xmlhttp)
{
alert("Fehler");
}
else
{
/*$.ajax({
type:"POST",
url:"dbConnection.php",
data:{"test" : "str"},
success:function()
{
alert("success");
}
});*/
alert(str);
xmlhttp.open("GET","dbConnection.php?test="+str,true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send();
/*var json_string= JSON.stringify(str); // convert it into a json string.
$.post('dbConnection.php' , {test : json_string },function(){
alert("success");
}); */
}
}
And here is my corresponding PHP code:
$test = intval($_POST['test']);
echo $test;
Also, I know about isset but I am trying to get the variable to show up. I'd rather get an error when it is not there, if that makes since...
Thank you very much. :) If there are easier ways to do this, I would be interested in that as well.
But as of now I feel like I do need to have a Form that calls a JS function, then my JS has variables retrieved from user input, and then those variables go to PHP so that they can be checked against my database... it all seems like the right order to me, but I admit to not having a very clear view of how JS variables show up in PHP and also of how PHP can respond in a way that is reflected through HTML code... for example I would like to "echo" back to a span in a p with the results of the comparison (user input against the database contents) and I have no idea of how that is done...
You are sending a GET request so you have to use $_GET instead of $_POST
$test = intval($_GET['test']);
echo $test;
a POST request would look like
xmlhttp.open("POST","dbConnection.php",true);
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send("test="+encodeURIComponent(str));

ajax search function using POST method without jquery

I have some html pages about movies, all containing the same search form. When the user types something in the form, I want the site to jump to movies-overview page. I already made a search function without ajax, but with a simple post request that searches the database en echos a movielist. But now I want the same to happen everytime a user presses a key.
this is the search form:
<form action='films.php' method='post'>
<input id="ZoekBalkSearch" type="search" name="zoekparameter" placeholder="Geef een zoekterm in." onkeyup="gaNaarFilm(this.value)"/>
<input id="ZoekButton" type="submit" value="Zoek"/>
</form>
and this is my ajax code:
function gaNaarFilm(str)
{
if (str.length==0)
{
document.getElementById("ZoekBalkSearch").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)
{
document.getElementById("ZoekBalkSearch").innerHTML=str;
}
}
xmlhttp.open("POST",'films.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('zoekparameter='+str);
}
the function is called but it doesn't seem to do anything, could someone please help me? thanks in advance.
fist of all you pass this and not this.value
then a short function i use for ajax is this
var ajax=function(a,b,c){c=new XMLHttpRequest;c.open('GET',a);c.onload=b;c.send()}
this has low support (no ie5 and ie6) but can be extended.
then as u lauche the code directly from your element you can access your value directly inside the ajax.
so:
JS
FormData() stores the whole content of your form
the ajax() function posts to film.php
in film.php u can retrieve the value with $_POST['zoekparameter']
the response executes fu()
this is done by adding a eventListener in javascript to the input field which is keyup.
var ajax=function(){
var fd=new FormData(document.querySelector('#form'));
var c=new XMLHttpRequest||new ActiveXObject("Microsoft.XMLHTTP");
c.open('POST','film.php');
c.onload=fu;
c.send(fd)
},
fu=function(){
document.getElementById("ZoekBalkSearch").innerHTML=this.response;
}
window.onload=function(){
var i=document.querySelector('#form').childNodes[0];
i.addEventListener('keyup',ajax,false)
}
as u can see no need for extra id's, lots of code or passing each input field to a variable in this case every function can access everything without passing parameters... and so it's
easier to modify the code later...
html
<form id="form"><input type="search" name="zoekparameter" placeholder="Geef een zoekterm in."></form>
if you wanna add more fields like year or whatever you just have to add a input and a name
<input type="text" name="year">
you don't need to edit the javascript as FormData does everything for you.
if you don't understand something ask ...
if wanna check compatibility
use caniuse.com
http://caniuse.com/xhr2
http://caniuse.com/queryselector
bonus
shortest way
window.onload=function(){
var s=function(){
var a=new XMLHttpRequest;
a.open('POST','film.php');
a.onload=function(){console.log(this.response)};
a.send('zoekparameter='+i.value);
},
i=document.createElement('input');
i.type='search';
i.addEventListener('keyup',s,false);
document.body.appendChild(i);
}

jquery div not showing more them on user profile

I have been working on this code for a while and I am finally stumped and cannot figure out what the heck to do to get this issue fixed.
I have a jquery code that works beautifully for the get profile, but when i need to return the values in a div, it only shows the first profile of the user, but if a user posts more then once on the blog, it will not show the profile information. I have tried to append more information for each profile div to be different, but its still not working.
Here is the jQuery code for the GET user profile and return response.
function showUser(str)
{
var profileDiv = document.getElementById("profile_"+ str);
if (str=="")
{
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)
{
profileDiv.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
Also here is the PHP script that i am using to pass the information
"<div id=\"info\" onmouseover=\"showUser(" .$blogrow['id_user'].")\"><imgalign= \"left\" style=\"vertical-align:top;\" class=\"imgb\" height=\"41\" width=\"41\" src=\"profilepics/".$blogrow['pic']."\" />".$blogrow['author']." <br>".$blogrow['timestamp']."<br></div><br>";
echo "</div>";
here is the div part as well that stores the information
echo "<div id=\"txtHint\"><div id=\"profile_".$blogrow['id_user']."\"></div></div>";
The problem relies on your HTML markup, which is invalid. Element ids must be unique in a HTML page but I see a lot of repeated ids such as #info, #theDiv, #txtHint and #profile_X
A quick fix for your problem would be to change all those and any other repeating ids to a class and then use the ajax code provided by #Rohan Kumar but using a class selector to append the content to every mention of the user in the page
function showUser(str)
{
$.ajax({
url:'getuser.php',
data:{q:str},
type:'GET',
success:function(data){
$(".profile_"+ str).html(data);
}
});
}
This is definitely not the most efficient or elegant solution but I think it would work. If you were to try and improve your code I would suggest binding all divs of class .info to a mouseenter handler, using data-attributes to get the user id and maybe maintaining a list of the profiles retrieved so you don't end up making redundant calls to your php
Using $.ajax it will more simple like,
function showUser(str)
{
$.ajax({
url:'getuser.php',
data:{q:str},
type:'GET',
success:function(data){
$("#profile_"+ str).html(data);
}
});
}
But, before this you need to add any version of jQuery

Javascript and php

I have a page called getvalues.php, I need to call a function which is written in a different php page(fileclass.php) in a class from this page(getvalues.php), but the issue is i need to pass a variable also which is $i, and the value of $i passed should be 1 if we are selecting option B, and $i=2 if option=c, and $i=3 if option=D given in dropdown. I had simply wiritten an onchange event but had not written any code in javascript. Please help Thanks. Here is the code for getvalues.php
<html>
<select id="s" onchange="callsome();">
<option value='B' selected>B</option>
<option value='c'>c</option>
<option value='D'>D</option>
</select></html>
<?php include("fileclass.php")
$obj=new file;
echo $obj->func($i);?>
You could implement this using JQuery or Javascript (I use JQuery in the example because it is shorter and easier to make Ajax calls) :
<html>
<select id="s" onchange="callsome();">
<option value='1' selected="selected">B<option>
<option value='2'>C</option>
<option value='3'>D</option>
</select>
<script>
function callsome() {
var selected = $('select#s option:selected').val();
$.ajax({
type: "POST",
url: "fileclass.php",
data: ({selectedvalue : selected}),
success: function(data) {
alert(data);
}
});
}
</script>
</html>
After that the callsome returns the output of the fileclass.php script and you can use that however you like in your code. From your explanation it was not really clear what is happening in fileclass.php and what you want to do with it, so I hope it helps you.
If you want the function in Javascript only:
<script type="text/javascript">
function callsome() {
var e = document.getElementById("s");
var strVal = e.options[e.selectedIndex].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) {
var data = xmlhttp.responseText;
//use the data as you wish
}
}
xmlhttp.open("GET","fileclass.php?selectedvalue=strVal",true);
xmlhttp.send();
}
</script>
This isn't the way PHP and HTML work.
PHP is rendered on the server. HTML is rendered on the client, after the PHP is completely done. To do what you want to do, you need to have the HTML (possibly Javascript) make a request to the PHP page at fileclass.php.

Categories