php 5.5 to 5.6 Breaks jQuery - javascript

I'm trying to update an old program someone else wrote that runs on php 5.5.38. I prefer to upgrade the old program because it's a highly customized eCommerce program with features/functions not normally found in eCommerce software. My goal is to get to php 7 then php 8.
When changing to php 5.6.40, some jQuery code no longer works. Not all broke but some did.
I see no server errors.
Here is one issue. When you click the tag, a popup window with a form should appear.
php 5.6 won't show the popup window.
The "alert" shows up, but the popup window doesn't.
<script type = "text/javascript">
//<![CDATA[
jQuery(document).ready(function () {
jQuery('#emailsomeone').click(function () {
alert("I am here");
return ajaxPopUpURL({
'divtitle': 'Email a Friend',
'divid': 'emailsomeone',
'app': 'ecom',
'ns': 'emailsomeone',
'ref': 'thispage'
});
});
...
and the html ...
<a id="emailsomeone" href="https://example.com/thepage.html">Email someone</a>
It uses
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
I tried upgrading jQuery to this and it doesn't help. (There were some console errors for other code, but none appeared to be from this code.).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
Here's the ajaxPopUpURL
function ajaxPopUpURL(params) {
// Check to see if the required params are defined. If not, exit.
if (!params.app || !params.ns || !params.divid || !params.divtitle || jQuery('#' + params.divid).length == 0) {
return false;
}
// Reset window timeout.
if (window.mytimeout) {window.clearTimeout(window.mytimeout);}
// Hide any popup we might have launched already.
if (jQuery('#' + params.divid).data('qtip')) {
jQuery('#' + params.divid).qtip('hide');
} // end if
// Get our params into a form object and issue the request.
var formobj = new Object();
formobj.object = {};
jQuery.each(params, function(key,value) {
formobj.object[key] = value;
});
params.ajax_request = {'ajaxPopUpURL': formobj.object};
postAJAX({'callback': 'ajaxPopUpURLResult', 'callbackparams': params, 'async': true});
return false;
} // end ajaxPopUpURL
Here is postAJAX
function postAJAX(params) {
// Submit AJAX to the system.
if (!params.callback || !params.callbackparams) {return false;}
// Post the info and return the result to the callback function.
jQuery.ajax({'type': 'POST',
'url': thisURL,
'data': {'app': 'core', 'ns': 'ajaxrequest', 'sid': thisSID, 'ajax': 1, 'ajax_request': jQuery.toJSON(params.callbackparams.ajax_request)},
'success': function(data) {params.callbackparams.ajax_response = data; window[params.callback](params.callbackparams);},
'error': function(data) {params.callbackparams.ajax_response = 'ERROR: Failed jQuery ajax request.'; window[params.callback](params.callbackparams);},
'dataType': 'text',
'async': params.async,
'cache': false});
} // End postAJAX
Thank you. Any help would be great.

ANSWER: Replaced outdated PEAR with json_decode or json_encode.
Thank you Barmar:)

Related

Including javascript file along with ajax response

I've got a dropdown that runs AJAX each time an option is selected. The ajax call returns HTML markup (buttons and text boxes) and a script tag, which the HTML(buttons) uses to submit to a database via ajax.
<html>
<head>........</head>
<body>........</body>
<select class="chooseOption">
...
...
</select>
<div class="ajaxResult">
<!-- after successful ajax -->
<!-- HTML Markup here -->
<!-- I'm having to include main.js here again so that HTML matkup can use AJAX -->
</div>
....
....
....
<footer> //include main.js </footer>
This arrangement seems to work fine only that, there's an exponential call to main.js each time an option is selected.
Doing something like this(below) doesn't seem to work, I'm guessing because AJAX is injected into the page and isn't aware of what scripts that are already available on the page?
<script>
var len = $('script').filter(function () {
return ($(this).attr('src') == 'main.js');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
var url = "main.js";
$.getScript(url);
}
</script>
Is there a simple way around this? To make sure that main.js works across all AJAX requests without having to include it with each request?
Sample main.js content.
Ajax snippet that populates the HTML Markup (buttons and textboxes)
$("#students").on("change", function (e) {
e.preventDefault();
var supervise = this.value;
var faculty = $("#faculty").val();
$.ajax({
method: "POST",
url: 'URL',
dataType: 'html',
data:
{
selectValue: supervise,
faculty: faculty
},
success: function (result) {
$("#ajaxResult").html(result);
}
})
});
When #statement_button from HTML markup returned from select dropdown is clicked
$('#statement_button').click(function (e) {
var student_statement = $("#student_statement").val();
if (student_statement == '') {
alert('Please enter your statement');
return false;
}
var student = $("#student").val();
var statement_button = $(this).attr("value");
$.ajax({
type: "POST",
url: formsUrl,
dataType: 'text',
data:
{
student_statement: student_statement,
student: studentusername,
statement_button: statement_button
},
success: function (result) {
$("#result").text(result);
$("textarea#student_statement").val('');
}
})
});
From the code you posted it looks like you can just delegate the button handling to the .ajaxResult element which is always present in the html (from the initial load).
So just changing how you bind your button handlers should be enough
$("#students").on("change", function (e) {
to
$('.ajaxResult').on('change', '#students', function (e) {
$('#statement_button').click(function (e) {
to
$('.ajaxResult').on('click', '#statement_button', function (e) {
etc..
So the script with the above code is run once in the initial load of the page (in a $(document).ready(..))

Delete / Destroy using a link and Laravel 5

I could have sworn I had this working at one point but now I'm pulling my hair out trying to figure out why it won't. I found this great script which inserts a hidden form next to a delete link and then submits the form with the necessary token. I posted a message on the git site but no response.
I've set it up exactly as it suggests and looking through the DOM I can see the form is there, inserted. I've done some alerts to make sure it sees the token correctly but every time I get:
TokenMismatchException in VerifyCsrfToken.php line 46:
If I put an old standard Laravel delete form it works fine, I just can't seem to get this script to work like it should. No other javascript errors or issues that I can find.
Here's the script with the code at the top that I added to my page:
<a href="posts/2" data-method="delete"> <---- We want to send an HTTP DELETE request
- Or, request confirmation in the process -
<a href="posts/2" data-method="delete" data-confirm="Are you sure?">
Add this to your view:
<script>
window.csrfToken = '<?php echo csrf_token(); ?>';
</script>
<script src="/js/deleteHandler.js"></script>
*/
(function() {
var laravel = {
initialize: function() {
this.registerEvents();
},
registerEvents: function() {
$('body').on('click', 'a[data-method]', this.handleMethod);
},
handleMethod: function(e) {
var link = $(this);
var httpMethod = link.data('method').toUpperCase();
var form;
// If the data-method attribute is not PUT or DELETE,
// then we don't know what to do. Just ignore.
if ( $.inArray(httpMethod, ['PUT', 'DELETE']) === - 1 ) {
return;
}
// Allow user to optionally provide data-confirm="Are you sure?"
if ( link.data('confirm') ) {
if ( ! laravel.verifyConfirm(link) ) {
return false;
}
}
form = laravel.createForm(link);
form.submit();
e.preventDefault();
},
verifyConfirm: function(link) {
return confirm(link.data('confirm'));
},
createForm: function(link) {
var form =
$('<form>', {
'method': 'POST',
'action': link.attr('href')
});
var token =
$('<input>', {
'name': '_token',
'type': 'hidden',
'value': window.csrfToken
});
var hiddenInput =
$('<input>', {
'name': '_method',
'type': 'hidden',
'value': link.data('method')
});
return form.append(token, hiddenInput)
.appendTo('body');
}
};
laravel.initialize();
})();
As haakym suggested, one solution is Unobtrusive JavaScript. While implementing that I realized I had an old version of a delete handler in another js file that was conflicting with my deleteHandler.
As usual many ways to achieve the same solution. Thanks for the input haakym.

Foundation Form in Reveal Modal - Abide Validation Events not firing

I'm working on a login/registration for a simple web app. I'm using Foundation to do so. The index page shows a login screen and a register button, if the user clicks this a Reveal Modal appears which includes the register form. This form uses abide to do the data validation (email address, matching passswords etc.). I want the 'register' submit button to be disabled if there are any validation errors and then not disabled when everything is good.
I have used the code on the Foundation Docs where it says:
$('#myForm')
.on('invalid.fndtn.abide', function () {
var invalid_fields = $(this).find('[data-invalid]');
console.log(invalid_fields);
})
.on('valid.fndtn.abide', function () {
console.log('valid!');
});
For some reason (that I can't find after much searching) these events aren't firing. My form has the correct ID, my js file is loading correctly (I put console.log messages either side of that jquery code) and I've tried calling:
$(document).foundation('abide','events');
as suggested here. But I'm still not getting any events.
Any ideas? Could it be because I've got it in a modal or something?
Thank you for your time.
EDIT: I found this page here which says to add:
$('#your_form_id').foundation({bindings:'events'});
instead of:
$(document).foundation('abide','events');
But that doesn't seem to change anything either.
Try using $.getScript after loading the form to run the javascript.
eg:
$('#myModal').foundation('reveal', 'open', {
url: 'form.html',
close_on_background_click:true,
success: function(data) {
$.getScript( "form.js", function() {});
}
});
I had the same problem with fancybox and ajax check before submit.
This is my solution that works for sure
<form id="my_form" action="...." method="POST" class="popup" data-abide="ajax">
<input type="text" name="check_this_field_with_ajax" id="check_this_field_with_ajax">
....
</form>
<script type="text/javascript" src="..../js/foundation.min.js"></script>
<script type="text/javascript" src="..../js/foundation/foundation.abide.js"></script>
<script type="text/javascript">
$('#my_form')
.on('invalid.fndtn.abide', function() {
console.log('NOT Submitted');
})
.on('valid.fndtn.abide', function() {
console.log('VALID');
})
.on('submit', function(e) {
var ajaxRequest = $.ajax({
type: 'GET',
url: "....",
data: {xxx: yyy},
cache: false,
dataType: 'json',
});
....
ajaxRequest.done(function() {
if (ok) {
$('#check_this_field_with_ajax').parent().removeClass('error');
$('#my_form').attr({'submit_this_form': 'yes'});
$(document).foundation('abide', 'reflow');
$('#my_form').trigger('submit.fndtn.abide');
}
});
}
</script>
in foundation.abide.js search line "validate : function (els, e, is_ajax) {" and add:
if (
is_ajax &&
form.attr('submit_this_form') === 'yes'
) {
return true;
}
before
if (is_ajax) {
return false;
}

Result of expression '$.mobile' [undefined] is not an object

I'm new in jquery mobile,and i develop a mobile application with jquery mobile and phoneGap and localstorage Html , i want to save an input value in page.html and then i will then retrieve this value withlocalstorage.getitem and used in a URL, My problem when I add this line value=localStorage.getItem('myStorage'); I can not connect to my app and I got this error :
Result of expression '$.mobile' [undefined] is not an object. at
file:///android_asset/www/js/application.js:258
this is my application of saving the input value
application.js
function setMessage() {
var firstName=document.getElementById('addresseip');
alert("Hello " + firstName.value + ", hope you like JavaScript functions!")
localStorage.setItem('myStorage', firstName.value);
}
and this is my call to this value in the same page .js, the input vaule is an param.html and the call to this value is in index.html :
function showUser(){
value=localStorage.getItem('myStorage');
val1 = document.getElementById("name").value;
val2 = document.getElementById("pass").value;
if (val1=="")
{
showdialog("Verifiez login et mot de passe","Erreur");
}
else{
alert("test"+value);
$.mobile.showPageLoadingMsg();
var geturl;
geturl = $.ajax({
url:"https://"+value+":80/B/authenticate",
//url:"https://10.0.2.2:80/B/authenticate",
dataType:"json",
timeout:10000000,
cache:false,
type:'GET',
beforeSend : function(req) {
req.setRequestHeader('Authorization',
make_base_auth (val1, val2));
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
$.mobile.hidePageLoadingMsg();
showdialog("Verifiez login et mot de passe","Erreur");
},
success:function(results) {
if(results==true){
$.mobile.changePage("bienvenu.html","fade");
$.mobile.hidePageLoadingMsg();
}
My error is an line $.mobile.showPageLoadingMsg();
Can you please help me,
Thanks
Except loading jQuery you should also include jQM. Make sure also that your code that uses jQM is included after it.
<script src="//code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script src="yourscripts.js"></script>
or
<script src="//code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script>
/* Your code here */
</script>
Since $.mobile is undefined, I guess that the jquery mobile library is not loaded. Check that you have loaded jquery and jquery mobile before calling showUser().

How to use jQuery Validation plugin with form-level server-side validation?

What's the best way to trigger errors on elements for server-side validation errors that come back after the form passes the initial client-side validation?
$("#contact_form").validate({
submitHandler: function(form) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/contact/send',
data: $(form).serialize(),
success: function(response) {
if(response.error) { //server came back with validation issues
var fields = response.fields;
for(var i=0, var len = fields.length; i < len; i++) {
var field_name = fields[i].name;
var field_error = fields[i].error;
// TRIGGER ERROR ON AFFECTED ELEMENT
}
return false;
}
//everything went ok, so let's show a thanks message
showThanks();
}
}
});
I'm thinking something like:
$(form).find("[name='" + field_name + "']").triggerError(field_error);
But I didn't see any api methods for manually triggering errors in that manner.
I think I figured it out from the documentation of Validator/showErrors
var validator = $("#contact_form").validate();
validator.showErrors({"state": "Bad state."});
Make it. Write a plugin that will do whatever you want.
Or if you get to complicated, simply write a javascript function to do it and call that.
I would write a plugin that would create a div, fill it with the error text and animate it nicely.
On submit of the form, I would make the target of the form an invisible iframe on the page which would then call a function in the topWindow with it's result.
<iframe id="subject_frame" name="submit_frame" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
then in the page in the iframe call a javascript method in the top window that either redirects on success or displays the errors.
In the iframe
<script language="javascript" type="text/javascript">
window.top.window.submitComplete("<?php echo $response; ?>");
</script>
In the top window (as an example)
function uploadComplete( result ){
$.unblockUI();
if(result == "OK"){
$.blockUI({ message: "<span style='color:green;'>File upload successful, request submitted.</span><br/><br/>Redirecting..." });
setTimeout(function() {
$.unblockUI({
onUnblock: function(){ window.location='thankyou.php'; }
});
}, 2000);
} else {
$.blockUI({ message: "<span style='color:red;'>Failed.</span><br/><br/>"+result });
$('.blockOverlay').attr('title','Click to remove').click($.unblockUI);
}
}

Categories