First, here is my code :
routes.php
$router->resource('vips','formController');
formController.php (im only posting the concerned function)
public function store(CreateVipRequest $request, Vip $vip, Pool $pool, Url $url)
{
$new_vip = $vip->create($request->except(['srv_hostname', 'srv_ip', 'srv_port','url']));
$pool->fill($request->only(['srv_hostname', 'srv_ip', 'srv_port']));
$url->fill($request->only(['url']));
/* Some more inserts on the database...*/
return redirect()->route('vips.show', [DB::table('vips')->max('id')]);
}
My code submits the form, and after some json requests to a distant Api (and some databases insertions) it redirects to the show view.
Now I want to add a second button that submits the form via Ajax.
Question : Is there a way to use the same function store ? I need it to be able to process both an ajax submit and a normal submit.
Submit form using ajax
$("#form-name").submit(function(ev){
ev.preventDefault();
var formURL = $(this).attr("action");
var postData = $(this).serializeArray();
$.ajax({
url: formURL,
type: 'POST',
data: postData,
success: function(data, textStatus, jqXHR){
location.reload();
},
error: function(jqXHR, textStatus, errorThrown){
var errResponse = JSON.parse(jqXHR.responseText);
},
});
});
Yes, you can.
In your javascript you can do something like this (assuming you're using jquery):
// if you're using a form
var data = $('form').serialize();
// if data comes from elsewhere
var data = {foo: 'bar', ...};
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function (data) {
// Do something if everything went fine
},
error: function (jqXHR, textStatus, errorThrown) {
// Do something if something went wrong
},
});
Your controller will catch the data coming from the request as you are already doing.
Related
For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.
I use the following ajax script.
$.ajax({
dataType: 'json',
url: url,
data: tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
The attribute Route in Web API before method.
[Route("api/tudisp/Edit/{tuDispId}")]
public IHttpActionResult Edit(int tuDispId)
{
}
The genarated request from ajax.
http://localhost:xxxxx/api/tudisp/Edit/?179
How to force ajax to not generate sign '?' by id parameter.
The simplest way to do it is to change the url property of the Ajax options...
$.ajax({
dataType: 'json',
url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
GET parameters are automatically appended to the Url as a querystring, which is fine if that's what your application is expecting, but not when you're using routing as you are.
However, if you wanted to modify existing Ajax requests you can use prefiltering. This example modifies the Url of the ajax call, replacing {variable} with a given value from the data object...
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.data = ""; // this removes the querystring
for (key in originalOptions.data) {
options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
}
});
$.ajax({
url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
data: {
"tuDispId": 179
}
});
If you wanted to use something like that then I'd strongly recommend spending a bit of time making it more robust, but it's an example of how you could do what you want.
I want to know how can I send the image data to the server (Django app) using javascript ajax function.
Following is my code.
// Get filename of image
jsondata = JSON.parse(data);
image_file_name = jsondata.fileurl;
// document.getElementById('previewimage').src = image_file;
// I can show the image.
b64_image = btoa(unescape(encodeURIComponent(image_file)));
var credentials = {
filename: image_file_name,
image: b64_image,
};
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'GET',
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
jsondata = JSON.parse(data);
alert("File upload completed...");
})
// If false...
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
You have to use FromData for posting files using ajax .
var form = $('form')[0];
var formData = new FormData(form);
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
// success code .
}
});
You just need to make one change in your code.
// Send ajax request to the server
$.ajax({
url: HOST_NAME + "user/api/file_uploader/",
type: 'POST', // changed from GET to POST
dataType: 'json',
data: credentials,
timeout: 10000,
})
.done(function (data) {
// Get the result
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Upload error");
})
as GET is use to read and post is used to create.
you can read more about request methods.
I'm trying to test the successful submission of data from javascript to a php file by having that php file return the results of the javascript post back to javascript. I'm getting a successful response in the ajax post, but the data is an empty string. How do I find out what data was posted? Here's my code:
JAVASCRIPT:
var benefitsArray = ["someData","someOtherData"];
$('#drop-submit').on('click',function(){
if (benefitsArray.length > 0){
var formData = { "benefits" : benefitsArray };
debugger;
$.ajax({
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
console.log(data); //result is "";
debugger;
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
console.log('failure');
}
});
}
});
PHP:
<?php
echo $_POST["benefits"]
?>
UPDATE:
I got a response by, in the php code, doing:
echo json_encode($_POST['benefits']);
but the problem is that in the javascript, if I log the data, the result is
"["someData","someOtherData"]" (a string)
and not
["someData","someOtherData"] (an array)
how do I get it to return an array and not a string?
You're not parsing the JSON being sent to you.
You can make jQuery do this for you by adding dataType: 'JSON' to your $.ajax options...
$.ajax({
dataType: 'JSON',
url : "dd-receiver.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR) ...
Or manually with JSON.parse:
success: function(data, textStatus, jqXHR) {
benefits = JSON.parse(data);
...
}
I am using ajax to send info from a filled out form to a php file which sends mass emails to selected user categories from the form. The problem is that the list is quite large (5000 users) and the operation times out before the list is completely done.
I have set a timeout limit for the operation but I dont know how to resend the original form data back to the php file so that it can continue processing the list. Below is that Jquery Ajax code im using
$(document).ready(function(){
$("#subscriberform").submit(function(e) {
e.preventDefault(); //prevent default form submit
var postData = $(this).serializeArray();
var formURL = "'.SITE_PATH.'components/admin/subscribers/ajaxprocess.php";
$.ajax({
url: formURL,
type: "POST",
data: postData,
timeout: 30000,
dataType: "html",
beforeSend: function(){
$("#formdata").html("<p>Sending selected articles to subscribers: </p><img src=\"'.DEFAULT_TEMPLATE_PATH.'images/ajaxloader.gif\"><p><strong>Please dont close window</strong></p>");
},
success: function(data,textStatus){
$("#formdata").html("<p>Sent Data ["+textStatus+"]: </p>"+data+"");
},
error: function(x,t,m){
// I want to insert the code here
}
});
});
});
I am not that knowledgeable in jQuery. Can I please get some assistance on this
Thanks in Advance
Check for the textStatus for error handler
from Doc Function( jqXHR jqXHR, String textStatus, String errorThrown )
and the value for textStatus can be "timeout", "error", "abort", and "parsererror"
function doSubmitList(formData)
{
var formURL = "'.SITE_PATH.'components/admin/subscribers/ajaxprocess.php";
$.ajax({
url: formURL,
type: "POST",
data: formData,
timeout: 30000,
dataType: "html",
beforeSend: function(){
$("#formdata").html("<p>Sending selected articles to subscribers: </p><img src=\"'.DEFAULT_TEMPLATE_PATH.'images/ajaxloader.gif\"><p><strong>Please dont close window</strong></p>");
},
success: function(data,textStatus){
$("#formdata").html("<p>Sent Data ["+textStatus+"]: </p>"+data+"");
},
error: function(x,t,m){
if(t==="timeout") {
doSubmitList(formData);
}
}
});
}