Tag

Javascript Archives - Custom Web Application Developers in Bromley, London

Laravel ajax calls failing with response code 419

By | Ajax, Laravel, PHP | No Comments

Recently I was working on a Laravel application with some ajax, and I was getting a 419 error after firing an Ajax call to a Laravel controller.

Laravel requires a token to be sent on some types of requests (POST being one of them), this is to prevent Cross site request forgery ( e.g. a form being submitted from somewhere it was intended by the developer to be submitted from ).

In php files its very easy to add this with the function call csrf_field().

But in js files, we need to essentially pull in this you store the token somewhere on the page and use js to pull it in.

you can pop the token in the page somewhere like this:

 

for reference: https://laravel.com/docs/5.5/csrf

 

 

 

 

How to add a form to a shortcode in WordPress (using PHP and Ajax)

By | Ajax, HTML, Javascript, online forms, Wordpress | No Comments

Recently I needed to develop a Shortcode that would display a form, this blog post details what I did. I used Ajax ( which seems the best way to add forms to shortcodes, but I’d welcome any input from other developers on your approach).

So without further ado lets get on with adding a form to a shortcode in WordPress.

We need javascript to handle submission of the form via ajax (this presumes you have jquery available), and handle the response from the server. green_form is the form id.

 

Next we need the php to handle everything else, you could put this in functions.php (or include from functions.php) or put it into a plugin. The shortcode to include the form in our page or post is [shortcode_with_form] 

The code handles:

  • the output of the shortcode
  • the server side processing of the form (I’ve just created a stub in this example ( function do_something_serverside )
  • and the including of javascript file required ( if you’d like to know abit depth on ajax forms in WordPress see my post on that )
 

Hope you find this interesting if you’re looking to add a form to a shortcode.

 

 

 

How to do Ajax in WordPress

By | Ajax, Javascript, Web Design, Wordpress | No Comments

updated 10th Jan 2018

Write a javascript function to trigger the ajax call

Put js above in my_js_file.js (see later in this post).

Wrap in code below for nice loading:

jQuery( document ).ready(function() {    put above code here     });

To see how to send a form via ajax see here.

 

Write a php function to handle the ajax call (you could put this in functions.php)

 

There is one final piece, you might notice the ajax_object.ajax_url in the Javascript function above. We need to make this available in the js file that this function is in. This needs to be done in php.

Include ajax_url like this (below)