$.ajax() post value not reaching php - php

I created an Ajax post request and for some reason the post data is not being received correctly by the PHP script. I get a 500 internal server error followed by "XHR failed loading: POST".
Here is a portion of my javascript:
$.ajax({
type: "POST",
url: 'newmessage.php',
// Generic form data
data: {name: $("#name").val(), message: $("#message").val()},
success: function(result){
showMessages();
}
});
Here is the PHP:
if(isset($_POST['name']) && isset($_POST['message']))
{
// Do something
}
Having looked at my code in detail I believe that I did something incorrect in my ajax request. Within my PHP file, if I create a javascript alert to output the $_POST variables, nothing gets printed.
<?php
$x = $_POST['name'];
?>
<script language="javascript">
alert ('<?php echo $x; ?>');
</script>
<?php
?>

Well, it's hard to say how your server is configured, but, just at first glance, it looks like your url may be the issue.
$.ajax({
type: 'POST',
url: '/newmessage.php', // <--- notice the leading slash
data: {
name: $('#name').val(),
message: $('#message').val(),
},
success: function(reply) {
//do stuff...
}
});
Check out the docs here: http://api.jquery.com/jquery.ajax/
Also, if you're using Chrome you can use the developer tools to see exactly what's going on under the hood. Specifically the Network tab. https://developers.google.com/web/tools/chrome-devtools/
Lastly, if you just want to troubleshoot your server, you can take jQuery out of the picture and use an app like Postman. https://www.getpostman.com/apps

XHL stands for XMLHttpRequest
Sounds like a there is no servelet (url issue).
or
servlet(php) just aborted your request(csrf token missing)
Solution 1,
Check the url
normal call
URL:"/newmessage.php" //modification needs here
rest call
URL:"/http://address/newmessage.php" //keep it in your mind please
Solution 2,
<form>
//...
<input type="hidden" id="token" value="<?php echo $token; ?>" />
//...
</form>
function sendDatas(){
var token =$("#token).val();
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
jqXHR.setRequestHeader('X-CSRF-Token', token);
});
$.ajax({
type: 'POST',
url: '/newmessage.php', // <--- notice the leading slash
data: {
name: $('#name').val(),
message: $('#message').val(),
},
success: function(reply) {
//do stuff...
}
});
}

Related

Getting an ajax post data in php

$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
dataType: 'json',
}).done(function(){
console.log('done');
});
Above is my AJAX post, below is my PHP:
var_dump($_POST['test']);
die();
The problem is, this fails to work (I get a NULL value) - why?
I know my call is getting to the PHP code as I can dump any old string:
var_dump('hello');
die();
Where am I going wrong?
Just remove this dataType: 'json'. Your $_POST['test'] is a string value, not a JSON string.
The POST value that you are testing with is not JSON, it's a string.
Remove the
dataType: 'json',
and it should work.
When you set dataType: "json" within the AJAX request it means the expected response should be parsed as json, (not the outgoing POST, as others have said).
Heres is a stripped down copy&paste example, for you to build upon. Hope it helps
<?php
//is it POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// set var
$test = isset($_POST['test']) ? $_POST['test'] : null;
//do some logic - skip that bit ;p
//was the request from AJAX, ok send back json
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//always a good idea
header('Content-Type: application/json');
//json encode, notice the ABC, then look at the jQuery below
die(json_encode(
array('ABC' => 'From Response: '.$test)
));
}
}
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var ajax = $.ajax({
url: "./",
type: "POST",
data: {test : 'test'},
dataType: "json"
});
ajax.done(function(data) {
$("#result").html(data.ABC); /* << See data is an object */
});
ajax.fail(function(xhr, status, error) {
$("#result").html(xhr.responseText);
});
});
</script>
<span id="result"></span>
I'm not totally sure if this is the issue, but .done is deprecated. Additionally, as others mentioned, you are asking for json from the server and not receiving json.
Your code should look like this
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
success: function () {console.log('done');}
});
I would like to recommend you my code. and please do check the following points.
check the location of the url you are giving. If it is in parent directory then you can access it using ../ and the most important thing give the extension of the file. like 'gateway.php'
and write success and failure function. It gives a better insight of what's going on.
$.ajax({
type:'POST',
url:'gateway',
data:{test:'test'},
success: function(data){
if(data)
{
alert(data);
}
},
failure: function(){
alert(failed);
}
}) ;
comment if there are any errors
hope it helps :). If it does then don't forget to green it :P
Or change PHP code
header('Content-Type: application/json');
exit(json_encode(array('data' => 'Bla bla bla')));

Very simple jquery AJAX post issue

I've been trying to find the problem for the last couple of hours, but no solution.
I'm having an issue with the following AJAX post request.
$("#about_button").click(function(e)
{
var about = $("#input_about").val();
$.ajax
({
type: 'POST',
url: location.href,
data: {
'about' : about,
},
success: function(message)
{
},
complete: function(message)
{
alert(about);
}
});
e.preventDefault();
});
Here is the html part of the code;
<textarea id="input_about" name="input_about"></textarea>
<input type="button" id="about_button" class="button" value="Update" />
And finally the PHP part at the beggining of the file;
<?php
require_once("headers.php");
if(isset($POST["about"]))
{
$data= $POST["about"];
$database->query("UPDATE hakkimizda set icerik='$data'");
echo '<script type="text/javascript">alert("dsdsfdsdfsf"); </script>';
}
?>
When I click the submit button, it goes into the complete function and alerts the data, but it looks like the page never receives the post message.
I don't if its related with my issue, but I'm using WAMP on localhost.
Its $_POST["about"] not $POST["about"] also as it stands you are open to sql injections.

Ajax call will not work

I have this method that I want to run a php file using ajax and then reload the page.
function winA()
{
var x = "<?php echo $id;?>"
$.ajax({ url: 'w.php5' ,
data: { id: x },
success: function(data) {
window.location.reload()
}
});
}
This is what I have and I've looked it over endless times for flaws, made sure the php variable is reading properly and made sure the function is truly being called. The php file works properly when called w.php5?id=1
Why won't this ajax call work?
Thanks in advance for the help, Aaron.
function winA()
{
var x = "<?php echo $id;?>"
$.ajax({ url: 'w.php5' ,
data: { id: x },
success: function(data) {
window.location.reload()
}
error:function (xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
});
}
This way it will show alert in case of ajax error
Also, if in chrome, press the combination Ctrl+Shift+I for developer tools and check network tab to see if w.php5 is called, and what is the response. Dont know tools for other browser but there should be something like that
There are 2 alternatives.
If you want to post some other data, use this
.ajax({
type: 'POST',
url:'w.php5',
data: {id: '<?php echo $id; ?>'},
success: function(resp){
console.log(resp);
},
dataType:'json'
});
If you go this way, your ID is going to be stored in $_POST array => *$_POST['id']*
If you want to just get some data by ID you post, use this
.ajax({
type: 'GET',
url:'w.php5?id=<?php echo $id; ?>',
success: function(resp){
console.log(resp);
},
dataType:'json'
});
If you go this way, your ID is going to be stored in $_GET array => *$_GET['id']*
You're missing a semicolon here:
var x = "<?php echo $id;?>"
Should be:
var x = "<?php echo $id;?>";
//set the method
POST or GET
type:'GET'; or type:"POST"
That url is probably missing a leading forward-slash, assuming you are trying to access a url like www.myurl.com/w.php?id=5
Try
url: '/w.php?id=5',
If that doesn't work, you need to inspect the request using a developing tool within Chrome or Firefox.
You can also var_dump the $_GET or $_POST in w.php, as the response will expose the output.

jquery ajax not working?

i have a jquery ajax post that for some reasons doesn't work:
<script>
var callback = function(data) {
if (data['order_id']) {
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
}
});
}}
</script>
<?php if ($_POST['myid']) { echo $_POST['myid']; } ?>
the 'callback' functions works fine(i test it), just that it stops at the ajax post
and i cant see my echo's
any ideas on what i am doing wrong?
thanks
edit:
i edited the script a bit at the point where the ajax is posting successfully but i cant get the php to echo anything
If the AJAX - Call is succeeding now, you can't just echo anything with PHP. The data is sent to the client, but PHP is interpreted at the server. You're not sending an HTTP - Request anymore (which is pretty much the point of an AJAX-Call), so PHP is not going to do anything at this point.
You have to add your new content to the DOM with JavaScript. Try this and see if you get the message shown on your page. I append it to the body, because I don't know how your Markup and your returned data looks like:
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
$('body').prepend('<p>Successful AJAX - Call</p>');
}
});
Then you can take a look at your data-variable with console.log(data), access the returned data and modify the DOM via JavaScript.
ok, for a start.
writeback("Transaction Completed!";
fix it to:
writeback("Transaction Completed!");
you have a trailing comma after 123456
data: { myid: 123456, },
you're missing a closing } to your callback function

AJAX form submission and results

Just started using AJAX today via JQuery and I am getting nowhere. As an example I have set up a job for it to do. Submit a form and then display the results. Obviously I haven't got it right.
The HTML.
<form id="PST_DT" name="PST_DT" method="post">
<input name="product_title_1682" id="product_title_1682" type="hidden" value="PADI Open Water">
<input name="product_title_1683" id="product_title_1683" type="hidden" value="PADI Advanced Open Water">
<input type="submit" name="submit" id="submit" value="Continue" onclick="product_analysis_global(); test();"/>
</form>
<span id="results"></span>
There are actually many more fields all loaded in dynamically. I plan to use ajax to submit to PHP for some simple maths and then return the results but we can worry about that later.
The JQuery
function test() {
//Get the data from all the fields
var alpha = $('#product_title_1682').val();
JQuery.ajax({
type: 'POST',
url: 'http://www.divethegap.com/update/functions/totals.php',
data: 'text=' + alpha,
beforeSend: function () {
$('#results').html('processing');
},
error: function () {
$('#results').html('failure');
},
timeout: 3000,
});
};
and the PHP
<?php
$alpha = $_POST['alpha'];
echo 'Marvellous',$alpha;
?>
That's my attempt and nothing happens. Any ideas?
Marvellous.
First of all, you're passing the $_POST variable as 'text' while your script is looking for $_POST['alpha']. If you update your PHP to $_POST['text'], you should see the proper text.
Also, if your form is going to have lots of inputs and you want to be sure to pass all of them to your AJAX Request, I'd recommend using jQuery's serialize() method.
data: $('#PST_DT').serialize(), // this will build query string based off the <form>
// eg: product_title_1682=PADI+Open+Water&product_title_1683=PADI+Advanced+Open+Water
In your PHP script you'd then need to use $_POST['product_title_1682'] and $_POST['product_title_1683'].
UPDATE Add a success callback to your $.ajax call.
function test() {
// serialize form data
var data= $('#PST_DT').serialize();
// ajax request
$.ajax({
type : 'POST',
url : 'http://www.divethegap.com/update/functions/totals.php',
data : data,
beforeSend : function() {
$('#results').html('processing');
},
error : function() {
$('#results').html('failure');
},
// success callback
success : function (response) {
$('#results').html(response);
},
timeout : 3000,
});
};
In your PHP script you can debug the information sent using:
var_dump($_POST);
In your AJAX request, you are sending the parameter foo.php?text=..., but in the PHP file, you're calling $_POST['alpha'], which looks for foo.php?alpha=....
Change $_POST['alpha'] to $_POST['text'] and see if that works.
There is a simpler method:
$("#PST_DT").submit(function(e){
e.preventDefault();
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'http://www.divethegap.com/update/functions/totals.php',
success: function(){
....do stuff.
}
});
return false;
});
This will allow you to process the variables like normal.

Categories