AJAX send post request only once - javascript

I'm having a problem with ajax, as it sends only once my request, i have a cssmap plugin, and that plugin have the option onSecondClick which gives me the ability to do something when i click on it twice, my post request sends some data, to the sessions.php, in session.php i delete session, and then i put one again.
The js lines :
'onSecondClick' : function(e){
var regionName = e.children("A").eq(0).text(),
regionHref = e.children("A").eq(0).attr("href"),
regionClass = e.attr("class").split(" ")[0];
if(regionClass == "eu13" || regionClass == "eu16" || regionClass == "eu47"){
//open model success
$.ajax({
type: "POST",
url: 'session',
data: { country : regionClass },
cache: false,
success: function(data){
$( "#success" ).click();
}
});
//$( "#success" ).click();
}else{
//open model error
$( "#error" ).click();
}
},
PS - the url is right, thats the url of the file, and the session is set, but only once and doesn't upadate.
session.php:
if(Input::get('country')){
$countries = array(
'eu13' => 'france',
'eu16' => 'germany',
'eu47' => 'united kingdom',
//end of playable countries, the rest is bots!
'eu5' => 'belgium',
'eu27' => 'luxembourg',
'eu33' => 'netherlands',
'eu44' => 'switzerland',
'eu20' => 'ireland'
);
if(Session::get('selected');){
Session::delete('selected');
}
Session::put('selected',$countries[Input::get('country')]);
}
On the success, i click a button, which open a "model" from Bootstrap.
everything is ok, but the session always return the previous clicked country, and no matter how much i click other country, it doesn't change.
i've got no idea what the problem is, tried e.preventdefault(), cache: false, and some more options, nothing seems to fix it.

It's hard to tell where the problem lies from your description, but if it's about presentation (i.e. you can verify that session.php does it's job, but still the modal presents the wrong info), this is probably the reason.
Bootstrap modals are only, by default, filled with content once. After that it will use .toggle to show or hide.
If you want to update the information, you'll have to clear it first:
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
This will clear any content from modals with class modal when it hides/closes. You can also use an id selector of course, like #myModal.
edit:
Try this ajax. What does the alert return?
$.ajax({
type: "POST",
url: "session",
data: { "country": regionClass },
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
cache: false,
success: function(data){
alert(data);
$("#success").click();
}
});
And add something like this to the end of your session.php:
echo $countries[Input::get('country')];
(php is not really my thing. I think that's correct though)

Related

Vue js Ready function is not triggered

I have this vue function where there are basically two methods. The first one postStatus is used to save a post just after the user clicks on the save button, and the other one getPosts is used to retrieve all previous posts of that user from the database.
Here is the vue.js, where there is an ajax call to a controller (in Laravel 5.3)
$(document).ready(function () {
var csrf_token = $('meta[name="csrf-token"]').attr('content');
/*Event handling within vue*/
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
posts : [],
token : csrf_token,
limit : 20,
},
methods : {
postStatus : function (e) {
e.preventDefault();
//console.log('Posted: '+this.post+ '. Token: '+this.token);
var request = $.ajax({
url : '/posts',
method : "POST",
dataType : 'json',
data : {
'body' : this.post,
'_token': this.token,
}
}).done(function (data) {
//console.log('Data saved successfully. Response: '+data);
this.post = '';
this.posts.unshift(data); //Push it to the top of the array and pass the data that we get back
}.bind(this));/*http://stackoverflow.com/a/26479602/1883256 and http://stackoverflow.com/a/39945594/1883256 */
/*request.done(function( msg ) {
console.log('The tweet has been saved: '+msg+'. Outside ...');
//$( "#log" ).html( msg );
});*/
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
},
getPosts : function () {
//Ajax request to retrieve all posts
$.ajax({
url : '/posts',
method : "GET",
dataType : 'json',
data : {
limit : this.limit,
}
}).done(function (data) {
this.posts = data.posts;
}.bind(this));
}
},
//the following will be run when everything is booted up
ready : function () {
console.log('Attempting to get the previous posts ...');
this.getPosts();
}
});
});
So far the, first method postStatus is working fine.
The second one is supposed to be called or fired right at the ready function, however, nothing happens. I don't even get the console.log message Attempting to get the previous posts .... It seems it's never fired.
What is the issue? How do I fix it?
Notes: I am using jQuery 3.1.1, Vue.js 2.0.1
I see that you are using Vue 2.0.1. There is no ready method in Vue 2.0 and above.
Here is the link to list of all Vue 2.0 changes: https://github.com/vuejs/vue/issues/2873
As mentioned in the page above, you can use mounted instead of ready.
Not an issue, but just a note: You are mixing jQuery and Vue extensively. If you need jQuery only for http related functions, you may instead use vue-resource - https://github.com/vuejs/vue-resource
EDIT: Update on vue-resource
As pointed out by #EmileBergeron in the comments, vue-resource was retired way back in November 2016 itself (few weeks after I provided this answer with that last paragraph on vue-resource). Here is more info on the same:
https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4
#Mani's suggestion of using mounted(){} works on the component that's not hidden. If you like to run a function in the component when visible and the elements which are hidden using conditions like v-if="" or v-show="" then use updated(){}.

Problema sending json file from javascript to laravel controller

im having problems trying to send a JSON file from javascript to Laravel controller, when i press my button from the view i didnt get any response.
This is my code, i appreciate any help or suggestion, thnks.
This is the the JS code:
var horarios= { Lunes: arrLunes, Martes: arrMartes, Miercoles: arrMiercoles, Jueves:arrJueves, Viernes:arrViernes};
var schedule = JSON.stringify(horarios);
//console.log(schedule);
var varurl= 'http://localhost/registerEntrance';
$.ajax({
type: "POST",
url: varurl,
data: {json:schedule},
dataType:'json',
success: function(res) {
var message = res.mesg;
if (message) {
$('.flash').html(message).fadeIn(300).delay(250).fadeOut(300);
};
}
});
When i press my button, doesnt happend anything. The next id the route and the controller code, the JSON file not arrive there yet.
Route::post('registerEntrance', array('as' => 'registerEntrance','uses' => 'CursoController#regisEnt'));
public function regisEnt(){
if(Request::ajax()) {
$data = Input::all();
return $data;
}
}
Thnks for any help.
What are you using to debug your requests? Have you checked your storage/logs/framework/laravel.log (if your log is HUGE you can always delete it and re-run your request)
Working with AJAX can get tricky when it comes to debugging your requests.
My recommendation would be
Open up your browser Inspector, and monitor Network Requests
Analyze the request you're sending.
Set debug to true under config/app.php to actually see a debug
Hope this helps!
I get resolv my problem, i post it if someone is getting a similar inconvenience.
In my view i wasnt create a form.
{!! Form::open(['route' => ['route'], 'method' => 'POST', 'id' =>'form-name']) !!}
{!! Form::close() !!}
This part create a implicit token that is necesary in laravel for use ajax method.
My code JS was modified for getting and send the csrf token.
var form = $('#form-name');
var myurl = form.attr('action');
crsfToken = document.getElementsByName("_token")[0].value;
$.ajax({
url: myurl,
type: 'POST',
data: {data:data},
datatype: 'JSON',
headers: {
"X-CSRF-TOKEN": crsfToken
},
success: function(text){
bootbox.dialog({
closeButton: false,
message: "Ok!",
title: "Perfect!!",
},
error: function(data){
console.log("Error");
}
});
With this change i get arrive to my controller.
Anyway Thnks.

jquery function not redirecting url

I am working with codeigniter and jquery. I am using ajax to send some info to a codeigniter function to perform a db operation , in order to update the page. After the operation is complete I am trying to refresh the page. However the refresh works inconsistently and usually I have to reload the page manually. I see no errors in firebug:
var message = $('#send_message').val()
if ((searchIDs).length>0){
alert("searchIDs "+searchIDs );
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
success: function(){
alert("OK");
},
complete: function() {
location.href = "pan_controller/my_detail";
}
})
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("OK");
location.href = "pan_controller/my_detail";
});
} else { alert("nothing checked") }
break;
How can I fix this?
addendum: I tried changing to ;
$.ajax({
type: "POST",
url: "AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "pan_controller/my_detail";
});
}
})
This is just defaulting to the website homepage. again, no errors in firebug
Add the window object on location.href like this:
window.location.href = "pan_controller/my_detail";
Try to use full path like
$.ajax({a
type: "POST",
url: "YOURBASEPATH/AjaxController/update",
data:{ i : searchIDs, m : message },
dataType: 'json',
.done(function() { // echo url in "/path/to/file" url
// redirecting here if done
alert("REFRESHING..");
location.href = "YOURBASEPATH/pan_controller/my_detail";
});
}
})
BASEPATH should be like this "http://www.example.com"
Try disabling the csrf_enabled (config/config.php) and trying it. If that works, then re-enable the protection and, instead of compiling data yourself, serialize the form; or, at least include the csrf hidden field codeigniter automatically adds. You can also use GET to avoid the CSRF protection, but that's least advisable of of the solutions.

call controller from a view in cakephp1.3, through javascript method

I have a map from which I want to select through javascript, a rectangular zone from my googlemap map. After this, I want to perform an action by sending the two corner coordonates (that I have took) to my Cakephp Controller, without clicking anywhere. How can I perform it please?
hint: I use the 1.3 cakephp version. Thanks.
here is my code:
var map, bnds, dz;
function initialize() {
...
dz= map.GetDragZoomObject();
...
google.maps.event.addListener(dz,'dragend', function(bnds){
//variable to be display: bnds
alert('KeyDragZoom end: ' + bnds);
}
The alert shows me this message in a alertbox:
"KeyDragZoom end: ((1.53790123, 9.404296), (5.22600788, 18.391113281))
you can try using jquery $.ajax to send the data back to the server. This example handles a response back from the server as well.
$.ajax({
url: "<?php echo $html->url( array( 'controller' => 'xxx', 'action' => 'xxx' ), true ) ?>",
dataType: "json",
crossDomain: false,
data: bnds
})
.then( function ( response ) {
$.each(response, function (i, val) {
// do something
});
});
The documentation for ajax is here if you need it https://api.jquery.com/jQuery.ajax/

passing variable back from the server to ajax success

User fills input texts, presses the button Submit. The data sends to the server to be stored and result returned back. Fancybox window with result appears. My question is: how to display the result $res1 in the fancybox?
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function ()
{
var html='$res1 from the server should be here instead of this string';//var html=$res1.
$.fancybox(
{
content: html,//fancybox with content will be displayed on success resul of ajax
padding:15,
}
);
}
});
=========================
OK, still doesn't work (returns in the fancybox the whole page+ the word "hello" on top instead of the message "hello"). Below is my update regarding the answers below, that doesn't work properly:
PHP:
<?php
$res1="hello";... // handle logic here
echo $res1; // print $res1 value. I want to display "hello" in the fancybox.
?>
AJAX
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
$.fancybox(
{
content: html,//returns hello+page in the fancybox
//if I use the string below instead of the upper one, the fancybox shows "The requested content cannot be loaded. Please try again later."
// content: console.log(html)
padding:15,
}
});
=============
New update:
Fixed!!! The problem was the data ( "hello" in the example above) was sent to the template in the framework, and template was displayed.
That's why.
Fixed.
Thank you.
Everybody.
Assuming you're using PHP:
PHP:
<?php
... // handle logic here
echo $res1; // print $res1 value
?>
AJAX:
$.ajax({
type: "POST",
url: "index/success",
async: false,
data: {
name: name,
password: password
},
success: function (html) {
// given that you print $res1 in the backend file,
// html will contain $res1, so use var html to handle
// your fancybox operation
console.log(html);
}
});
Enjoy and good luck!
$.ajax({
type:"POST",
url:"index/success",
async:false,
data:{ name:name, password:password},
success:function(html){ // <------- you need an argument for this function
// html will contain all data returned from your backend.
console.log(html);
}
});

Categories

Resources