I want to get rid of my html form submits and replace them by Ajax ( X M L H t p Request). I have set the form return value to "false" and I have written a small test to test the Ajax mechanism.
At the Java script side I do receive the ready state 4 and status 200, so sending data succeeds apparently, but at the PHP side the variables never arrive.
I try to pick them up the usual way with the POST method, the same way like I did before when receiving html submits, of which the simplified form is:
$x = $_POST['x'];
echo $x;
'x' having been sent with Ajax, state 4 , status 200.
Can anyone tell what am doing wrong?
Thanks a lot.
most likely you are posting JSON data? Try this snippet:
switch ($httpMethod) {
case 'POST':
$rest_json = file_get_contents("php://input");
$jsonData = json_decode($rest_json,true);
foreach($jsonData as $item){
var_dump($item);
$studentsCollection->insert($item);
}
$response = $studentsCollection->find();
break;
This is from a simple rest api I was using. Just change it to suit yourself without a verb switch statement.
Perhaps your ajax request is being submitted via GET instead of POST. Try $_GET instead of $_POST, or use $_REQUEST to cover both your bases. If you're not using jQuery, I'd recommend using it, ajax is a lot easier with ajax(), post(), etc.
$('form').submit(function(e)
{
e.preventDefault();
$.post("test.php", $(this).serialize(), function(result) {
console.log(result)
});
});
I suggent check the header of your ajax requests (in the chrome or firefox), the you can see if really your data is passing to the PHP side.
To find the issue you can use debug tool Firebug is good to to debug ajax request.
using Firebug you can see the ajax call.
You can see the parameters you send.
You can see the respond of the ajax request.
My suggestion is use Jquery for your javascript function.
Jquery ajax call up code -
$.ajax({
type: 'POST',
url: 'ServerPageUrl.php',
dataType: 'json',
success: function(data){
if(data==true)
{
alert("OK");
}
else
{
alert("Error save data");
}
}
});
You can learn more about jquery ajax from jQuery.ajax()
More help full page
Thanks.
Related
I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.
Good Evening!
First of all this is my First Question so sorry, i might be a little nervous.
I have a Problem in the following situation...
I have an ajax call like this:
$.ajax({
url: "test.php",
method: "POST",
data: {
"somedata": "somedata"
},
success: function(){
//Do something when it is an success
},
error: function(){
//Do something when it is an error
}
});
Now i want to give in the test.php an error response so that the jQuery ajax call executes the error and not the success call even if there is no error.
Please don't answer like: 'Why would you like to do this?' I just want to know if that's possible :)
To manually set a response code within your php file, you can use http_response_code:
<?php
http_response_code(500);
?>
See a full list of supported http response codes here (a comment from the docs).
As long as your server returns a response code in the range 4xx -5xx, your $.ajax error function will run.
For anyone else looking at this, if you want a conditional method of checking for an AJAX error, check out this post:
https://stackoverflow.com/a/55201895/3622569
I hope you can help me with this issue:
My sistem runs over Zend Framework, I have installed jQuery in it's latest version. I have an input that receives a file and it makes an Ajax call when changes, and I want that call made in the background, without expecting any response (because that script will send an email when finished). My ajax call is like this:
var formData = new FormData();
formData.append('file', $(this).get(0).files[0]);
$.ajax({
url: 'uploadaddresses.php',
type: 'POST',
data: formData,
dataType: 'json',
async:true,
processData: false,
contentType: false,
beforeSend: function(){
bootbox.alert("You've made your petition correctly. When finished, an email will be sent to you.")
},
error: function(err) {}
});
return false;
Although, the call waits for a response (even FireBug shows me that uploadaddresses.php is still executing...). What i'm doing wrong? How should I do it best? I want to avoid using daemons and system calls, because system restrictions...
Thank you very much in advance :)
If you're wanting uploadaddresses.php to return an HTTP response immediately but continue processing, take a look at pcntl_fork in PHP.
Here's the main doc page: http://php.net/manual/en/function.pcntl-fork.php
Here's a good example that you might want to follow: http://php.net/manual/en/function.pcntl-fork.php#94338
Create a success method for the ajax call and have something like this:
console.log("Done");
This way you know if is complete and successful but only if you are looking at the dev tools. Unless you specify output it should not continue to run after the call has been made. Maybe you have an error in your PHP code?
EDIT: If you can't get this resolved you may want to post your PHP page as well.
I use this simple javascript code to call a php function from javascript.
var a = new XMLHttpRequest();
a.open("GET","save.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
alert("Worked");
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
In this example I have a php function save() contained into save.php file.
I have some questions:
1) How can I call a php function that it is located into the same file where there is the javascript function? (I would to call a php method declared into the same file where there is the javascript caller)
2) Is possible to pass also an php array as parameter?
First: You are not "calling a function". You are making a request to a server. The request is "interpreted" in php, and php has a function defined that is called. Js never calls php directly (one is front side, one is back).
To answer your questions:
You need to make the request to the same page you are displaying, but your js will also be executed.
Yes, but I suggest a post not a get for this (use var_name[] for array, where var_name is the name of the array).
As side notes:
Having both php and js in the same file is usually a bad idea. Try to isolate the front-end from the back-end as much as possible (it may be hard at first, but it will save you from huuuge headaches).
The script you are using is fine for simple things, but lacks lots of things (what if destination was moved and you get a redirect state, what if is unreachable, what if you need a callback, etc.). You are also limited at GET, and for some thing you may prefer POST method. I suggest using js lib for your requests (like jQuery ajax, prototype ajax, etc.) that take care of this things. Or you can extend your script of course.
You have to use ajax call as described manner--
On javascript side on save.php page-
$.ajax({
type:"POST",
data:'demodata',
url:"save.php?action=php_function", // place your php function name here
dataType: "html",
success:function(response){
alert(response); // It will alert value returned by php function
},
failure:function(response){
alert("there is an error.");
},
});
On PHP side on save.php page-
<?php
if(function_exists($_GET['action']))
{
$_GET['action']();
}
else
{
echo 'There is some error.';
}
function php_function()
{
// some code
echo "result";
}
?>
In general, passing an array between PHP and Javascript is better done using a JSON document as interchange format.
You would have to detect the request was made via ajax so that you can run the save() function, or if not then output the page normally, with the JavaScript caller included.
There are a number of ways to detect ajax, one would be to set the X-Requested-With header, which you can check on the PHP side.
save.php
function save(){
// some PHP code here
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){
// request was made via ajax, call the function
save();
exit(); // exit so no page content is sent via ajax
}
// output the page content including JavaScript caller
JavaScript:
var a = new XMLHttpRequest();
a.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // set the header
// continue with your XHR code
The best way to send an array would be to JSON encode it before sending via POST, then JSON decode on the PHP side.
JavaScript:
a.open("POST","save.php");
a.send('json=' + encodeURIComponent(JSON.encode(myArray)));
PHP
function save(){
$myArray = json_decode($_POST['json']);
}
Edit: changed $.alert() to alert()
I've got a file, planner.php that uses JQuery to send an ajax request to the same page.
Using the debugger, I can see that the php correctly gets the request, accesses my database, and then sends the data. However even after sending it I get no success callback in the javascript. What's wrong?
JQuery:
$(function()
{
$.post('planner.php', {"want": "keys"}, success_func, 'json');
});
function success_func(result)
{
//This is never called :(
alert("Worked");
}
PHP:
<?php
require_once "./php/couch.php";
require_once "./php/couchClient.php";
require_once "./php/couchDocument.php";
if (count($_POST) > 0 && array_key_exists("want", $_POST)) {
$couch_dsn = "http://localhost:5984/";
$couch_db = "subjects";
$client = new couchClient($couch_dsn, $couch_db);
header('Content-type: application/json');
$response = $client->getView('subject_views', 'keys');
echo json_encode($response); //This all seems to work fine
}
?>
It's that simple. All of the PHP code there is just accessing couchDB which you don't have to worry about because I know that $response is set correctly.
For knowing where the ajax call is done or faced a error
$(function()
{
$.post('planner.php', {"want": "keys"},function(){
alert( "success" );
})
.done(function(){
alert("second success");
})
.error(function(){
alert("error");
});
});
link : http://api.jquery.com/jquery.post/
This is probably be cause there is no such thing like $.alert(), use simple alert() instead.
Also your success_func is declared below the ajax call, move it up before $.post();
EDIT:
as the function is declared, there is no need to type it before executing.
you can use like that it may be your sucess function not calling
var data = 'want=keys';
$.post(
'planner.php',
data
).success(function(resp){
json = $.parseJSON(resp);
alert(json);
});
Credit to vivek for giving me a method to work out the problem.
Basically I fundamentally didn't understand how php worked. The code for sending the POST response was halfway down the page, so PHP was sending back the entire page along with any extra json I had encoded, and then JQuery attempted to parse this html page as json, failed, and then didn't run the success function because it never succeeded in its request. Read this answer for some more insight
The obvious solutions are:
Make a new page for the response
Put the php at the top of the
page.
I ended up going with option #2 for simplicity's sake.
Thanks everyone!