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.
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...
}
});
}
I stucked in Yii, with an Ajax call "bug". The problem is, that i have to search by checkboxes, wich are stored in SESSION after hitting the search button.
After this, the keywords inserts into SESSION, and i want to print them in a tag-cloud. (with a cross in the corner -> delete this tag).
The removal of these tags is handled by an ajax call:
$(".tags a").click(function(e) {
e.preventDefault();
var class1 = $(this).attr("class");
var id = $(this).attr("id");
$("#checkbox__"+id).removeAttr("checked");
jQuery.ajax({
url: "recipe/removeFromSession",
type: "POST",
data: "id=" + class1+"&rcp="+id,
dataType: "json",
"success": function(data){
location.reload();
},
"error": function(xhr, status, error) {
var err = xhr.responseText;
alert(xhr.status);
},
"cache" : false,
});
});
It calls the removeFromSession action:
public function actionRemoveFromSession() {
$remove = intval($_POST['id']);
unset($_SESSION['searchItems']['category'][$remove]);
unset($_SESSION['recipeSearch']['category'][$_POST['rcp']]);
echo json_encode($_SESSION);
}
The problem is that it doesn't unsets the value. It's still in the session. Any idea? (sorry for grammar mistakes)
Thanks
You can try this:
Set your session:
Yii::app()->session['searchItems']['category'][$keyword] = "Any string";
To unset session:
unset(Yii::app()->session['searchItems']['category'][$remove]);
I'm currently trying to use the return value of a PHP script to do a refresh action with jQuery. My PHP script is doing what it should do, return the value "reload" when a certain requirement is met; jQuery then however displays "reload" briefly and doesn't act on the refresh action that I've required it to do.
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(output) {
if (output == "reload") {
location.reload();
}
}
});
The PHP that returns the value, when a requirement has been met, looks like this:
echo json_encode("reload");
Also, to make it even more confusing, it sometimes does what it has to do, but it's not consistent at all.
So, am I missing something?
Since I saw this was still open and I managed to fix it myself, I'll post the code so it can/may help others with similar problems.
This was the code that fixed it.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function()
{
$.post('/bidstatus.php',
{
auction_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
function(data)
{
if(data == "reload"){
location.reload();
}
else{
$('#shop-balance').html(data);
}
}
);
}, 1000);
});
Well, try this:
function do_ajax(callback)
{
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(data){
callback(data);
},
});
}
Just check it again and if you use any global scope variable then pass it through function's parameters.
And call it like this::
do_ajax(function(data) {
if (data == "reload") {
location.reload();
}
}
);
What I have done is to set a callback for your .success state, rather than direct code execution. Since Javascript executes the code asynchronously, it just passes the .success before the AJAX is finished, and thus, the data will not be "output" and it is "null" probably. You shoul add a callback there and execute it through a callback to allow the Javascript Interpreter to accomplish the task.
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
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