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
Related
I'm new to PHP and jQuery, so I have doubt when declaring PHP data in JSON format with AJAX.
I don't know how to receive the JSON data again and place it inside a PHP variable.
Here's my current attempt:
<?php
$id = $_GET['id'];
?>
function load_topic()
{
$.ajax({
url:"fetch_topic.php",
method:"POST",
data:{
tpid :"<?php print $id; ?>"
},
dataType:"JSON",
success:function(data)
{
$('#display_topic').html(data);
}
})
}
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
data:{
"tpid" :"<?php print $id; ?>"
},
dataType:"JSON",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
I assume you want to retrieve the tpid which you pass with ajax in your files fetch_comment.php and fetch_topic.php.
To do this, you simply use
$tpid = $_POST['tpid'];
This retrieves the 'tpid' which was send via the ajax post request and stores it in the variable $tpid.
Source: http://php.net/manual/en/reserved.variables.post.php
check by inspecting in browser under network that it is sending data or not?
if it is sending the data using method post
then in php file where you are receiving data use
print_r($_POST);
if it print something in and it is showing in json try print_r(json_decode($_POST));
There's a few issues with your post, here:
1/ It's not clear what JSON data you are returning from fetch_topic.php and fetch_comment.php. Your code is fine, but without knowing what JSON data you are returning from those pages, it's difficult to help.
2/ The function that handles the response is a bit odd in that it will print the raw JSON data to those elements. If you want to process the JSON a bit better, i suggest something like this:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data:{
"tpid" :"<?php print $id; ?>"
},
dataType:"JSON",
success:function( response )
{
if ( response.status == 'success' ) {
$('#display_comment').html( response.html );
} else {
// handle your error here.
}
}
});
and your fetch page responds with:
{"status":"success","html":"<p>Here is an HTML response!<\/p>"}
or not use JSON and just return html from your fetch pages:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data:{
"tpid" :"<?php print $id; ?>"
},
dataType:"HTML",
success:function( response )
{
$('#display_comment').html( html );
}
});
A little more clarity in your request would be super helpful.
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...
}
});
}
I'm sure this has been asked many times but I couldn't find the answer after quite a bit of searching.
I have a simple jquery ajax request to get some data for a particular string as follows:
$.ajax(
{ url: "/getval.php?title="+encodeURIComponent(title),
dataType:"json",
success: function(data) { console.log(data) }
});
The php script is using:
$title = urldecode($_GET["title"]);
to get the value from the get request.
It doesn't need to work for every conceivable string but I do need it to work for a string with a single quote. What is the safest (and easiest) way to do this request and handle the request in php?
Thanks in advance,
Steve
Why hard way?
jQuery:
$.get("/getval.php", { title: 'your title' },
function(data){
console.log(data);
}
);
PHP:
<?php
$title = $_GET['title'];
Please always read manual first:
http://api.jquery.com/jQuery.get/
You just need to set the data attribute, and PHP will get the value from the $_GET array:
$.ajax(
{ url: "/getval.php",
dataType:"json",
data: { title: 'the title' },
success: function(data) { console.log(data) }
});
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.
i want to send a php variable $thread_id to php file using jquery ajax, so the php file can get all posts for $thread_id and echo it back to main file.
it doesnt work when i type:
$.get("ajaxcall_reply.php", thread_id: $thread_id, function(data) {
$("#threads").html(data);
});
how should i type?
Do you know what $thread_id is outputting? Try putting it into a variable of its own and looking at the output before putting it in the get function. It might have symbols or things that are messing up your javascript syntax. Do you have an example output? Additionally the get method returns the XMLHttpRequest object (data) so you might want to look into setting the type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".
Try this:
$.get("ajaxcall_reply.php", {thread_id: $thread_id}, function(data) { $("#threads").html(data); });
<script>
$.get(url, { get_var: '<?php echo $phpvar ?>' }, function(data) { alert(data); });
</script>
at the URL:
<?php
echo $_GET['get_var'];
?>