I am having trouble getting a basic ajax POST to work. I switched to an onclick after I was having trouble getting using a jquery .click, among other things. Just wondering if I am making some blatant mistake or what. If no obvious mistake, it may be something with apache? Not too much experienced here so any help would be appreciated.
Here is a link to a function:
click this for php page
Here is the function:
function postData() {
console.log("outside ajax is working");
$.ajax({
type: "POST",
url: "/markerpages.php",
data: {
source1: "some text",
source2: "some text 2"},
success: function (data) {
console.log("inside ajax is working");
},
error: function () {
console.log("ajax post failed")
}
});
here is what I have on my php webpage:
<?php
if (isset($_POST['source1']))
$src1 = $_POST['source1'];
else $src1 = "post data not obtained";
echo $src1;
echo "<pre>" . print_r($_REQUEST, 1) . "</pre>";
print_r($_POST);
var_dump($_POST);
var_dump($_POST);die;
?>
I am not returning errors in firebug, and I am getting the log statements I placed inside ajax and outside, just not getting empty arrays on the PHP page.
Sincere thanks for any help.
You are sending the user to the page using the anchor tag. If you do this, all post data is lost. You need to replace the url in the anchor tag with # to make sure the user stays on the page:
click this for php page
First of all you should put a return false; in the js function, doing so there will not be any redirects,
Check in Developer Network your request, if the url is correct and if you are retrieving any errors during the ajax post.
When clicking the link, postData() is being called, but then the browser is loading the URL specified in your <a href>. You can do one of three possible things:
Add the following line at the top of your postData() function: event.preventDefault(). That will stop the original event clicking action, and is the preferred method.
Change your onclick attribute and add return false to prevent the URL clicking behavior. Ex: onclick="postData(); return false;
Change the <a href="/markerpages.php"> to <a href="#">. But this is not a good approach since the page's URL will change to mypage.htm#.
Another helpful debugging tip: you can output the data variable (the returned value from your PHP script) like so: console.log(data);.
And since you seem to be hand building a form which will eventually pass values from the server back to the front-end, I suggest looking at this article: Pass a PHP Array to Javascript as JSON using AJAX and json_encode()
Related
I am new to AJAX here. How can i replace the initial php function after the action of ajax is execute? I have found that the page will not refresh after the action is execute.
Here is the code:
javascript
function set_ddm(another_data) {
var result = $.ajax({
url: '../display/ea_form_header.php',
type: 'POST',
data: {
action: 'set_ddm',
Data_store: another_data,
},
success: function(data) {
console.log(data);
}
}).responseText;
}
php code
<td>
<?php
//initial function (customized drop down)
print ddm_jsfunc_employee("employee_list",$employee_list)
set_ddm(data);
if($_POST['action'] =='set_ddm') {
$employee_list=$_POST['Data_store'];
$employee_list_decoded = json_decode($employee_list,true);
//expected this function to replace the initial function after ajax was called
print ddm_jsfunc_employee("employee_list",$employee_list_decoded);
} ?>
</td>
I expect the function will replace the initial function and show in the main page but it only show in console after ajax(page aren't refresh to show it). Is there any wrong with the code or any solution for this? (the ddm_jsfunc_employee must be there to print the drop down)
thanks in advance
From ajax success callback you have to set that response in the html to view on web page.
like this:
$('.elementClass').html(response);
i hope this will works for you.
I think you have a slight misunderstanding about what AJAX is, it is not something to replace your PHP code with, but to asynchronously get data and update your webpage without reloading.
Let's first take a look at the .ajax function specifically interesting for us now is the .done() callback method, because JavaScript does the request realtime (async) JavaScript does not know when the request is done. But it allows us to specify a function inside the .done for it to call when it is done.
A really simple example would be:
$.ajax('https://stackoverflow.com')
.done(function(data) {
// We can do what we want with the data here.
console.log(data);
});
Now when the request is done the function we defined in .done will be called, in this case a simple log. But you would want to change this to a function that updates your HTML.
I also see you are calling JavaScript functions in your PHP, this will not work as PHP runs on your server but JavaScript runs in your browser. (Unless you use node or the likes)
Just a tip; it is advised to place JavaScript at the bottom of your HTML page as JavaScript is blocking content. (proper link explaining needed here)
Meaning your browser will stop parsing the HTML and run the JavaScript as it finds it.
Long story short, if you want to replace the PHP code, you would have to remove it. Make a PHP script which gives you your data. AJAX call it and then use .done or success and update your webpage from there.
My files:
signup.php, form.php, success.php, failure.php.
In signup.php there's an area <div id="myarea"></div>. Inside of this block I load the form.php by default via <?php include ("form.php"); ?>.
Now I want to show the success.php or failure.php whether the signup was successfull or not.
My Question: How can I replace the content/loaded file in myarea?
(Until now I did not wrote the file the data of the form is sent to.)
EDIT: I'm new to php and so on
This is not using ES2017, but it is a simple example and will give you the general idea.
I assume you are using ajax to verify the login, so something like below.
When you come back from the ajax (that is, inside the ajax .done() or .success or whatever-you-use function, you can either use $.load() to load the new content and $('#myarea').html() to replace the content of the #myarea div, or even something as simple as $('#someHiddenDiv').show() to reveal a previously hidden div.
Here is a simplistic example:
var my_id = $('#loginid').val();
var my_pw = $('#loginpw').val();
$.ajax({
type: 'post',
url: 'ajax/login.php',
data: 'id=' +my_id+ '&pw=' +my_pw,
}).done(function(recd){
if (recd==1) {
var newhtml = $.load('success.php');
$('#myarea').html(newhtml);
//-OR-
//$('#myhiddendiv').show();
}else{
$('#loginid').val('');
$('#loginpw').val('');
alert('Please try logging in again');
}
});
Now that you see a very basic example, here is how we do it these days:
How to do AJAX in 2018
Understanding the Fetch API
Async/Await in 2017
I have a form which when submitted is checked by the JQuery validator plugin. This works fine. In the JQuery code though I have my submit handler.
This part looks like the following:
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "php/main.php",
data: $(form).serialize()
});
return false;
}
Now I dont see anything wrong with this, looks fine to me. Then in main.php, I simply do
<?php
var_dump("OK");
include("APIEmailConnection.php");
var_dump("OK2");
if (isset($_POST["emailAddress"]) && !empty($_POST["emailAddress"])){
var_dump("OK3");
$connection = new APIEmailConnection();
$connection->obtainConnection();
var_dump("OK4");
}
I dont show it above, but I have a success function in my ajax call, and everytime I submit my form with an email address the success is fired. However, if I check firebug, I see the error
Fatal error: Class 'APIEmailConnection' not found in
/var/www/vhosts/myurl.com/httpdocs/folder/php/main.php on line 12
Also, the outputs from my var_dumps are
string(2) "OK"
string(3) "OK2"
string(3) "OK3"
So its missing OK4. My folder structure is like so
index.html
--js
--main.js
--php
--main.php
--APIEmailConnection.php
Now php include should be relative to the current file location, and because I am in main.php I believe my include is the correct path. And my submit handler must be correct, otherwise main.php would never be called in the first place.
So my question is what am I doing wrong? I dont know if it makes a difference, but main.php is a standard php file whereas APIEmailConnection.php is a class (and I dont namespace it).
Any advice on what the problem could be appreciated.
Thanks
Try checking the relevence to the section from which you include or use the main.php file. Hope this helps.
I am using this plugin to enable me to display what I am currently listening to live on my website: https://github.com/derekmartinez18/Simple-Ajax-Spotify-Now-Playing
A piece of JavaScript will run on page load, which connects to the PHP which via API checks what I am listening to, grabs the title etc, if successful sends back to the JavaScript and displays via HTML.
I've echoed out what the PHP is getting and can see it's correctly grabbing all the recent songs, names etc. Therefore because nothing is appearing on the page maybe it's the JavaScript. I've pasted it below with pastebin link to php too.
JavaScript
<script type="text/javascript">
function get_spotify() {
$.ajax({
type: 'POST',
url: '/Scripts/last.fm.php',
data: { request: 'true' },
success: function(reply) {
$('.now-playing').html("<p>" + reply + "</p>");
}
});
}
window.onload = get_spotify;
</script>
Pastebin of PHP - http://pastebin.com/eZUH6BNU
A snippet of the API output which is being past over to the PHP (it's huge so didn't paste it all.):
{"recenttracks":{"track":[{"artist":{"#text":"LMFAO","mbid":"ed5d9086-e8cd-473a-b96c-d81ad6c98f0d"},}
Live Link - http://bit.ly/1ewTe8l
Based on the example you have given below your question, the problem is that there is no element with a class of now-playing.
Your page seems to have been cut short, perhaps due to an error, but the ajax request fires and in the console I can see the response (the url is actually echoed before that as well):
I am currently listening to 01. Circles Around The Sun by Dispatch on Spotify.
Adding a <div class="now-playing"></div> should do the trick.
Edit: Note that your key is visible in the response as you are echoing the url you are making a request to. It might be a good idea to change the key when you have solved your problem.
Is it possible to run a MySQL query using jQuery? I'm trying to emulate the functionality of voting on SE sites.
The vote counter on SE automatically updates without the need to reload the page (which is what I currently have, a hidden form that re-submits to the current page but runs a small block on PHP that updates the score of a question in the database). I'm assuming that is being done using Javascript/jQuery seeing as it is dynamic.
How can I do this? Is there a library which makes it easy and simple (like PHP)?
You can use ajax to call a server page (PHP / ASP /ASP.NET/JSP ) and in that server page you can execute a query.
http://api.jquery.com/jQuery.ajax/
HTML
<input type='button' id='btnVote' value='Vote' />
Javascript
This code will be excuted when user clicks on the button with the id "btnVote". The below script is making use of the "ajax" function written in the jquery library.It will send a request to the page mentioned as the value of "url" property (ajaxserverpage.aspx). In this example, i am sending a querystring value 5 for the key called "answer".
$("#btnVote").click(function(){
$.ajax({
url: "ajaxserverpage.aspx?answer=5",
success: function(data){
alert(data)
}
});
});
and in your aspx page, you can read the querystring (in this example, answer=5) and
build a query and execute it againist a database. You can return data back by writing a Response.Write (in asp & asp.net )/ echo in PHP. Whatever you are returning will be coming back to the variable data. If your query execution was successful, you may return a message like "Vote captured" or whatever appropriate for your application. If there was an error caught in your try-catch block, Return a message for that.
Make sure you properly sanitize the input before building your query. I usually group my functionalities and put those into a single file. Ex : MY Ajax page which handles user related stuff will have methods for ValidateUser, RegisterUser etc...
EDIT : As per your comment,
jQuery support post also. Here is the format
$.post(url, function(data) {
alert("Do whatever you want if the call completed successfully")
);
which is equivalent to
$.ajax({
type: 'POST',
url: url,
success: function(data)
{
alert("Do whatever you want if the call completed successfully")
}
});
This should be a good reading : http://en.wikipedia.org/wiki/Same_origin_policy
It's just a few lines in your favorite language.
Javascript
$.post('script.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
PHP (simplified)
$id = intval($_POST['id']);
mysql_query("UPDATE votes SET num = num + 1 WHERE id = $id");
There are many different ways to accomplish this.