parse ajax response text - php

I want to update the web page based on ajax response received from a php script.
code inside php page :
// based on the logic either of the following three will be returned using ajax repsonse.
echo "<div align='center>Yahoo</div>";
echo "<div align='center>Rediff</div>";
echo "<div align='center>Google</div>";
The page which calls the ajax and receive the repsonse needs to perform some actions based on the returned response text.
Like , when the reponse includes "Yahoo" i need to execute some javascript functions....
when the reponse includes "Rediff" i need to perform some other javascript functions....
Currently i am using the javascript .indexOf function to search for "Yahoo" or "Rediff" in the ajax response and based on the return status of .indexOf() i am calling the functions i wish to execute.....
I feel i am not doing it in the right way ..... so thats why this question !!!
Can JSON be used in this case ??? [ just a tech thought :-) ]

i use json quite a lot for ajax apps, you could simply have a response such as
{
"response":"rediff",
}
then eval that, and get the .response value. works perfectly for me
the response from the php script would be the same as above, then (the way i interpret json) use
var resp = eval("("+req.responseText+")");
resp = resp.response;
resp will now return "rediff"

Related

Respond with JSON using AJAX and XMLHttpResponse

I wasn't 100% how to phrase this question. I have a request to a URL similar to
example.php?miscData=JSON_FILE_NAME
Now JSON_FILE_NAME contains data unique to that file. I've got example.php set-up similar to below
xmlHttpReq.open('GET', strURL, true);
xmlHttpReq.onload = function(e) {
var data = JSON.parse(this.response);
}
xmlHttpReq.send();
The request file has a function to handle the success of the call and is set up as below
function(retData, textStatus, xhr) { }
I expected retData would contain the JSON data {"name":"Dominic"} etc... But it doesn't. what am I doing wrong?
Your server side code from http://pastebin.com/c7h8V9JK is responding with an HTML page, not a JSON response. The code outside of your PHP is nothing but HTML. So naturally, when requesting the page, the server will return the HTML you've put outside of that php script.
Keep in mind, an AJAX request at its most basic is nothing special in terms of sending and receiving data from the server. Imagine that you have another tab open in your favorite tabbed browser, and that tab is navigating to the URL that your AJAX request is navigating to. That's what's going on when you make an AJAX request.
If you're trying to get JSON data from example.php, begin by removing all of the HTML from that file and serialize the data that you're trying to get using a JSON serializer.
encode json using php?

HTTP POST/GET request to PHP script and JSON response

I have pages that send POST/GET requests to PHP scripts on the server. All PHP scripts respond in JSON. Question is how to capture the JSON response at the client-side in JavaScript.
Example : when i submit the form register.html, i want to capture and manipulate (using Javascript) the JSON response returned from http://localhost/register.php.
You have to make an AJAX request. You can do this quite simply by using a library such as jquery. Or a little more difficultly just using javascript.
Using AJAX will change the current flow of your application though.
This follow example is using jquery
<form onSubmit="makeRequest(); return false;"></form>
function makeRequest() {
$.post('register.php', formDataHereAsAnObject, function(response) {
console.log(response) // this response is your json
});
}
i could recommend http://www.json.org/js.html for a detailed description of using JSON.
The moment you submit a form in the classic sense, you're out of luck. What you want is to load the JSON response from the server. To achieve this, there are a few possibilities
Set the target of your form to an invisible iframe and do submit it, then take the JSON out of there via JS (old school)
Start an AJAX request (via a framework or directly), that ends up having your data in a JS variable

call a php function from jquery

I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

JQuery .GET call/function

Ok so trying to get a page together that needs to connect to our SQL database. So on the javascript page I have functions that will autocomplete a textbox with data out of our mysql DB and then I need to send it to other functions and classes so that it will then look in our SQL DB and return some data. The problem I have is trying to get the .GET call to call in the php page, with the function that calls the class in which I need to get into for the SQL call. I have it setup somewhat but trying to figure out how to send the data through with it as well as just get clarification on how to work the .GET function.
Javascript page:
$.get("dsl_validate.php", calldsl(job));
Php Page
function calldsl($job){
var $dsljob = $job
hasfunctioncode($dsljob);
}
The hasfunctioncode function is in my DSL class page that will return the info I need. Any help on if I am in the right direction or not?
It looks like you're trying to physically call the PHP function calldsl() from the JavaScript. This... isn't right. (I'm assuming the $.get() you're using is from jQuery, please correct me if that assumption is incorrect.)
What $.get() does is simply call a resource on the web server. It doesn't have any knowledge of the server-side code (nor should it, for a number of reasons). From the perspective of the server-side code, there's no difference between a page being called via $.get() vs. one that's just loaded in a web browser.
What you essentially need to do is create a PHP page which accepts arguments either as a form post or query string (if you're using $.get() then the query string is the way to go), does its server-side logic, and then simply outputs the results to the "page." In the case of calling the page via AJAX as you are here, it's a good idea to render the page content using JSON notation. (Don't forget to set the content-type header to "application/json" as well.)
Then what you're getting on the client-side from the $.get() call is the response body, which would be that JSON data. It's really just a "page" like any other, the only difference is the content-type telling the browser that it's JSON data and that it doesn't have HTML, just JavaScript objects. The success callback on the $.get() call (the function you pass it, or create in-line) would receive that response data as an argument and can do what you need to with it.
The way I understand jQuery.get(), the second argument is the "callback" (http://api.jquery.com/jQuery.get/). The callback will hand the results from your server therefore should be a function. Currently your code actually executes the function "calldsl" where you should be only passing a reference like so...
Javascript:
$.get("dsl_validate.php", function(response){
alert("yay I haz ajax! "+response)
});
PHP: "dsl_validate.php"
echo "this is some data from the server";
No, your are not in the right direction. The first parameter of the get method have to br the complete URL of the page, not just the script (this works if the script resides on the same directory of the javascript file, though). The .php file shall return somehting "usable" for you javascript (JSON, or HTML, or text, or... whatever). The "calldsl" function will be called AFTER the data has been returned from the call. Something like that:
$.get('dsl_validate.php?value=somevalue', function(data) {
alert("Data returned from dsl_Validate: " + data)
});
i think you are better off passing the function as a param to your php page
$.get("dsl_validate.php?calldsl="+job, function(data) {
$response = $(data);// create a jquery object from the response
});
`
and in your php file
create a switch statement that call the function based on the parameter
Mmm I think you are wrong, the second argument on your get function is the javascript function that will process de data returned by "dsl_validate.php". I mean, if that page returns "foo", job will contain "foo".
But in my experience is better to use the autocomplete plugin from Jquery UI
jquery autocomplete plugin

Retrieving PHP variables from an AJAX form input

I have a form in a PHP sending variables to a PHP file which duly inserts them into a MySQL table.
I currently have a div displaying the response from the PHP (which is anything that is printed by the PHP).
All works fine. The problem is I want to use variables that are created/updated during the PHP MySQL insert process. I.e. not only show what is printed in that PHP file, but USE those variables.
I have seen complicated use of the JSON Encoding to possibly cross this divide, but I'd love to know if that's the simplest approach. And if anyone has any good links or examples on the subject.
I assume that you want to be able to have multiple pieces of data sent back via AJAX to your page and manipulate those.
JSON is indeed the simplest way to do this. If you use PHP5, you can use json_encode() from the PHP side to send a complicated data type (such as an object or an array) back to the browser page. Then in the javascript, you use eval() on the data that is sent back (ex: var data = eval(response);) to parse it back into a usable complicated type in javascript.
There are tons of tutorials out there that will show you how to do this and explain it in further detail than a response here ever could.
Use PrototypeJS and do it like this:
Have some PHP like this
$jsonHeader = array();
if($_REQUEST['param1'])
{
echo '<p>You passed ' . $_REQUEST['param1'] . '</p>';
$jsonHeader['status'] = 'Success';
}else
{
$jsonHeader['status'] = 'Failed because the request was invalid';
}
if(is_array($jsonHeader) and sizeof($jsonHeader) > 0)
{
header('X-JSON: (' . json_encode($jsonHeader) . ')');
}
Then make your Ajax call like this
new Ajax.Request('dostuff.php', {
method: 'get',
parameters: {'param1': 'this is param 1'},
onSuccess: function(response, jsonHeader){
if(jsonHeader['status'] == 'Success'){
//Everything is OK, do stuff
}else{
alert(jsonHeader['status']);
}
},
onFailure: function(){
alert('Fail!');
}
});
Prototype grabs the X-JSON header returned by PHP and automatically sets the jsonHeader argument of the onSuccess function to a Javascript array of the values that were originally set in PHP.
The above scenario is good as long as the amount of data you're returning to Javascript fits in the HTTP header.
If you need to pass back lots of data, just have PHP output the JSON encoded result rather than making it part of the header. Then you can use the evalJSON() method of the response object in your Ajax call.
You do not have to just show what's 'printed in that PHP file', your PHP file could print JavaScript commends back to your page. You could then, upon receiving the response, execute those commands. I like to use the eval function for this, but many people here will discourage you from doing so :)
Just use the "echo" function to put put PHP variables to the standard output put.
echo $myVarName;
Or, I prefer the printf(), be sure to check for HTML in the input BEFORE you output to avoid XSS issues.
Use something like this:
printf("Your input was: %s", strip_tags(%myInputVar));
Also, remember to use the %d or %f formatters when outputting number for best security.

Categories