Jquery toolbar help: accessing external php script - php

Hi i'm currently working on a toolbar and have run into a problem. I have two files, the toolbar and a PHP script. The PHP script simply pulls an array of titles out of a database. What I am trying to do is get the toolbar to call this script and return this array, and then use this array to create a drop down menu with the titles as the options.
I'm assuming I need to use Ajax in some form but have no idea how to achieve this.
Many Thanks.
UPDATE: I am having problems getting .getJSON work cross browser because of the same site policy. The problem is the javascript file making the call produces a toolbar which is appended to a remote site, this toolbar is supposed to call a php script back on my own server to get data from a db.
How can I get around this issue?

Yes. If you want to have PHP and Javascript working together the answer is: JSON. You will have to JSON encode your array in php. Use Javascript Ajax to call the PHP file and then parseJSON the response. Then you have your array in use in Javascript. After that you can render it in Javascript and just attach the result to the element you want.
There are plenty of examples in jQuery documents. If you are unfamiliar with ajax, read the documentation: http://api.jquery.com/jQuery.ajax/ In the end there are simple examples. You can also use .getJSON.
jQuery.getJSON( url, [data,] [success(data, textStatus, jqXHR)] )
- url A string containing the URL to which the request is sent.
- data A map or string that is sent to the server with the request.
- success(data, textStatus, jqXHR) A callback function that is executed if the request succeeds.
Basically:
$.getJSON("url of the php file",
data to send to the php file if any,
function(data) {
console.log(data);
}
});
Inside that function where is the console.log you can do anything you want with your data.

Related

Replace an API call using $.ajax() and JSONP with a server-to-server API call

I have a javascript application calling an ajax function that looks like this
$.ajax({ url: apiURL, dataType: 'jsonp', success: function(data) {
if (data.ok) {
//do things
}}});
the ajax url im trying to access is through etsyapi
everything works fine and dandy until i try to access the application in chrome with adblock on. it makes the ajax call fail completely, returns an error with a Failed to load resource-"theActualURL" message.
I couldn't figure out how to get past this in javascript and was told that i need to do a php call to get this working.
Unfortunately, i dont know the first thing about php- ive tried to understand even the basic structure for it, and i havent been able to find any work arounds in javascript, so i think it has to be done with php.
Is there simplest way to call the ajax function in php with a dynamic url(which is passed to the php page from javascript) and have it pass the array back to javascript to maniuplate?
ive gotten this far with the php-
<?php
$json = array();
????????????????????????
$jsonstring = json_encode($json);
echo $jsonstring;
?>
but dont understand how to access a dynamic url from javascript.
If it's genuinely using jsonp you shouldn't need php. Replace your $.ajax... with:
var newScript = document.createElement('script');
newScript.src = apiURL;
document.head.appendChild(newScript);
Ignore the above, I'm out of date with jQuery. Even so, you shouldn't need php if the API endpoint is really responding with jsonp. It sounds like the url was wrong/bad if you're getting an error. Have you tried simply opening apiURL by putting it in your browser's address bar?
jsonp is a work around for cross domain ajax restrictions that wraps the returned data in a javascript function call. This allows you to load it in a script tag and the function is run with the data as a parameter when the script is executed.

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

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

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.

Categories