Remove alert from a javascript - javascript

I've the below code from a tutorial,i want the action but i just want to remove the alert,
here is the code:
<script type="text/javascript">
setTimeout('read()', 10000);
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post',
function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += "\n\nType: "+response.error.type+"\n\nMessage: "+response.error.message;
}
alert(msg);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
I've tried this:
<script type="text/javascript">
setTimeout('read()', 10000);
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post';
}
</script>
but not worked, thanks

If what you're trying to do is just to ignore the response (remove the alert dialogs):
function read()
{
FB.api('/me/news.reads' +
'?article=<?php echo $fbrdurl ?>&access_token=<?php echo $access_token ?>','post',
function(response) {});
}

If you're not using the alert() function anywhere else, you can simply override it so it does nothing:
window.alert = function() {};

Related

WordPress Ajax Uncaught ReferenceError: url is not defined

I'm having a WordPress template file from where I'm getting the user_id and response_id and passing those to javascript written in same file at bottom. All of the ids are passing properly but only for the url I'm getting error. How can I solve this issue? When I am testing it on local environment it works fine but when I upload it on live server Uncaught ReferenceError: url is not defined and here is the javascript code:
<script>
$(document).ready(function() {
$('#vote-' + <?php echo $response->id; ?>).on('click', function() {
var response_id = "<?php echo $response->id; ?>";
var user_id = "<?php echo get_current_user_id(); ?>";
$.ajax({
url: "<?php echo esc_url(get_stylesheet_directory_uri() . '/Votes.php'); ?>",
method: "post",
data: {
response_id: response_id,
user_id: user_id
},
beforeSend: function() {
},
success: function(response) {
alert('Thanks for your response!');
//location.reload(true);
},
error: function(jqXHR, status, err) {
var msg = '';
console.log(url);
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
alert(msg);
alert('Please try again to cast your vote');
// window.location.href = '/plan';
// $("#claimajaxresponse1").html(jqXHR.status);
console.log(jqXHR.status);
return false;
}
});
});
});
</script>
the url you are consoling is not a variable, remove it or define first.
If you comment out or remove the following line of code, this specific issue will be solved:
console.log(url)

how to pass ajax response value to another page?

I'm trying to send an AJAX response to a PHP file. Based on the response I would like to redirect to another page. If the response is success I would like to redirect to a 'thank you' page along with the parameter data.
How can I pass this transactionId to another page?
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
if (response == "success") {
window.location.href = 'http://www.google.com';
}
});
});
});
change your php output from
if ($result->success)
{
print_r("success!: " .$result->transaction->id);
}
else if ($result->transaction) {
print_r("Error processing transaction:");
print_r("\n code: " .$result->transaction->processorResponseCode);
print_r("\n text: " .$result->transaction->processorResponseText);
}
else
{
print_r("Validation errors: \n");
print_r($result->errors->deepAll());
}
to
if ($result->success)
{
echo json_encode(array('status'=>'success','id'=>$result->transaction->id));
}
else if ($result->transaction) {
echo json_encode(array('status'=>'error','code'=>$result->transaction->processorResponseCode, 'text'=> $result->transaction->processorResponseText)));
}
else
{
echo json_encode(array('status'=>'error','text'=>$result->errors->deepAll()));
}
and change your js to the following
$('#paymentForm').submit(function() {
var serializedData = $(this).serialize();
$.post('card.php', serializedData, function(response) {
// Log the response to the console
console.log("Response: "+response);
alert(response);
var data= $.parseJSON(response);
if (data.status == "success") {
window.location.replace('http://www.google.com?id='+data.id)‌​;
}else{
alert('Operation Failed');
if(data.code){
console.log('response code: '+data.code);
}
console.log('response text: '+data.text);
}
});
});
});
looking at your php code - it never returns success, it will return success!: somthing so this condition if (response == "success") is never true
you could use
if(response.indexOf("success") == 0)
or change the response in the php file
You can send the response variables you'd like by incorporating them into a query on the redirect.
For instance if you wanted to pass on foo to your redirected php domain.com/bar.php:
var url = 'domain.com/bar.php?foo=' + foo
window.location.href = url;
And then on the PHP page, you can use this data:
$bits = parse_url($url);
parse_str($bits['query'], $query);
echo $query['foo']

jQuery .ready() function use in other event

Below is my .ready() function:
$(document).ready(function()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
This function will run when the page load, but I would like to use this function in other event like .click(). Do I need to rewrite the function?
Just create the function with a name, and use it everywhere! Example:
$(document).ready(function(){
function yourFunction(){
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
yourFunction();
$('#element').click(function(){
yourFunction();
});
});
name the function and call that function on your click event.
sample:
<button id='btn'> click me </button>
$(document).ready(function(){
foo();
$("#btn").click(function(){
foo();
});
function foo(){
alert('data');
}
});
JSFIDDLE DEMO
This function will run when the page load, but I would like to use
this function in other event like .click().
Try using array of functions as parameter to .ready() , name first function in array , set named function to property of this:document within first array ; named function should be available at second function within array as property of this:document
$(document).ready([
function fn() {
this.fn = fn;
console.log(this)
},
function() {
$("div").click(this.fn)
}
])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click</div>
First Create a function that will be called on your click event. Please see below example.
$(document).ready(function(){
$("#samplebutton").on("click",function(){
example();
});
function example(){
alert("clicked");
}
});

Trying to call php function with ajax doesn't work

I'm trying to pass some variables to a php file with ajax
$(document).ready(function(){
$("button").click(function(){
var id = this.id;
var name=this.name;
console.log(id+" "+name);
$.ajax({
type: 'GET',
url: 'utility.php',
dataType: 'text',
data: {id: id, name: name},
success: console.log('aa'),
//error: function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown ); },
//complete: alert(id+' '+name)
}); // Ajax Call
}); //event handler
}); //document.ready
<?php
warning('getting something');
if($_GET['id'] && $_GET['name']){
$id=$_GET['id'];
$name=$_GET['name'];
if($id=='delete'){
my_remove($name);
}
if($id=='modify'){
retrieve($name);
my_remove($name);
modify($name);
}
}
else {
warning('unable to get information');
}
function my_remove($name){
warning('deleting');
//mysqli_query($con,"DELETE FROM `book`.`".$page."` WHERE `".$page."`.`name` =\'".$name."\'");
//echo "<script type='text/javascript'>alert('$name');</script>";
}
function modify($name){
warning('modified');
}
function retrieve($name){
warning('fetching');
}
function warning($message){
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
The .js part seems to run smoothly, it sets the name and id as it should and returns a success message, but nothing else happens, not even the alert('getting something') which should run regardless of parameters.
Printing out the data gives [object Object] which I'm not even sure what it means.
Please help!
you're using GET not POST so under the line
if($_GET['id'] && $_GET['name']){
should be get, not post as you have it
$id=$_GET['id'];
$name=$_GET['name'];
since your php script runs in the background with your ajax call, I don't think the alert code in that page will work. Instead try returning the plain text to the ajax function and alert it there
$(document).ready(function(){
$("button").click(function(){
var id = this.id;
var name=this.name;
console.log(id+" "+name);
$.ajax({
type: 'GET',
url: 'utility.php',
dataType: 'text',
data: {id: id, name: name},
}).done(function(text){
alert(text);
}); // Ajax Call
}); //event handler
}); //document.ready
and your php file like this.I changed your warning function
<?php
warning('getting something');
if($_GET['id'] && $_GET['name']){
$id=$_GET['id'];
$name=$_GET['name'];
if($id=='delete'){
my_remove($name);
}
if($id=='modify'){
retrieve($name);
my_remove($name);
modify($name);
}
}
else {
warning('unable to get information');
}
function my_remove($name){
warning('deleting');
//mysqli_query($con,"DELETE FROM `book`.`".$page."` WHERE `".$page."`.`name` =\'".$name."\'");
//echo "<script type='text/javascript'>alert('$name');</script>";
}
function modify($name){
warning('modified');
}
function retrieve($name){
warning('fetching');
}
function warning($message){
echo $message;
}
?>

confirm message when onclick

I want to ask confirm message when onclick
Here is my code:
$('#activate').click(function() {
var url='<?php echo getStoreURL($_REQUEST['key']); ?>admin/email_tracker.php';
var key='<?php echo $data['api_key'];?>'
$.post(url, { key:key, activate:1 } );
alert('Store activated');
location.reload(true);
});
Here I need an alert box are you sure you want to active?. How to do it?. Thanks
Try this,
$('#activate').click(function() {
var url='<?php echo getStoreURL($_REQUEST['key']); ?>admin/email_tracker.php';
var key='<?php echo $data['api_key'];?>'
if(!confirm("Your message")){ return; }
$.post(url, { key:key, activate:1 } );
alert('Store activated');
location.reload(true);
});
PROCEDURAL DEMO
Try this:
$('#activate').click(function() {
var Confirm = confirm("Are you sure?");
if (Confirm == true) {
//put your function here
}
});

Categories