how to call a web service written in php in javascript? - php

Hi I have web service that is written in php that outputs my data in xml format. I need that data to be send to an html page where I use javascript to display it. I want to know to how call that php service from my html page using javascript?

You can use JSON and PECL for data transfer with php
JSON
http://www.json.org
Scroll down to the page to see some options that you have for PHP.
If you wanted to do something fast and simple, you can use the jquery get or post call to acheive the disired result:
jQuery GET:
http://api.jquery.com/jQuery.get/
The get and the post both have a call-back function which can be used to accept the result of loading your php page and then you can determine how to display it.

You should have a way or create a way to access that by going to a specific URL. So just create some JS that will call that URL. Best to use JQuery to make things easier. Then just manipulate the data all you want.
Try that .ajax function from JQuery. There are some great examples at http://visualjquery.com/. You can also get more details on it from http://api.jquery.com/jQuery.ajax/
Example:
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
You could also use JQuery's load function:
$('#result').load('ajax/test.html');

How about something like this using jQuery's load()?
$('#result').load('http://myWebService/serviceName.php');
<div id="result"/>

Related

jQuery AJAX vs PHP in HTML attribute

If I want to do some PHP on an event(e.g. onchange) should I use jQuery ajax like:
$("#elm").on("change", function(){
//ajax code
}
, should I use the PHP in the HTML attribute like:
<element onchange="<?php //stuff to do ?>"></element>
You seem to be conflating two different issues.
JS bound events vs intrinsic event attributes.
Bind your event handlers with JS.
Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
Ajax vs Putting PHP in a JS function
If you put PHP in a JS function then it will run when the PHP outputs the JS function to the browser, not when the JS function is called.
If you want to run PHP in response to an event, then you have to make an HTTP request to the server to run the PHP.
If you want to insert content from the load of page and leave it static, you should use only PHP.
If you want to insert content dynamically (changing with users interactions) you should use AJAX.
I can't found out what are you trying to achieve with your example, so not very sure what you should do there.
taking your code it would give this :
$("#elm").on("change", function(){
//ajax code
$.get('url', {data:'tosend'}, function(data){
// here you have the response of the php script in the data object
// it can be json for exemple
});
}
You must realise two things, your php code will be render when the page is loaded in the
browser so the second code you gave us
means that your "onchange" event is already present in your page.
If you want to request something (data, html, etc) to server from a loaded page, then do an ajax.
In that case below code is correct.
$("#elm").on("change", function(){
//ajax code
}
You cannot execute a piece of php code from client side. But you can assign values from php to javascript and then do operations on client side.

Call a php script from javascript

I need to call my REST API that is written in PHP from a javascript script. A similar situation I can point to is the jquery ui autocomplete plugin. When you specify an external php script for the source attribute, it reads the output from the php script, and uses that as the autocomplete options.
you could use the jQuery ajax function:
http://api.jquery.com/jQuery.ajax/
AJAX. That is all.
If you have any more specific issues, feel free to ask.
You can use an AJAX request (if I understood the question)
If your API is written in myapi.php, you can:
var word = "The Word";
$.ajax({
url: "myapi.php?action=searchfor&word="+word,
success: function(data){
alert(data);
}
});
...assuming you're using jQuery, of course :)

How to identify the use of Ajax in jQuery?

I want to make a form that uses jQuery's ajax function to submit the data, but to be functional when javascript is disabled. So I need a way to know, in the server-side script (PHP), weather the request came from ajax or from simply submiting the form.
HTML:
<form id="form_1" method="post" action="process.php">
jQuery:
$.ajax({
type: "POST",
url: "process.php",
data: $("#form_1").serialize(),
cache: false,
success: function(msg){alert(msg)}
});
So I would like to check in process.php if it was called from jQuery or from submiting the form. Note that I serialize the data, I don't want to use an URL parameter, like '&ajax=1'. Thanks!
Automatically, requests made with XMLHTTPRequest (like those made with jQuery's AJAX suite) have the X-Requested-With header set to XMLHTTPRequest. You can check for the presence of this header.
if (
isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHTTPRequest')
) {
// request is AJAX
}
You can check for the presence of $_SERVER['HTTP_X_REQUESTED_WITH']. jQuery will send this header with AJAX calls.
The jQuery serialize() method won't serialize (and therefore provide a value for) any submit buttons contained within the form, but submitting the form using one of these will do so. You can check for the existence of that value using PHP and handle appropriately.
I know you don't want to use a url parameter, but it might be the only way you can determine where the call came from.
You can construct data manually and add an AJAX only parameter, and then check for it in PHP.
I would suggest you add a field to your form when it is submited via ajax just before the ajax call. So you can serialize your form and send it as the data containing your ajax=1 for example
The server has no guaranteed way to know what mechanism the client used to make a request. Any request that you can make via JQuery or any other kind of page load can be spoofed by another client to look exactly the same; the server would have no clue.
A client that isn't trying to spoof the result will generally send some clues to the server, in the form of the UserAgent string, and so on, but none of these clues will tell the server anything about whether it's being called via Ajax or not.
Therefore the only route you have to tell the server where the request is coming from is in the URL, and the easiest way to do that is to add an extra parameter. I know you don't want to do this, but it is the best answer to your question.
The alternative option is to have a different action URL for the form if it is called via Javascript. You can toggle the URL easily in JQuery when the page is loaded, and because it is done in Javascript, if JS is disabled then the form will post to the default URL, and you'll be able to generate you non-JS page load.
The final solution is not to do anything different on the server; render the page exactly the same whichever route the user comes in via, and instead have the JQuery code accept the that page code and extract the relevant parts of it for use in the Ajax context.
I hope that helps.
There is a much simpler way to achieve this. Use something similar for jQuery:
$("form").submit(function(){
/*ajax request*/
return false;
}
The return false; does the "magic". If you have JS enabled, then the submit button won't submit the regular way; you can process data via jQuery and send it with AJAX. If you have JS disabled, therefore this function is not called and the form is submitted as usual.

Send data to database when click on a link without page refresh

Is there a way to send data to database when click on a link without page refresh?
I use php/mysql...
I will give you an example using jQuery.
Let's say that we have a link with an attribute id="button_id" (you have to learn the jQuery selectors ).
$("#button_id").click(function(){
var var_data = 5;
$.ajax({
url: "my_script.php",
data: { var_PHP_data: var_data };
success: function(data) {
// do something;
alert(data);
},
});
});
Explanation: you will send the variable var_data with the name var_PHP_data to a my_script.php without page refresh using an ajax call (using GET method).
This is very simple example of what you have to write on your PHP script.
<?php
$var_name = $_GET['var_PHP_data'];
echo 'This is what you have send'.$var_name;
?>
Because the default method to send variables in the ajax function in jQuery is GET.
We have to use the $_GET function in PHP.
This php script will print a message and this message will be handled in the success: function in the Ajax call and just for example we will alert this message returned from PHP.
You'd have to use JavaScript. When a user clicks a link, if you don't use JavaScript, then you need to go user -> server -> user and they get a whole new page.
HTTP is stateless.
It's not possible without a page refresh but this is the classic use-case for AJAX requests. If you're not familiar with AJAX then there are various methods of doing this using all the popular JavaScript frameworks such as Prototype and jQuery
You can't send data directly to a database, but you can use AJAX to send data to a php page that will save them to the database, without reloading the page or following the link in the browser..
Have a look at http://api.jquery.com/jQuery.post/
Not using PHP because it is server side - you need JavaScript / AJAX for this.
Check out frameworks like dojo (http://www.dojotoolkit.org/) , mootools (http://mootools.net/) or jQuery ( http://jquery.com/ ).
Yes, you can use AJAX.
This is a very big topic, but I'd recommend you do some research on AJAX and jquery (javascript).
Here are some tutorials:
http://www.ajaxf1.com/tutorial/ajax-php.html
http://www.talkphp.com/vbarticles.php?do=article&articleid=58&title=simple-ajax-with-jquery
Do a search in google for more info.

Updating MySQL with textarea content without reloading

I'm building a page which loads the contents of our MySQL db for editing. Each row of the table is in a seperate, editable textarea on the page. I need the user to be able to update each row (ie send it's contents to the db) without reloading the whole page, with a click of a button that's responsible for that specific textarea.
I understand that such procedure would involve some JavaScript, but sadly I know none - I did all I could with php, so I need a pointing in that direction. Basically my question (I think) is how do I grab a text from an edited textarea and send it to MySQL without reloading the page. If I'm heading in the wrong direction I'd be more than willing to hear other suggestions.
Yes this will require javascript. Namely an async call to a PHP page you have. This is often called AJAX.
I hate to be the "use jquery" answer here but the hump of learning jQuery to use AJAX based calls is very low to the value you gain from calls like this.
The documentation has great examples and most of them are quite simple.
That's precisely what AJAX does: Asynchronous JavaScript and XML. It lets you send requests to the server without reloading the page.
I'd recommend starting with jQuery which you'll notice has a lot of support in the StackOverflow community, as well as elsewhere, and which makes cross-browser AJAX requests very easy.
With the jQuery script on your page, you can do something like this:
$("#id-of-the-button-the-user-will-click").click(function() {
$.post('/path/to/your/script.php', { field1: value1, field2: value2 }, function(data) {
// This function is called when the request is completed, so it's a good place
// to update your page accordingly.
});
});
Understanding the details will still require a thorough understanding of JavaScript, so really the best thing to do is dive in and start writing (and thus learning) a lot of JavaScript. AJAX is a fine place to start.
There is a good introduction to JavaScript at Opera. Jibbering covers the use of the XHR object, which is the usual way to send data to the server without leaving the page. Libraries such as YUI or jQuery can do some of the heavy lifting for you.
What you're looking for is AJAX. jQuery makes a lot of that easier; try starting here.
You can add JavaScript event to textarea:
onblur="sendUpdate(this.value)"
This event will happen when user has finished editing the text and leaves the input.
In example, "this" references current textarea component.
And then use Ajax, as previously mentioned. An example would be:
function sendUpdate (text) {
$.post('script.php', {textarea_value:text},function(){});
}
You need to make asynchronous calls to server from your script (javascript).Use ajax to achieve this.You need to have a look at using XMLhttp objects to communicate with the server /database from your client side script (javascript) . You need not submit the entire page using a button click,instead you can invoke the javscript code in a button click event or a onBlur event or a onTextChange event etc...
jQuery is a javascript framework library which helps you to reduce the number of lines of code to implement this. But its not necessary that you need to use jquery .You can do ajax calls without using jquery.Usage of jQuery will reduce the number of lines.
Check this
http://docs.jquery.com/Ajax/jQuery.ajax
You will definitely require JavaScript, and some method of sending a HTTP request to your PHP server without reloading the page. Generally, this is called AJAX.
It is probably best to use a JavaScript library, as AJAX is a bit complicated for beginning JavaScript developers. A good choice is JQuery, or MooTools
AJAX libraries usually use XMLHttpRequest or JSONP to implement the HTTP requests. Understanding those should make it a bit easier.
JQuery AJAX: http://docs.jquery.com/Ajax
MooTools AJAX: http://mootools.net/docs/core/Request/Request
Selecting the textarea element, updating it, would require use of the DOM (http://www.w3.org/DOM/). Most JavaScript frameworks now use an implementation of CSS or XSLT selectors to query the DOM.
JQuery Selectors: http://docs.jquery.com/Selectors
MooTools Selectors: http://mootools.net/docs/core/Utilities/Selectors
You can do this fine without JavaScript. Just have each textarea+button in its own <form>, then submit the form to a script that updates the database from the textarea value, and returns a:
204 No Content
status instead of 200 OK and a new page. The old page will stay put.
You can start by adding a jquery function to pick up any changes made ie:
$('#inputelement').on('input propertychange', function(){
alert("Alert to test jquery working");
});
You should then use AJAX to create a php script with the data (as php is how you update to the server) and send using either a GET or POST variable. Then use that script file to upload the changes to your server. e.g.
$('#yourElement').on('input propertychange', function(){
$.ajax({
method: "POST",
url: "updatedatabase.php",
data: {content: $("#yourElement").val()}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
Script upload:
session_start();
if(array_key_exists("content", $_POST)){
include("connection.php");//link to your server
$query = "UPDATE `users` SET `updateColumn`= '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE id= ".mysqli_real_escape_string($link, $_SESSION['id'])." LIMIT 1";
if(mysqli_query($link, $query)){
echo "success";
}else {
echo "failed";
}
}
Try to read more about Ajax. There are a lot of libraries for it.

Categories