Related
I'm making a form that's called by Ajax and trying to configure the form to submit using Ajax. This form is supposed to submit the data through route('ruangrapat.store). But every time I submit the form, it returns 419 status when I don't use csrf_token() in Ajax and if I use the csrf_token() in Ajax. It always returns 500 internal server error. Can someone help me to solve this problem? I've been reading almost every discussion that I found on the internet, but still no answer.
Maybe I missed something important on my code. Please review my code.
//ajax
$(document).ready(function(){
$('#form-ruangrapat').on('submit',function(e){
e.preventDefault();
var formdata=$('#form-ruangrapat').serialize();//should i do this??
//if i should take the value of inputs 1 by 1,please show me the proper way
var token="{!!csrf_token()!!}"
$.ajax({
url:"{{route('ruangrapat.store')}}",
data: {formData:formdata,_token:token},
type:'post',
success:function(result){
$('#result').html(result);
}
});
});
});
//controller
public function store(Request $request)
{
$data = new Ruangrapat();
...
$data->contact = $request->get('contact');
$data->save();
return view('ajax-result.ruangrapat.index')->with('status', 'Ruang rapat baru berhasil ditambahkan!');
//is this return value correct??
}
//route
Route::resource('ruangrapat', 'RuangrapatController');
i had the same problem,419 is matched to the csrf token,when you fixed it,the request go to the server so ,the internal server error 500 say that there is a probleme while storing,so relook into the store function in controller and make sure that all process are correct in the function.
First Recomendation
To make any ajax request, it is recommended to add the CSRF token to the header of the ajax requests
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
As advised by laravel documentation
Second Recomendation
To see what the ajax request is sent, I would advise having the controller return the data to you and see it through the web console.
$(document).ready(function(){
$('#form-ruangrapat').on('submit',function(e){
e.preventDefault();
var formdata=$('#form-ruangrapat').serialize();
var token="{!!csrf_token()!!}";
$.ajax({
url:"{{route('ruangrapat.store')}}",
data: {formData:formdata,_token:token},
type:'post',
dataType:'JSON',
//You can use sucess or done, personally i like more done
}).done(function (data) {
console.log(data)
});
});
});
And in the controller
public function store(Request $request)
{
return response()->json($request->input());
}
Other option is to use the network monitor of the browsers and see the variables that are sent.
I am working on a project that displays hotel and airbnb data using flask and a sql database. We are trying to create a "favorite button" so the user can favorite/unfavorite listings. I've got an AJAX call to a Flask endpoint that will the make corresponding SQL queries to the "favorites" table. My problem is, I can't seem to access the data I'm passing into Flask.
Here is my AJAX call on the client-side:
function unfavoriteClicked(uid, itemid, type){
$.ajax({
type: "POST",
url: "/unfavorite",
data:{uid:uid, itemid:itemid, type:type},
contentType: 'application/json;charset=UTF-8',
success: function(data) {
console.log(data);
},
error: function(jqXHR) {
alert("error: " + jqXHR.status);
}
});
}
And here is my Flask code:
#app.route('/unfavorite', methods=["GET","POST"])
def unfavorite():
if request.method == "POST":
return request.form
return "this shouldn't happen"
Note that I've taken the SQL logic and other things out since I've figured out that I am not accessing the data correctly in Flask.
I am sure that the AJAX request goes through, because when I return something like "hello", it shows up in the console log. However, when I try to access the data dictionary I'm passing in, it returns a "500 internal server error" or some other kind of error depending on what I'm trying to access. I've tried to access a bunch of different things from looking at other stackoverflow posts (like request.form['data'], request.data, request.args, etc) but nothing seems to allow me to access the data. However, it does seem to allow me to access "request.method".
I was wondering if there is something fundamental that I am missing here that would be a reason why I cannot pass in data to Flask? Or any other suggestions for doing this "favorite" button are appreciated. Thanks!
So considering the main issue that you want to tackle is accessing the data that is been passed by your web page using Ajax. I have a solution which might work in your case.
So there are two parts in which i will explain how you can solve this problem.
1) Passing the data to your python controller/function to further process the data.
$.post("url_to_which_you_want_to_pass_data", {variable_name_to_access_in_python:any_value/variable_from_front_end},
function(response, status){
call_back_function_code
});
2) Accessing the data that has been passed from the webpage in python flask
#app.route('/unfavorite', methods=["GET","POST"])
def unfavourite:
if request.method == "POST":
any_variable_name = request.form.get("variable_name_to_access_in_python","")
print(any_variable_name) #If you want to print
return any_variable_name #If you want to see any_variable_name on web
return None
Hope it Helps! Cheers :)
I don't know if it's the best option, but its worked for me.
JavaScript:
var data = [1, 2, 3, 4]
var frontend_data = {'list':data}
$.ajax({
url: "/unfavorite",
contentType: 'application/json',
type: "POST",
data: JSON.stringify(frontend_data),
dataType: 'json',
success: function(result) {
console.log("Result:");
console.log(result);
}
});
Flask:
#app.post('/unfavorite')
def unfavorite():
data = request.get_json()
print(data['data']) #[1, 2, 3, 4]
return jsonify(data)
This question already has answers here:
What is AJAX, really?
(21 answers)
Closed 5 years ago.
Ok, pardon the dramatic title, but making AJAX calls has to be the most confusing thing to do for me in my coding journey so far.
I’m completing a project where a user enters a keyword into a search bar and results are returned using the Wikipedia API. I’ve watched several tutorials on making AJAX calls and gone over the documentation, but it’s just not clicking.
The main questions that go on in my head when trying to figure this out:
What the heck is supposed to go into an AJAX call and how do I find out? I've gone over the documentation and know that there are a number of settings that can be specified in an AJAX call, but how do I figure out what settings I need to use? What do these settings mean?!
I know this might be a stupid question to most, but I'm just starting out and want to learn!
This is honestly all I have and currently understand:
$(function() {
// make ajax request
$.ajax({
url: "https://en.wikipedia.org/w/api.php", // this is the API endpoint
dataType: json;
});
});
What is an AJAX request?
Ajax is a set of web development techniques using many web
technologies on the client side to create asynchronous web
applications.
With Ajax, web applications can send data to and retrieve from a
server asynchronously (in the background) without interfering with the
display and behavior of the existing page.
Think of an AJAX request the same way you would think about an HTTP request. You are simply requesting files, text, or any other resource that is located on a server.
Why should I use AJAX requests?
They provide benefits to user experience, functionality, and performance.
For example, let's say you are trying to build a text-messaging application. To build something like this, you will need to have the new text messages appear on the page without the user needing to do something. This is called: Dynamically loaded content.
This can be achieved with AJAX.
How can I make an AJAX request?
By using jQuery, a framework for Javascript, we can make the experience alot easier. Here's a basic AJAX request with jQuery AJAX.
$.ajax({ *properties* });
The AJAX method takes some properties:
URL: The source you want to pull information from.
Method: The request method you want to use. (POST, GET, PULL)
Data: The data you wish to send to the source.
There's a lot more, however for simplicity reasons I am only going to name those.
Let's say you want to create a login system without a page refresh. This is really simple!
First, we need to setup the backend.
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == 'USER' && $password == 'PASS') {
echo('success');
} else {
echo('failure');
}
}
Save this inside a file called login.php.
Second, let's setup the frontend.
<form method="POST" action="login.php">
<input name="username" type="text" placeholder="Username">
<input name="password" type="password" placeholder="Password">
</form>
We now have a foundation for an ÀJAX request. Before I implement it, let's talk about what the PHP and HTML are doing.
The HTML has a form, which has two inputs, username and password. As we can see from the attributes, the form will send the data to login.php using the POST method. The PHP will check if they're set, and if they're correct.
Unfortunately, this setup causes one of the most hated website features. THE REFRESH.
How can we solve this? AJAX Baby!
First, remove the attributes on the form.
<form>
<input name="username" type="text" placeholder="Username">
<input name="password" type="password" placeholder="Password">
</form>
Second, add a submit event listener.
$('form').submit(function(event) {
});
Third, add a preventDefault() on the event to stop the page refresh.
$('form').submit(function(event) {
event.preventDefault();
});
Fourth, get the form values.
$('form').submit(function(event) {
event.preventDefault();
var $form = $(this);
var username = $form.find('input[name="username"]').val();
var password = $form.find('input[name="password"]').val();
});
Fifth, add the AJAX.
$('form').submit(function(event) {
event.preventDefault();
var $form = $(this);
var username = $form.find('input[name="username"]').val();
var password = $form.find('input[name="password"]').val();
$.ajax({
url: 'login.php',
method: 'post',
data: { username: username, password: password },
success: function(response) {
alert(response);
}
});
});
This will send the data to the login.php file on form submission. If the values are set, the PHP will echo (or give the data to AJAX) the status. It will return success or failure depending on the username and password accuracy.
Hope this helped! It took forever.
Ok, I'm not an "Ajax master" but here is an example of how you can use it, I hope it will help you.
Imagine you have a simple log in form in HTML :
<form method="POST" name="connexion" id="connexion">
<input type='text' id='add_url' name="add_url" required/>
<label for="add_url">Add URL</label>
<input type="submit" name="sub_add" value="Add">
</form>
Now I have a.js file where I want to check if the value added is good and I want to show a result if it's okay, but I don't want to reload my page. So I will make an Ajax call :
function add_url () {
var data = $('input[name = "add_url"]').val(); // Here I select my input "add_url" and put the value on my var "data"
$.ajax({
type: "POST", // How I want to send my data on my php page
url: "mypage.php" // the name of the file where I will use this data
data: {"add" : data}, // The data I will use in my php, with the name "add"
dataType: "json", // The type of data I want to receive
success: function(response) {
// If my ajax call worked, I will do some code here
},
error: function (xhr, status, msg) {
// If my ajax call failed, I want to know why so I will use "xhr, status and msg" to have some information about why it failed
}
});
}
Now in my php, I will use the data send with ajax and build a JSON response :
// mypage.php
<?php
$url = $_POST['add']; // I put the data send in my var $url
// you do some code here with your data, for example I add the new URL in some array and the new array is $data
$result['status'] = "success"; // All is ok so I say it
$result['message'] = "All is ok !" // I add some message
$result['data'] = $data; // The data I will use in my JS
$result = json_encode($result); // I need a JSON as response, remember?
echo $result; // My response
?>
Now in my ajax function, if all is ok I can use what I send in the success part:
success: function(response) {
if (response.status === "success") { // I test if the status I send is "success"
alert(response.message); // The message I send
console.log(response.data); // I want to see in my console the data I receive
}
}
This is just an example, but I hope you have a better idea of how to use it :)
It is hard to answer this question here and write about the use of all configuration of AJAX. I would suggest you to learn about HTTP Request in general. How it works and what all headers are there and their use. There is this nice tutorial on HTTP requests and AJAX . Please look into https://code.tutsplus.com/tutorials/a-beginners-guide-to-http-and-rest--net-1634 . Keep on using and exploring the AJAX calls. You will learn it with the time.
This question is closed so I hope other newbies who are learning about ajax
and are not looking for jQuery solution will get some idea from this page.
Asynchronous Javascript And XML (AJAX) is something that runs without stopping your entire code execution (in short, AJAX is asynchronous).
In normal JavaScript, codes are executed synchronously. This means that one code cannot be executed before the codes before it have been executed.
However, in AJAX, the codes after ajax code are still executed, even though the ajax code has not finished executing.
jQuery's $.ajax method is basically the over-simplified JavaScript below:
function ajax(settings){
var ajax = new XMLHttpRequest(), // initializing AJAX constructor
header = 'application/x-www-form-urlencoded';
ajax.addEventListener('readystatechange', function(e){
if (this.readyState == 4){ // if request is ready
if (this.status == 200) // if request is successful
settings.success(this); // run `success` function
else // if request is unsuccessful
settings.fail(this); // run `fail` function
}
});
if (settings.dataType === 'json') header = 'application/json';
ajax.open(settings.type, settings.url, settings.async); // opens connection with the server
ajax.setRequestHeader('Content-Type', header); // sets ajax request header
ajax.send(settings.data); // sends data to server
}
ajax({
type: 'POST',
url: 'api.php',
dataType: 'json',
data: {},
async: true,
success: function(e){
alert('Ajax successful');
},
fail: function(e){
alert('Ajax failed');
}
});
The code above explains what AJAX is. The code below explains what asynchronous mean.
If ajax is set to be synchronous:
var a = 0;
a += 1;
ajax({
type: 'POST',
url: 'api.php',
dataType: 'json',
data: {},
async: false, // async is set to false
success: function(e){
a += 10;
console.log(a);
},
fail: function(e){
alert('Ajax failed');
}
});
a += 2;
console.log(a);
After a few seconds (because of awaiting server's response), the console will log two 13 in the console. This is because the a += 2 will only be executed after the ajax()'s execution has ended.
However, if ajax is set to be asynchronous:
var a = 0;
a += 1;
ajax({
type: 'POST',
url: 'api.php',
dataType: 'json',
data: {},
async: true, // async is set to true
success: function(e){
a += 10;
console.log(a);
},
fail: function(e){
alert('Ajax failed');
}
});
a += 2;
console.log(a);
The console will immediately first log 3, then after a few seconds, logs 13. This is because while the ajax() is waiting for the server's response, the a += 2 and the codes behind are still being executed, even though the ajax() is still executing (waiting for server's response). Once the server responds, it will then only execute the a += 10 and the other console.log(a).
Of course, to make meaningful ajax request, you will need some code at the server side.
Assuming we have a fake api from api.php:
if (isset($_POST['hello']) && isset($_POST['foo'])){
$array = [
'one' => $_POST['hello'],
'two' => $_POST['foo'];
];
}
echo json_encode($array);
Then in JavaScript:
ajax({
type: 'POST',
data: {
hello: 'world',
foo: 'bar',
},
success: function(response){
console.log(response);
},
});
The console will then log something similar to the following:
{
'one': 'world',
'two': 'bar',
}
I have the following ajax long polling script
(function poll(){
$.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn'); ?>", success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
}, dataType: "json", complete: poll, timeout: 1000 });
})();
The backend PHP code is as follows
if(isset($_POST['status']) && $_POST['status']){
$data = ['status'=>$_POST['status']];
$json = json_encode( $data );
echo $json;
}
Flow
When I render the page, the ajax script runs and waits for response. When I checked the network tab, ajax was endlessly making requests to the URL specified.
I get a form post from an external website to the backend PHP which I need to push to the jquery.
But when a post is happening, nothing is being logged in the console. But if I hard code some values in the $json and echo it, its coming up in the console.
I am facing two issues
When a post happens on the PHP script, its not coming up in the ajax code.
When I hard code (simulated the response posted by the external form post) the $json and echo it, its coming up in the console, but the condition for data.status== 'success' is not getting checked.
What is wrong in this. Am I missing something?
UPDATE
I could fix the "condition not being checked" as there was something wrong the json being echoed.
Now to avoid confusion, the flow for this
User open the page,
> The ajax starts the long polling process to my PHP code, waiting for a
> response.User enters payment details in a form which is my html,clicks on pay, a pop up appears
> which renders the banks login page (Payment gateway).After user entering all
> details in the pop up (banks page), bank sents a server to server call about the status of
> transaction to my notificationURL
> ('mydomain.com/internal.v1/checkTxn'). As soon as I get a POST on this
> URL(I will close the pop up), my ajax polling should get the data posted to my PHP and there by
> I will show the status of TXN to the user on the same card form he entered his details earlier and
> the pop window closes. The response here is returned by my PHP code to the ajax.
The
> post coming to my PHP code is a server to server post which is posted
> by a Payment Gateway.
1. let's debug this:
set your ajax error call back,
$(function(){
(function poll(){
$.ajax({ url: "http://tinyissue.localhost.com/test.php", success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
},error:function(err){
console.info('error fired...');
console.info(err);
}, dataType: "json", complete: poll, timeout: 1000 });
})();
});
run this, you will get console
error fired...
Object {readyState: 4, responseText: "", status: 200, statusText: "OK"}
2. Why went to error callback:
Why ajax response status is 200 and statusText is "OK" , error callback still fired instead of success?
Your AJAX request contains the following setting:
dataType: "json"
The documentation states that jQuery:
Evaluates the response as JSON and returns a JavaScript object. (...)
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown.
This means that if server returns invalid JSON with a 200 OK status then jQuery fires the error function and set the textStatus parameter to "parsererror".
Solution: make sure that the server returns valid JSON. It is worth noting that an empty response is also considered invalid JSON; you could return {} or null for example which validate as JSON.
3. Why ajax return invalid JSON:
In your mind, at server side, you checked the $_POST['status'] to make sure last call success in the loop poll, only $_POST['status'] is set, you will echo json, or it echo nothing.
But, unfortunately, at the beginning of the call loop, the first time the ajax called, you didn't set status to post. Then it echo nothing, then it went error callback, also went complete callback, then call again without status to post. See, it went a bad cycle.
4. Solution:
Set a status value to post at the first ajax call.
$(function(){
(function poll(){
var status = 'success';
$.ajax({ url: "http://tinyissue.localhost.com/test.php", success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
status = data.status;
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
},error:function(err){
console.info('error fired...');
console.info(err);
status = 'error';
}, type:'post',dataType: "json", data:{status:status}, complete: poll, timeout: 1000 });
})();
});
If you are using long polling, you could have a cache issue.
First, when your post comes to your system, check that checkTxn changes.
Last, you can add a random parameter (by adding date in millis, for example) in url query, you will not use it, but your server will think your requests are different.
Please, check it and let us know.
#Edit: Sure #Ajeesh, I'll explain it:
(function poll(){
$.ajax({ url: "<?php echo URL::to('/internal/v1/checkTxn'); ?>?_ts=" + new Date().getTime(), success: function(data){
//Update your dashboard gauge
console.log(data.status); //Data is getting logged
if(data.status == 'success'){ //This condition is not being checked
console.log('suucesful'); //Not coming
}
}, dataType: "json", complete: poll, timeout: 1000 });
})();
By doing this, cache will not be used, because all queries are different for your server/browser.
On the other hand, I ask you for any changes in your page when you receive the POST, so, if not, your ajax will never receive the notification, do you know what I mean?
I am currently developing a Ruby on rails 3 application.
My server controller function render a json object as response:
class DaysController < BaseController
...
def the_days
...
render :json => days
end
end
In my javascript,I use the following code to get json response from server( that's from the_day function in controller)
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
var result = data.response;
alert(result)
alert(data)
},
"json"
);
I use firefox browswer and checked with Firebug, in Firebug Net->XHR, I see the Get request is successful, and the response "days" is there. That's both request and response are successful.
But I did not see the two alert window defined in the above $.getJSON function, why? Why I can not get the response "days" in $.getJSON function??
-----------------Edited------------------
I edited my code to this one:
$.ajax({
url: myURL,
type: 'GET',
data: {
emp_id: emp_id
},
dataType: "json",
success: function(data) {
alert("hi");
alert(data)
}
});
When I run this code, the browser is stuck at success: function(data)
If data is coming back null, but the response was otherwise successful, I'd say that you're sending the request in a manner that violates the Same Origin Policy.
The request needs to be sent to the same host/port/protocol that served the original page.
If this is only an issue in your development environment, you can test in Chrome by launching it from a Terminal application with --disable-web-security.
EDIT: Try changing the parameter name from data to something else, like dat or whatever.
Then try an alert:
alert( dat );
I've heard of some browsers having trouble with the data parameter when you utilize the data property of an AJAX call.
I'm guessing that the problem is that data does not have a response property. Try alerting just the data variable. It should be the days object itself.
I wish I could just leave a comment but I guess I don't have access to that yet.
Anyway, I'd start with something even more basic. Add some text alerts just to make sure you're actually making it to where you think you are. ie...
$.getJSON(
url,
{emp_id: emp_id},
function(data) {
alert('hi') // add this
var result = data.response;
alert('bye') // add maybe even this
alert(result)
alert(data)
},
"json"
);
Sometimes when I'm debugging I find that even my most basic assumptions are wrong.
Edit: here's some sample code from working code I recently implemented
$.ajax({
url: 'users/check_username',
type: 'GET',
data: {
username: username
},
dataType: "json",
success: function(user_exists) {
alert(user_exists) // CHANGE THIS PART
}
});
It sounds like you are not sending the correct header in your ruby application. Firebug should report the response Content Type as application/json because that is what jquery is expecting it to be.
You could try changing the datatype in your ajax call to html to see if your alerts work with that, but that doesn't really help with the json parsing.
ALL, finally, I figured out the root cause. The reason is simply because of "Invalid json data" returned in server. That's in rails controller function 'def the_days':
render :json => days
should be modified to
render :json => days.to_json
Then, everything works smoothly:) Thank you all anyhow!