Reputation: 329
I have an ajax function that submits some data to my PHP file. In my PHP file I have some checks that it does with that data, I then try to make an alert to come up to say something. I can't get any alerts to come up though. All that happens is in the console->network->submit.php->response shows the javascript that should make the alert.
This is my Ajax, which I know works:
$('#submit').click(function() {
if(selectedImageArray.length <= 10){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray}
}).done(function( msg ) {
//alert( "Data Saved: " + selectedImageArray );
}); }else{
alert( "You can only trade up to 10 items at once." );
}
});
Then in submit.php I do some checks, and have this:
if($QueueCount == 1){
Echo '<script language="javascript">';
Echo 'alert( "You already have an active trade, check your Steam profile.");';
echo '</script>';
}else{
Echo '<script language="javascript">';
Echo 'alert("You are currently in the trade Queue, you should receive a trade request soon.");';
echo '</script>';
}
This should make an alert, but it just outputs <script language="javascript">alert( "You already have an active trade, check your Steam profile.");</script>
into the network tab, like I said.
How can I make this work to make an alert pop-up from the PHP file?
Upvotes: 1
Views: 6089
Reputation: 950
You javascript code must look like this:
$('#submit').click(function() {
if(selectedImageArray.length <= 10){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray},
success: function(data,status){
eval(data)
}
});
}else{
alert( "You can only trade up to 10 items at once." );
}
});
And your php code should not declare script tags:
if($QueueCount == 1){
echo 'alert( "You already have an active trade, check your Steam profile.");';
}else{
echo 'alert("You are currently in the trade Queue, you should receive a trade request soon.");';
}
Make sure that this is the only output from your php file.
Also this code also needs several improvements before go to production, such as callback to error on server-side processing, check if ajax didn't fail at all due to network issues and XSS protection, to list a few.
Upvotes: 1
Reputation: 1126
You're trying to output javascript from the php, without outputting it in your ajax callback, won't work.
The easiest way to do what you want, is to return the string with your php, and handle the outputting to your javascript.
something like :
if($QueueCount == 1){
Echo "You already have an active trade, check your Steam profile.";
}else{
Echo "You are currently in the trade Queue, you should receive a trade request soon.";
}
and for the javascript
$('#submit').click(function() {
if(selectedImageArray.length <= 10){
$.ajax({
method: "POST",
url: "submit.php",
data: {selectedImageArray: selectedImageArray}
}).done(function( msg ) {
alert(msg);
});
}else{
alert( "You can only trade up to 10 items at once." );
}
});
Upvotes: 2