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.
Related
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...
}
});
}
Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.
I'm currently learning PHP. I've made a simple script # http://hash.techho.me, only thing is, I want the form to submit then load the results via AJAX, without the user leaving the page. Possible?
post the form using ajax
$.ajax({
url:'yoururl',
data:$("form").serialize(),
type:'POST',
success:function(data){
alert("success");
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
jQuery.ajax() – jQuery API
Posting to the same page should do the trick. No need to use ajax for that
> <?php
>
> //do stuff with $_POST
> ?>
>
> <html> <body> <form method="post">
>
> <?php echo $result ?>
>
> </form>
> </body>
Fike
use ajax for this, lets suppose try this one for your practice
var string = $("#string").val();
var dataString = 'string=' + string ;
if(string==''){
alert('enter any string');
}
else{
$.ajax({
type: "POST",
url: "path of php file",
data: dataString,
suceess: function(){
//do something
},
error: function(){
//do something
}
});
}
You can use jQuery or Prototype JS libraries to make an easy AJAX call. Example using jQuery would be:
$.ajax({
url:'hashed.php',
data:$("form").serialize(),
type:'POST',
success: function(data){
$('hashmd5').html(data.md5);
$('hashsha1').html(data.sha1);
},
error: function(jxhr){
alert(jxhr.responseText);
}
});
Don't use the same id value in HTML, never ever. They must be unique to correct perform JavaScript functions on elements.
yes it is possible. Write a javascript function that would trigger on submit, disable the submit button so user couldn't press it again, and finally request the server via ajax. on successful response update the content. Something like following in Jquery
$('.form-submit').click(function(event)) {
event.preventDefault();
if(form is valid and not empty) {
$.ajax({
type: "POST",
url: "path to script that will handle insetion",
data: "data from form", //like ({username : $('#username').val()}),
suceess: function(data){
//update the content or what. data is the response got from server. you can also do like this to show feedback etc...
$('.feedback').html("Data has been saved successfully");
},
error: function(){
$('.feedback').html("Data couldn't be saved");
}
});
}
}
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.
I have the following ajax call:
$("#welcome a.close").click(function(e) {
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
e.preventDefault();
}
});
});
Aimed at the following piece of my site:
<div id="welcome">
<h2>Welcome <a class="close" href="Javascript:;"></a></h2>
<div class="left">
</div>
<div class="right">
<div class="loginElement">
</div>
</div>
<div class="clear"></div>
</div>
With the following code to answer the ajax request:
<?php
class VisitorsController extends AppController {
function hide_welcome() {
if($this->RequestHandler->isAjax()) {
$this->Session->write('Welcome.hidden', true);
echo 'Success.';
}
else {
echo 'I am, in fact, here.<br>';
$this->autoRender = false;
}
}
}
?>
It's pretty straight forward. It calls to /visitors/hide_welcome to set a session variable noting that they've hidden the welcome. But it doesn't seem to complete. If I place alerts on either side of it, like so:
$("#welcome a.close").click(function(e) {
alert("Begin.");
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
e.preventDefault();
}
});
alert("End.");
});
They will trigger. But alerts placed in success are ignored. The same goes for error and complete. This was working just fine on my test machine. The page in question is definitely there, I can reach it with out ajax. Firebug reports nothing, neither does the error console. Success simply never fires.
The strangest part is that often if I reload manually the welcome disappears, indicating that the ajax call did fire. It just never returned. What is going on here? I'm at wits end. Any one see any trees I haven't barked up yet?
SOLUTION:
CakePHP is supposed to auto detect ajax calls. But in this instance, it wasn't. As a result it was running the code I had for the Ajax, but then returning a 404 when it failed to find a view. The solution was to append $this->autoRender= false; to the end of the ajax handling controller function. After that everything worked beautifully.
I think given your symptoms, you're redirecting to whatever URL the <a class="close"> you're clicking on pointed to - since the default behavior isn't prevented.
The e.preventDefault() call should happen in the base method, not a callback, like this:
$("#welcome a.close").click(function(e) {
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(){
$("#welcome").hide(0);
}
});
e.preventDefault();
});
Try adding data to your success callback like so:
$.ajax({
type: "GET",
url: "/visitors/hide_welcome",
success: function(data){
$("#welcome").hide(0);
e.preventDefault();
}
});
EDIT:
Try supplying the absolute path of your url:
$.ajax({
type: "GET",
url: "http://fridgetofood.com/visitors/hide_welcome",
success: function(data){
$("#welcome").hide(0);
e.preventDefault();
}
});