REST API springboot cannot get the Polymer iron ajax call - ajax

I am trying to send data from the front-end to the back-end.
In Polymer I have
<paper-radio-group selected="{{radioSelected}}">
<paper-radio-button name="one">one</paper-radio-button>
<paper-radio-button name="two">two</paper-radio-button>
</paper-radio-group>
in the JavaScript:
radioSelected: {
observer: '_onSourceChanged'
},
_onSourceChanged: function (newValue, oldValue) {
console.log('New value is ' + newValue);
}
How should I construct an ajax call to connect with the backend?
Note that only the newValue is needed for the backend.

You can use the iron-ajax component, is very easy to use.
https://www.webcomponents.org/element/PolymerElements/iron-ajax
This code goes in the html container.
<iron-ajax
id="myRequestId"
url="http://myurl.com"
method="POST"
content-type="application/x-www-form-urlencoded"></iron-ajax>
This goes in any script function where you want to fire the post request.
this.$.myRequestId.body = JSON.stringify(myBodyParams);
this.$.myRequestId.generateRequest();

Related

How to validate google reCAPTCHA in alpinejs?

I have a AlpineJS signup form with reCAPTCHA I want to validate reCAPTCHA. In google reCAPTCHA we need to pass some callback function for client side validation. Method inside alpine function is not accessible for reCAPCTHA.
<div x-data="alpineFormApp()">
...
Form Input HTML
...
</div>
alpineFormApp = () => {
...
other code
...
validateCaptcha(response){
console.log(response);
}
}
//Captcha callback funtion
function captchaCallbackFn(response){
window.alpineFormApp().validateCaptcha(response);
}

Insert Data Using Ajax

I am using Laravel 5.3. I want to insert the data using blade template.But my when i press submit button it gets refreshed every time. what to do? and please anyone tell me how to use ajax url,type,data
If you try to submit via Javascript make sure prevent form default action with e.preventDefault(). This code prevent the form submitted in a regular way. Just add this code to wrap your AJAX call:
$('#form-id').submit(function(e){
e.preventDefault();
$.ajax({...});
});
I just assume you are using jquery if you are talking about ajax. It's really simple. Your laravel routes listen to "post", "get", "patch", "delete" methods.
Everything of these can be created with a ajax request - example:
$.ajax({
method: "POST",
url: "/posts",
data: { title: "Hello World", text: "..." }
})
.done(function( post ) {
// assuming you return the post
alert(post.title + " created");
});
Now that you use ajax you will not want to return a view to the ajax call. You have different options here (create a new route, helper functions etc.) I will give the most easy example
Controller function:
public function store(Request $request) {
$post = App\Post::create($request->all());
if($request->ajax()) {
return $post;
} else {
return redirect('/posts');
}
}
now you controller will return data on ajax calls and will redirect you on default calls without ajax.
Finally you have a last thing to keep in mind. If you have web middleware applied ( done by default ) you need to handle the csrf token. The most easy way to handle this is by adding a meta tag to your html head
and then (before doing all your calls etc.) add this to configure your ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
this will add the valid csrf token which is in your head to every ajax call and will ensure you not run into token missmatch exceptions.
Things to keep in mind:
- if you stay very long on one page tokens might expire ( laravel-caffeine will help here )
- you need to handle validation for ajax calls

How to make cross application ajax call hosted in same domain

I need to make an ajax call from one application(my-app) to other application(my-web) in the same domain. The ajax call will invoke the controller in my-web.
I made a ajax call like below, but got an error saying
"Ajax call ended in error"
code:
var base = document.URL;
var servletContextPath = base.substr(0, base.indexOf(window.location.pathname)) + "/my-web";
$(document).on("click", ":focus", function () {
$.ajax(servletContextPath + "/ajax/mycall");
});
Both applications are hosted in weblogic like
http://localhost:8090/my-web
http://localhost:8090/my-app
What is the best possible way to do ajax call between applications?
You can provide a relative URL when making an AJAX call.
$(document).on("click", function () {
$.ajax("/my-web/ajax/mycall");
});

Set Session value from JavaScript and Get Session value in C#

Is it available to set the value from javascript(Session / ViewState) and get the value in C# without using hidden field??
Its work to store the value from javascript , and available to get the value in C# (page.request["Token"]) , but its not working for me because there have a postback action " form.submit();"
function setToken(Token) {
try {
var form = document.createElement("form");
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'Token');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} catch (err) {
}
}
If you want to submit a value from your clientside code to your serverside code, you'll need to submit it in some kind of request. A form post would be one way, but if you don't want the page to reload it could equally well be an AJAX request:
function setToken(accessToken) {
$.post('/SetToken', { Token: accessToken });
}
Using jQuery there as it'll save you a lot of the trouble involved in getting AJAX to work the same way across browsers.
In the example I'm posting a request to a page called /SetToken, which could be any url in your website where you have code that can update the token. Your own example submits a form without an action, which means it'll submit to the current page. You could easily do that as well
$.post(location.href, { Token: accessToken });

How to assign div value to php variable using Jquery Ajax call

I have a href tag, in that i wrote onclick func,
<?php the_post_thumbnail('portfolio_thumbs'); ?>
in the onclick() function the code is,
<script type="text/javascript">
function doThumb(temp)
var tempThmb = temp;
document.getElementById("selectedResult").innerHTML=tempThmb;
return tempThmb;
}
</script>
the returned value, im printing it in an empty div.
<div id="selectedResult" name="selectedResult"></div>';
Now my issue is, im getting the result in the empty div, but i have to pass the value of the div to $my_postid.
$my_postid = "Should pass the value here";//This is page id or post id
$content_post = get_post($my_postid);
How can i achieve this do i have to use ajax jquery, kindly help me....
This is not possible in the way you are doing. PHP is server side language and javascript is client side. One way to do this is to send an ajax request at onclick event of your image. And send the id in ajax request. The ajax will get the post on the base of that id and will return you. Then you can show that post content any where.
update after receiving code of questioner
You don't need to do initial operation in your function. Just change it as below.
function doThumb(temp) {
var $mainCats=temp;
alert ($mainCats);
$.ajax ( {
url:"<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
type:'POST',
data:'action=my_special_ajax_callc&main_catidc=' + $mainCats,
onsuccess : function(data) {
$("#selectedResults").removeAttr("disabled");
$("#selectedResults").append(data);
}
} );
}

Resources