I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes
Related
I'm using the jquery tabledit plug-in to update a database. Works perfectly like in the official examples.
I can succesfuly include a static dropdown with a fixed number of options (defined in custom_table_edit.js).
I'd like to be able to dynamically get those options from a database instead, but I don't know how to customize the code in custom_table_edit.js.
I can code this in php with a loop querying the database and generating a html <select> field. But I don't have knowledge of javascript or if it's even possible in this framework.
This is the custom_table_edit.js file. A dropdown is defined with three colour options. I want this dropdown to be dynamically produced.
// custom_table_edit.js
$('#example2').Tabledit({
url: 'example.php',
eventType: 'dblclick',
editButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}
});
I really haven't tried anything because i'd like to know if it's possible to do in this framework.
Welcome to SO, nucelar.
What you are describing is a HTTP request from the client to server through JavaScript. This is commonly referred as AJAX or Asynchronous JavaScript And XML. This API enables you to manually send requests to the server and there are multiple implementations.
Because you are using jQuery I will recommend you to use the $.ajax function which is included in the jQuery library.
Down here I've made a very basic example of how to send a HTTP request to a server with the GET method to retrieve some data.
$.ajax({
url: 'https://yourdomain.com', // Where to send the request to. Can also be a file.
method: 'GET', // What method of request it uses.
success: function(data) { // When a response is succesfully received.
// Do something with the received data.
console.log(data); // Show what the data looks like in the console.
},
error: function(jqXHR, textStatus, errorThrown) { // When an error occurs while making a request.
console.log(jqXHR, textStatus, errorThrown); // Show the error in the console.
}
});
In your case the url property value might be the URL of a PHP file in which you query the database and return the result, as you mentioned you are able to do.
The response of the AJAX function (which is stored in the data variable in the success method) can be text, as in a string, or even JSON if you want to send structured data.
Beware of the Asynchronous part. This means that the AJAX code does not stop the execution of the rest of your JavaScript code, but simply continues and comes back whenever the HTTP request has been completed.
I hope that this is enough to get you started. Good luck and don't hesitate to ask questions.
I'm very new to JSON and JSONP.
I've read through each of the posts that are recommend by the SO search for this error, but I can't seem to get a handle on it.
I have the following code to grab data from an EXTERNAL website:
$.ajax({
url: "https://url.com/authenticate?login=test&apiKey=test",
dataType: 'jsonp',
success:function(json){
console.log("login successful");
}
});
When I load the page, I get:
Uncaught SyntaxError: Unexpected token :
and when I click on the error in Chrome, I see
{"Status":{"Code":"2","Message":"Authentication Succeeded","Success":"true"}}
with a little red x after "true"})
From this, it seems as though I have succeeded in logging in, but I'm doing something else wrong because my console.log("login successful"); never fires. What am I doing wrong?
P.S.
I've tried dataType: 'json' but I get the No 'Access-Control-Allow-Origin' header is present as I'm on a different server, so I went back to jsonP as this is cross-domain.
I've also tried the above url as url: "https://url.com/authenticate?login=test&apiKey=test&callback=?", as I've read I need a callback, but I don't really understand what the functionality of callback is and either way, the error that gets returned (whether &callback=? is in there or not) is:
authenticateUser?login=test&apiKey=test&callback=jQuery111107732549801003188_1423867185396…:1 Uncaught SyntaxError: Unexpected token :
so it's adding the callback in either way....
Also, from the API I'm trying to access:
"this uses the REST protocol, and provides data structured as XML or JSON"
This is not a duplicate of the linked post as the information in the linked post does a great job of explaining what JSONP is, but doesn't answer my specific question regarding why I get data back (so my call is successful,) but why I still get an error and cause my script to stop.
The API you're sending the AJAX request doesn't implement JSONP. It ignores the callback= parameter, and just returns ordinary JSON. But when the browser tries to process this as JSONP, it gets a syntax error because it's not properly formatted. JSONP is a JSON object wrapped in a call to the specified callback function, e.g. it should be sending back:
jQuery111107732549801003188_1423867185396({...});
where {...} is the JSON object you're trying to retrieve. But it's just returning {...}.
You should implement this using a PHP script on your own server. It can be as simple as this:
<?php
$username = urlencode($_POST['user']);
readfile("https://url.com/authenticate?login=$username&apiKey=test");
Then your AJAX call would be:
$.ajax({
url: "yourscript.php",
type: "post",
dataType: "json",
data: { user: "test" },
success: function(json) {
console.log("login successful");
}
});
So I have to send some data to a php page, and it will return me another php page based on my data.
I send the data this way:
$(document).ready(function() {
$.ajax({
url: '//www.example.com/page.php',
type: "post",
dataType: 'jsonp',
data: { myvar:myvalue },
success: function(response) { console.log("success."); },
error: function(XMLHttpRequest, textStatus, errorThrown) { console.log("error."); },
complete: function() { console.log("complete."); }
});
});
It shows an alert saying jQuery180014405992737595236_1357861668479 was not called (numbers are copied from other question)
I think the reason is that it's expecting a json result from the page, when it's not.
In Chrome it says Uncaught SyntaxError: Unexpected token < referring to the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
To sum up, this works, but that jQuery alert and the console error needs to be fixed, and I think the right way would be handling properly the returned result page.
I hope you guys can help me fix it that seems quite a simple task, but Im really new to this. Thanks
Removing the dataType: 'jsonp' or changing it to 'json' turns out on my script not being executed and getting the following error:
XMLHttpRequest cannot load http://www.example.com/page.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myserver.com/myPage' is therefore not allowed access.
I think the reason is that it's expecting a json result from the page
It's expecting a JSONP response. (JSONP is not JSON). You said:
dataType: 'jsonp',
… which explicitly forces jQuery to treat the response as JSONP (and, as a side effect, GET).
the returned php page, so I assume that my code isnt expecting that kind of file to be returned.
The server shouldn't be returning a PHP page. It should be executing the PHP code and returning whatever that outputs. It looks like it is outputting HTML.
You need to either:
Not tell your script to expect JSONP. (Note that you'll probably then have to configure CORS on the server to deal with same origin issues) or
Change the PHP to return JSONP
I am building a jQuery Mobile and PhoneGap application.
Here is some of my code to query data from an external server:
function showDetail(stationID){
$('#itemDetail').load('http://www.mywebsite.com/detailPage.php?stationId='+stationID, function(){
});
It works perfectly on my local machine, WAMP server, however when I compile the script and run on an actual device, Android, it does not work. The same thing applies to this form:
$('#addStationForm').on('submit', function(e) {
$.post( 'http://www.mywebsite.com/add_parser.php', $(this).serialize(), function(response) {
alert( response );
});
// disable default action
e.preventDefault();
});
Also I have whitelisted my server, so that is not the problem.
Any help would be greatly appriciated, thanks.
Are you trying to get data from a server and load it into a dom element?
If so use the .ajax function to perform a http request to get the data from the sever.
Check the following doc with good examples
http://api.jquery.com/jQuery.ajax/
Also provide more info about the type of data you are going to request receive to help you further in the configuration of the ajax call parameters.
You can also use getJSON but depending on your data and needs.
EDIT
Post is a shorthand of the ajax function.
Make sure your PHP does have the correct content-type in the headers. That is very important
Like:
header("Content-Type:text/plain");
or
header("Content-Type:text/html");
depending what you need, want.
Also you can debug the HTTP response using firebug or any other tool out there, and let us know what you got.
Also try to use the verbose option of the function, give it a try. Make sure you specify correctly the dataType and the data parameters.
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "html" // DATA TYPE is ALSO VERY IMPORTANT
})
.done(function() {
alert( "success" );
})
.fail(function( XMLHttpRequest, textStatus, errorThrown ) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
});
Also, when you said "when I compile the script and run on an actual device, Android, it does not work.", what errors you got? use the FAIL function of the http request to print the errors (like in the example above).
This is my $.ajax function. volunteerDist is an array in a previous function and it calls myAjax(volunteerDis);However, the program always calls the error and complete functions, with an error message of undefined. What should I do? Thanks
admin-view-available-volunteeers.php is the filename where this is located
volunteerDist is an array that contains floats
function myAjax(volunteerDist){
$.ajax({
type:'POST',
url: 'admin-view-available-volunteeers.php',
data : ({
distance:volunteerDist
}),
success: function(){
alert('worked');
},
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
complete : function(){
alert('thanks');
}
});
}
If your error: handler is being called, then the remote script returned an error.
Fix the script, not the JS code!
To get better debugging on error you need to update your code, this
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
will not work - as err is a jqXHR object!
change it to this :
error: function(jqXHR, textStatus, errorThrown) {
alert("Error : " + errorThrown);
}
This will output the message sent by the server.
All the details for the params of .ajax() are documentation here
Update
Check the name of your PHP file ...
admin-view-available-volunteeers.php
has 3 es in the word volunteer ... is this the problem ?
I always get this a lot. In your admin-view-available-volunteers.php you need to make sure that you're outputting the right headers.
To do that you need to put this in your php before anything is output:
header("HTTP/1.01 200 OK");
header("Content-type: text/html");
Otherwise it is returned as a 404 to jQuery's ajax and then goes into the error and complete bits.
You may wish to try loading a different test file first, something simple that way you can test the js separately and ensure that when you hit the php script directly in your browser that there are no errors shown.
Also in the future make sure you have all these ajax calls on the same domain as your php scripts(like you do now), otherwise ajax won't work across domains without adding a "Access-Control-Allow-Origin", "*" header.