How to trigger ajax call based on url - javascript

I am building coupon website. I need to trigger ajax action based on url of page. Let me explain.
For example, if user goes to page website_url/?coupon_id=99 - he gets page website_url and popup with ajax action inside it (ajax gets data for coupon post type with id=99 and show it's values).
If user goes to page website_url/page1/?coupon_id=99 - he gets page website_url/page1/ and the same popup.
You can see this logic in action on some coupon websites, for example, coupondunia.in
I created ajax action, it's working
function coupon_get_code(){
$couponid = $_GET['couponid'];
$code = get_post( $couponid );
if( !empty( $code ) ){
$offer_coupon = get_post_meta( $code->ID, 'coupon', true );
$response .= '<div class="coupon_modal_coupon">'.$offer_coupon.'</div>';
}
else{
$response = __( 'Offer does not exists', 'textdomain' );
}
echo $response ;
die;
}
add_action('wp_ajax_ajax_code', 'coupon_get_code');
add_action('wp_ajax_nopriv_ajax_code', 'coupon_get_code');
Currently I made triggering ajax action based on click, like this
// Coupon Modal
$( '.offer_coupon.masked_coupon:not(.expired_coupon)' ).live("click", function(e){
var $this = $(this);
var couponid = $this.data('couponid');
$.pgwModal({
url: translation.ajax_url + "?action=ajax_code&couponid=" + couponid,
titleBar: false,
ajaxOptions : {
success : function(response) {
if (response) {
$.pgwModal({ pushContent: response });
} else {
$.pgwModal({ pushContent: 'An error has occured' });
}
}
}
});
});
But how to trigger this ajax request based on url?

You could get the last number characters from the URL on page load (equal to the coupon id), instead of getting it on click from the data attribute.
$(window).on('load', function() {
// Get the last numbers from the current page URL using Regex
var couponid = window.location.href.match(/\d+$/);
$.pgwModal({
url: translation.ajax_url + "?action=ajax_code&couponid=" + couponid,
titleBar: false,
ajaxOptions : {
success : function(response) {
if (response) {
$.pgwModal({ pushContent: response });
} else {
$.pgwModal({ pushContent: 'An error has occured' });
}
}
}
});
});
Put the jQuery in a file named ajax-coupon.js and conditionally enqueue the script.
// Conditionally enqueue your script only if the template coupons.php is used to display the page.
function my_scripts_method() {
// Register your script location, dependencies and version
wp_register_script('ajax-coupon', get_template_directory_uri() . '/js/ajax-coupon.js', array('jquery'), '1.0' );
// Check if the current page is using coupons.php, if so, load the script.
if ( is_page_template( 'coupons.php' ) ) {
wp_enqueue_script('ajax-coupon');
}
}
add_action('wp_enqueue_scripts', 'my_scripts_method');

I think I found function which can help me. Testing now.
function GetURLParameter(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
So my ajax trigger can be like this
var coupontrigger = GetURLParameter("couponid");
if(coupontrigger){
$.pgwModal({
url: translation.ajax_url + "?action=ajax_code&couponid=" + coupontrigger,
titleBar: false,
ajaxOptions : {
success : function(response) {
if (response) {
$.pgwModal({ pushContent: response });
} else {
$.pgwModal({ pushContent: 'An error has occured' });
}
}
}
});
};

Related

ajax not saving my inputs in form after reloading the page

I am trying to use Ajax that will keep
the inputs that the user has entered but for some reason, it isn't working.
In case of an error, my controller redirects the view with the data of errors,
however, after the page is uploading the form is empty.
I am using the MVC model of Codeigniter.
$("#save").click(function () {
var tnum1 = $("#tnum1").val();
var tnum2 = $("#tnum2").val();
var tnum3 = $("#tnum3").val();
var loc = $("#loc").val();
var dine = $("#dine").val();
var date = $("#date").val();
var time = $("#time").val();
var phone = $("#phone").val();
var fullname = $("#fullname").val();
$.ajax({
type: 'POST',
url: "<?php echo site_url(); ?>" + "/hosting/create",
data: {tnum1:tnum1, tnum2:tnum2, tnum3:tnum3, loc:loc, dine:dine,
date:date, time:time, phone:phone, fullname: fullname},
error: function () {
alert( "Load was performed.");
},
success: function (data) {
if (data === "") {
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else {
$("#error").html(data);
}
}
});
});
Controller
public function create() {
$newDate = date("Y-m-d",strtotime($this->input->post('re_date')));
$newTime = date("H:i", strtotime($this->input->post('re_time')));
$data = array(
'num' => $this->input->post('num'),
'location' => $this->input->post('location'),
'diners' => $this->input->post('diners'),
're_date' => $newDate,
're_time' => $newTime,
'phonenumber' => $this->input->post('phonenumber'),
);
$dataclient = array(
'fullname' => $this->input->post('fullname'),
'phonenumber' => $this->input->post('phonenumber'),
);
$error = $this->validation($data,$dataclient);
if ($error) {
$data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.'');
redirect(base_url("/hosting/tableMap"));
} else {
$this->Hosting_model->form_insert($data, $dataclient);
}
}
If you redirect the controller then it will not retain the previous values. Instead save the error in a variable and return it to ajax function.
That is the whole point of ajax - to not redirect or reload a page ie do the task asynchronously.
remove this line-
redirect(base_url("/hosting/tableMap")); // redirecting on error
then in your controller
if ($error) {
// data['error'] = $this->session->set_flashdata('error','<b><u>Failed! </u></b>'.$error.''); // remove this as page will not reload, flashdata wouldn't work
// redirect(base_url("/hosting/tableMap"));
$ajax_data['error'] = 1; // if error exists then value
$ajax_data['validation_error'] = $error;
} else {
$this->Hosting_model->form_insert($data, $dataclient);
$ajax_data['error'] = 0; // if error doesn't exist then value
}
return json_encode($ajax_data); // or echo json_encode($ajax_data);
Now, to prevent default action of form submission that is to redirect page use
$("#save").click(function (e) {
e.preventDefault();
// rest of your code
then in your ajax success:
if (data.error == 0) { // no error
window.location.href = "<?php echo site_url('hosting/tableMap'); ?>";
}
else { // error
$("#error").html(data); // do whatever you want to do with error
// errors can be retrieved from "data.validation_error" -- it will be an array probably sp you'll have to loop through each element
}

Return value from Ajax call into Javascript function

I am sending data to a PHP script using an Ajax call, and I intend to use the Ajax return value in a Javascript function.
I have tried using return $.ajax({}) and it doesn't work. I also tried registering a callback function in my Ajax call, and that didn't work as well. Is there something am not doing right here?
function click_to_showResult() {
var score;
if (userName !="") {
var result = getResultData();
//display result for selected user
if (result == "Distinction") {
score ="A";
} else if (result =="Pass") {
score ="C";
} else {
score ="User has no result in DB";
}
}
alert(score);
}
function getResultData(callback) {
var data;
var userName = $.trim($("#user").val().toLowerCase()); //gets username input from the user
$.ajax({
type:"POST",
url : "getResult.php",
data: {'name':user},
success: function(resp) {
data = resp;
},
error: function(resp) {
alert('Error occured');
}
});
return data;
}
Let's say the user inputs Mike, then it should send the variable to PHP and get the results for Mike (for instance Pass), then alert C.
You should use the callback like this.
function click_to_showResult() {
var userName = $.trim($("#user").val().toLowerCase()); //gets username input from the user
if (userName != "") {
getResultData(userName, function (err, result) {
if (err) { console.log(err); return; }
var score;
//display result for selected user
switch (result) {
case "Distinction":
score = "A";
break;
case "Pass":
score = "C";
break;
default:
score = "User has no result in DB";
}
alert(score);
});
}
}
function getResultData(userName, callback) {
$.ajax({
type: "POST",
url: "getResult.php",
data: { 'name': userName },
success: function (resp) {
callback(null, resp);
},
error: function (resp) {
callback('Error occured');
}
});
}
If I understood correctly then you could perhaps rewrite the above code like this - the callback will process the response and alert the user. One issue I spotted after making the above comment was the data you send was user but this does not appear to be defined within the function - I suspect you intended userName?!
const click_to_showResult=function(e){
let userName=$.trim( $('#user').val().toLowerCase() );
if( userName!='' ){
/* callback function to process the response data */
const gradecallback=function( r ){
let score;
switch( r ){
case 'Distinction':score='A';break;
case 'Pass':score='C';break;
default:score='User has no result in DB';break;
}
alert( score );
};
$.ajax({
type: 'POST',
url : 'getResult.php',
data: { 'name':userName }, /* previously supplying user rather than userName */
success: function( resp ){
gradecallback.call( this, resp );
},
error: function(resp){
alert('Error occured');
}
});
}
}
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/*
do db lookup or whatever tasks the getResults.php
script actually does and send the response.
For the purposes of the demo send back some data
which might or might not reflect the actual data
from getResult.php...
Open the console to view output
*/
$name=$_POST['name'];
$score=mt_rand(0,100);
if( $score >= 75 )$grade='Distinction';
elseif( $score > 50 && $score < 75 )$grade='Merit';
elseif( $score > 40 && $score < 50 )$grade='Pass';
else $grade='Fail';
$payload = json_encode( array( 'name'=>$name, 'score'=>$score, 'grade'=>$grade ) );
/*
sleep is used ONLY to indicate that this backend process MIGHT take some time to perform ALL
the actions that are done by getResult.php
*/
sleep( 2 );
exit( $payload );
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
document.addEventListener('DOMContentLoaded',e=>{
let SCORE=false;
/* AJAX function bound with a promise to send POST requests only */
const ajax=function(url,params){
return new Promise( function( resolve, reject ){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 ){
/*
The request has completed and the response is available.
Resolve the Promise with the response data
*/
resolve( this.response )
}
};
xhr.onerror=function( error ){
reject( error )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
xhr.send( params );
});
};
const alt__click_to_showResult=function(){
/*
asynchronous functions do not necessarily complete in the order
you would imagine like a standard synchronous function does
which is why returning a value from them is harder
*/
console.info('called before asynchronous request bound in a Promise');
let url=location.href;
let params='name='+document.getElementById('user').value;
ajax( url, params ).then(
res=>{
/* The Promise has been resolved */
console.info('The asynchronous request has now completed - trigger ajax callback');
return ajax_callback( res );
}
).then(
/* this is the value returned by the ajax_callback */
res=>{
console.info( 'The ajax callback returned this data: %o',res );
return true;
}
).then(
res=>{
alert( 'all done....'+res )
}
).catch(
/* For some reason the promise was rejected*/
e=>{ alert(e) }
)
console.info( 'After asynchronous request' );
};
/* do something with the data */
const ajax_callback=function(res){
SCORE=JSON.parse( res );
console.info( 'The user "%s" scored %s which is a grade "%s"', SCORE.name, SCORE.score, SCORE.grade )
/* modify the data to indicate that it has been intercepted and processed - only to show flow of data*/
SCORE.banana='yellow';
return SCORE
};
/* a slightly modified version of previously posted function */
const click_to_showResult=function(e){
let userName=$.trim( $('#user').val().toLowerCase() );
if( userName!='' ){
/* callback function to process the response data */
const gradecallback=function( r ){
let json=JSON.parse( r );// process JSON response rather than plain text as before
let score;
switch( json.grade ){
case 'Distinction':score='A';break;
case 'Merit':score='B';break;// added this...
case 'Pass':score='C';break;
default: score='User has no result in DB';break;
}
alert( 'User: '+json.name+' Scored: '+json.score+' Award: '+json.grade+' Grade:'+score );
};
$.ajax({
type: 'POST',
url : location.href, // "getResult.php"
data: { name:userName }, /* previously supplying user rather than userName */
success: function( resp ){
gradecallback.call( this, resp );
},
error: function(resp){
alert('Error occured');
}
});
}
}
document.querySelector( 'form > input[type="button"][name="std"]' ).addEventListener( 'click', click_to_showResult )
document.querySelector( 'form > input[type="button"][name="alt"]' ).addEventListener( 'click', alt__click_to_showResult )
});
</script>
</head>
<body>
<form method='post'>
<input type='text' name='user' id='user' value='geronimo' />
<input type='button' name='std' value='Click to show results' />
<input type='button' name='alt' value='Alternative - Click to show results' />
</form>
</body>
</html>

same ajax call several times before close popup

I have more than 4 forms which has different name and id in my page and i create loop function to post every form with ajax.and loop work every form posting ın order.
Problems:
1-gives me error like
"Uncaught TypeError: Cannot read property 'location' of null"
2-sometimes window.close work at first click(usually on local computer) sometimes not (usually at remoteserver) probably ajax calls interrupt closing
This is my script
<script name="ajax fonksiyonları" type="text/javascript">
function validate(form){
var formID = form.id;
var formDetails = $('#'+formID);
$.ajax({
type: "POST",
url: 'ajax.php',
data: formDetails.serialize(),
success: function (data) {
console.log(data);
window.opener.location.reload();
window.close()
},
error: function(jqXHR, text, error){
// Displaying if there are any errors
console.log(error);
}
});
return false;
}
function submitAll(){
for(var i=0, n=document.forms.length; i<n; i++){
validate(document.forms[i]);
}
}
This is ajax.php
FUNCTION mysql_update_array($table, $data, $id_field, $id_value) {
$data=data_cleaner($data);
FOREACH ($data AS $field=>$value) {
$fields[] = SPRINTF("`%s` = '%s'", $field, MYSQL_REAL_ESCAPE_STRING($value));
}
$field_list = JOIN(',', $fields);
$query = SPRINTF("UPDATE `%s` SET %s WHERE `%s` = %s", $table, $field_list, $id_field, INTVAL($id_value));
if( mysql_query($query) ) {
return array( "mysql_error" => false,
"mysql_insert_id" => mysql_insert_id(),
"mysql_affected_rows" => mysql_affected_rows(),
"mysql_info" => mysql_info()
);
} else {
return array( "mysql_error" => mysql_error() );
}
}
if (isset($_POST['hupdate'])) {
$result=mysql_update_array("customers", $_POST, "c_id", $_POST['c_id']);
}

Ajax success and error

I am using Ajax to post the results from a php form to a database using an API. However when the script runs, I am not getting anything in return stating that it was a success or an error. I can log into the database and see that it has added the entry but I am not getting an alert when it saves to the database.
What I would like the script to do is:
-First save to the database (Done)
-Second: Alert the user that the operation was completed successfully or error
-Third: reset the values in the form if success, keep values if error
Here is what I have tried and have so far:
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
$('form#directory-create').on('submit', function (e) {
//stops the submit action
e.preventDefault();
//format the data into javascript object
var data = $(this).serializeArray();
//calls function to create record, passing participant information as arguments
createRecord(data);
});
function resetStudyInfo() {
//resets all form values to default
$('form#directory-create').find('input:text, input:radio, input:email, input:phone').val('');
return true;
}
function createRecord(data) {
//converts into json data format
var myData = JSON.stringify(data);
console.log(myData);
$.ajax({
//setup option for .ajax func
type: "POST",
url: "directory-create-record.php",
data: {
//user_data : contains all the fields and their data
user_data: myData
},
//shows output message on error or success
success: function () {
showSuccess('Study created successfully, you may now add participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});
PHP side:
require "RestCallRequest.php";
function insertData($data_from_user){
$status = 2;
$url = "xxxx";
$token = "mytokenishere";
$fname = $data_from_user[0]->value;
$lname = $data_from_user[1]->value;
$title = $data_from_user[2]->value;
$school = $data_from_user[3]->value;
$facultystafftrainee = $data_from_user[4]->value;
$email = $data_from_user[5]->value;
$phone = $data_from_user[6]->value;
$record_id = $lname .'_'. $fname;
# an array containing all the elements that must be submitted to the API
$data = "record_id,f_name,l_name,title,school,facultystafftrainee,email,phone,directory_complete\r\n";
$data .= "$record_id,$fname,$lname,$title,$school,$facultystafftrainee,$email,$phone,$status";
$args = array(
'content' => 'record',
'type' => 'flat',
'format' => 'csv',
'token' => $token,
'data' => $data
);
# create a new API request object
$request = new RestCallRequest($url, 'POST', $args);
# initiate the API request
$request->execute();
$result = $request->getResponseBody();
if($result == '1'){
return 1;
}
}
Any help is greatly appreciated. Thank you
When resetting the form values, you have input:email and input:phone, javascript throws a syntax error as you do not need these values, When you remove them your code should work.... Here is the complete working code
$(document).ready(function () {
function showSuccess(message) {
$('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
$('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function resetStudyInfo() {
$('form#directory-create').find('input:text, input:radio').val('');
return true;
}
$('form#directory-create').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray();
createRecord(data);
});
function createRecord(data) {
var myData = JSON.stringify(data);
$.ajax({
type: "POST",
url: "directory-create-record.php",
data: {
user_data: myData
},
success: function () {
showSuccess('Study created successfully, you may now add more participants to this study.');
var reset = resetStudyInfo();
return true;
},
error: function () {
showError('Unable to create the study, did you fill out everything?');
return false;
}
});
}
});

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}

Categories