HTTP POST/GET request to PHP script and JSON response - php

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

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?

How to send data from javascript to php

$('myBtn').on("click",function(){
var parent= $(this).parent();// will give you the Parent Object of the button, that has been clicked
});
I need to send var parent to php so it knows where to display the html data (in the correct are div/class, how would i do this.
The short answer is that "You can't".
Communication between the browser (where your JS is running) and the server (where the PHP is running) is handled via HTTP. If you want to send a JavaScript object then you have to serialise it to a string and deserialise it at the other end. There is no sane way to represent an HTMLElementNode (or a jQuery object that wraps on) in that process (not least because PHP doesn't usually represent HTML in a DOM and when it does it won't be the same DOM instance as the browser is using).
Usually in this type of situation, you would request some data from PHP (possibly using one of jQuery's ajax methods) and then use JavaScript to turn it into DOM elements and insert it into the document.
Try JSON and Ajax (XMLHttpRequest) as the "client to server" mechanism
JavaScript is evaluated on client-side, when PHP is server side. You don't have trivial way to do it.
If the html data is not already generated, you would have to make a new request to the server, preferrably by the jQuery $.get function, then pass the output (again via jQuery) to the parent element.
Please use Jquery and use $.ajax for this purpose
$.ajax({
type: "POST",
url: "yourPHPPage.php",
data: "parentvar="+parent,
//parent is a javascript variable
success: function(msg){
//Message received from server,
// if you would write some code in echo there, like echo "hello";
// you would get that in msg.
}
});
to access this variable on php, use $_POST["parentvar"];
You can also send multiple values by concatinating them with & operator.
Like data:"parentVar="+parent+"&name=atif&age=23"; etc
Please let me know if further help needed.
Further help on
http://api.jquery.com/jQuery.ajax/
As far as I know, you can't pass a DOM object directly to the server -- there's too much information stored for it to be practical. You could send the HTML of the object though.
Here's an example that sends the HTML to the server. You would process it, but we just echo it back.
http://jsfiddle.net/hLD4F/
Try clicking on any of the buttons, and it will send a request. In PHP you could access this information via $_POST['html'].

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

JSON response from PHP script being enclosed in <head></head><body> ... <body>

I am trying to debug a simple PHP/JSON/jQuery problem.
The following PHP script:
header('Content-type: text/javascript');
echo json_encode(array('type'=>'error','message'=>'arg'));
is being consumed by jQuery but when the line:
var results = jQuery.parseJSON(responseText);
is executed, the jQuery JSON parser gives the following:
uncaught exception: Invalid JSON: <head></head><body><pre>{"type":"error","message":"oops!"}</pre></body>
Obviously the head/body/pre are not supposed to be returned.
I cannot see any hidden characters nor anything out of order in my PHP code..
Any ideas?
This one has had me stumped for the last two days. I'm using the jQuery Form plugin's ajaxSubmit function to submit a form via AJAX without reloading the page. I finally stumbled across the answer after this question showed me a parameter I hadn't noticed previously: dataType.
Behind the scenes, an iframe is being created and is actually making the call back to the server. The response from the server is being pulled from the iframe, which is bringing along with it the tags.
The jQuery Form plugin handles the situation by allowing you to specify the type of response to expect from the server. If I specify 'json' as the response type, the following few lines of code are executed to get the JSON from within the tags:
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
}
(doc is a reference to the iframe's document and xhr is the XmlHttpResponse object that ultimately gets returned from the plugin's function.)
I don't know exactly how you're making your AJAX call, but I'm guessing a similar construct (perhaps using a document fragment) will allow you to extract the necessary JSON from the response.
Try not to send header('Content-type: text/javascript');
json for php find "function send_as_json($obj)"
headers types
Set the header to application/json.

How to activate PHP file in JavaScript function

I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");

Categories