I am new to laravel 5 and I want to know how can I use xmlhttp.open to send a GET request.
Here is what supposed to be my javascript code:
xmlhttp.open("GET", "reg_validation?field=" + field + "&query=" + query, false);
So how can I link that one to a function inside a controller and return its value with xmlhttp.responseText
Create a new route for this request :
Route::get('reg_validation', 'YourController#yourAction');
Then use the return in your action :
use Illuminate\Support\Facades\Input; //Import 'Input' class in the top of controller
function yourAction(){
$field = Input::get("field");
$query = Input::get("query");
return $field.' -- '.$query;
}
Hope this helps.
Related
I'm trying to create a form on my website where a user has a text field that they can use to enter a registration number. I want the registration number to be added to the end of the action URL so when that page loads I can use PHP to explode the URL and grab the number. Here's an example of what I'm looking for...
<form action="http://mywebsite.com/registrations/123456789">
<input type="text" name="registrationnumber">
<input type="Submit" value="Submit">
</form>
Is it possible to take whatever is entered into the text field called registrationnumber and have it passed to the URL the form directs to? Maybe an easier way is to create a text field that has a button, when the button is clicked the URL is links to is dynamically created by adding the registrationnumber to the end.
Anyone know of a way to do this?
Indeed you don't need a form to make an AJAX call. A simple input and button will suffice.
I have made a function that will make AJAX call, it will convert the object params containing all key/value pairs of the parameters you want to send to PHP, and concatenates it into a URL string:
function ajax(file, params, callback) {
var url = file + '?';
// loop through object and assemble the url
var notFirst = false;
for (var key in params) {
if (params.hasOwnProperty(key)) {
url += (notFirst ? '&' : '') + key + "=" + params[key];
}
notFirst = true;
}
// create a AJAX call with url as parameter
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(xmlhttp.responseText);
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
Assuming you have an input field:
<input id="code" type="text">
<button id="sendData">Send</button>
Here's how we can use the function ajax:
function sendData() {
parameters = {
inputValue: document.querySelector('#code').value
};
ajax('target.php', parameters, function(response) {
// add here the code to be executed when data comes back to client side
// e.g. console.log(response) will show the AJAX response in the console
});
}
You can then attach the button to sendData using an event listener:
document.querySelector('#sendData').addEventListener('click', sendData)
I'm trying to update a record in my database when a user decides to edit a table. I use javascript to make the table editable row by row and I change the button from 'Edit' to 'Save' image of table before a user can edit and image of table after a user clicks edit .
Once a user clicks'Save', I want to be able to call the route that will find the old record, and overwrite with the new record. I'm having troubles calling the route in my javascript. I've tried to use "location.href = '/people/updateshift'" but it doesn't because it load the people/update shift page, and I just want to be able to call the route in the background without sending a user to the page. Any resources, or pointers would be appreciated :)
Thank you in advance!
function editRow(obj) {
var currentTD = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
var row_length = document.getElementById("myTableData").rows[currentTD].cells.length;
console.log(obj.parentNode);
//the below is a way to get the HMTL within a cell
console.log(document.getElementById("myTableData").rows[currentTD].cells[0].innerHTML);
if (obj.value == 'Edit') {
document.getElementById("myTableData").rows[currentTD].cells[0].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[1].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[2].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[3].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[4].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].cells[5].setAttribute("contentEditable", true);
document.getElementById("myTableData").rows[currentTD].style.backgroundColor = "#A4D9F5";
var_employeetype = document.getElementById("myTableData").rows[currentTD].cells[0].innerHTML
var_daysworked = document.getElementById("myTableData").rows[currentTD].cells[1].innerHTML
var_num_employees = document.getElementById("myTableData").rows[currentTD].cells[2].innerHTML
var_shift_start = document.getElementById("myTableData").rows[currentTD].cells[3].innerHTML
var_shift_start = document.getElementById("myTableData").rows[currentTD].cells[4].innerHTML
var_shift_end = document.getElementById("myTableData").rows[currentTD].cells[5].innerHTML
console.log(var_employeetype)
obj.value = 'Save'
} else {
document.getElementById("myTableData").rows[currentTD].cells[0].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[1].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[2].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[3].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[4].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].cells[5].setAttribute("contentEditable", false);
document.getElementById("myTableData").rows[currentTD].style.backgroundColor = "#FFFFFF"
obj.value = 'Edit'
location.href = '/people/updateshift'
}
}
You want to look into the jQuery "post" feature. https://api.jquery.com/jquery.post/
When the user clicks save, send the value to the server using $.post, and an identifier for which "cell" it is (I don't know how you are doing this), and then have your server deal with updating the record.
I'm working on an application that should be sending a post request to an internal page that does a certain calculation
When pressing a button, the page(dashboard.php) prints the content of the other page(calculate_salary.php)
here's my js code so far:
<script language="JavaScript" type="text/javascript">
function getXmlHttpRequestObject() {
return new XMLHttpRequest();
}
var receiveReq = getXmlHttpRequestObject();
function sayHello() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
var start_date = $("#start_date").val();
var end_date = $("#end_date").val();
receiveReq.open("GET", 'calculate_salary.php', true);
receiveReq.onreadystatechange = handleSayHello;
receiveReq.send(null);
}
}
function handleSayHello() {
if (receiveReq.readyState == 4) {
document.getElementById('span_result').innerHTML = receiveReq.responseText;
}
}
</script>
I want to send over the values in start_date and end_date to the calculate_salary.php page
I will use that calculate page to perform some sql statements and return the result back.
How can I create this request?
POST is not an absolute necessity, I'm willing to use other techniques (js, php) to get the job done
thanks
You can use ajax instead
$.ajax({
url:"calculate_salary.php",
type:"POST",
data:{
start_date = $("#start_date").val(),
end_date = $("#end_date").val()
},
success:function(response){
$('#span_result').html(response);
}
});
You can read more about $.ajax and $.post
You have to generate querystring with url like so:
var url = 'calculate_salary.php?start_date='+start_date+'&end_date='+end_date;
receiveReq.open("POST", url, true);
Because you are not sending values that is why you are not receiving values on server side.
Another example you can find here:
How do I pass along variables with XMLHTTPRequest
Also check into this:
http://devzone.co.in/jquery-serialize-function-ajax-post-bigger-html-forms/
I have a MVC3 action method with 3 parameters like this:
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
and I want to call this by normal javascript function not AJAX (because it's not necessary to use AJAX function)
I tried to use this function but it didn't work:
window.location.assign(url);
It didn't jump to Insert action of QuestionController.
Is there someone would like to help me? Thanks a lot
This is more detail
I want to insert new Question to database, but I must get data from CKeditor, so I have to use this function below to get and validate data
// insert new question
$("#btnDangCauHoi").click(function () {
//validate input data
//chủ đề câu hỏi
var title = $("#txtTitle").val();
if (title == "") {
alert("bạn chưa nhập chủ đề câu hỏi");
return;
}
//nội dung câu hỏi
var content = GetContents();
content = "xyz";
if (content == "") {
alert("bạn chưa nhập nội dung câu hỏi");
return;
}
//danh sách Tag
var listTags = new Array();
var Tags = $("#list_tag").children();
if (Tags.length == 0) {
alert("bạn chưa chọn tag cho câu hỏi");
return;
}
for (var i = 0; i < Tags.length; i++) {
var id = Tags[i].id;
listTags[i] = id;
//var e = listTags[i];
}
var data = {
"_strTitle": title,
"_strContent": content,
"_listTags": listTags.toString()
};
// $.post(url, data, function (result) {
// alert(result);
// });
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
window.location.assign(url); // I try to use this, and window.location also but they're not working
});
This URL call MVC action "Insert" below by POST method
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
try
{
//some code here
}
catch(Exception ex)
{
//if some error come up
ViewBag.Message = ex.Message;
return View("Error");
}
// if insert new question success
return RedirectToAction("Index","Question");
}
If insert action success, it will redirect to index page where listing all question include new question is already inserted. If not, it will show error page. So, that's reason I don't use AJAX
Is there some one help me? Thanks :)
Try:
window.location = yourUrl;
Also, try and use Fiddler or some other similar tool to see whether the redirection takes place.
EDIT:
You action is expecting an HTTP POST method, but using window.location will cause GET method. That is the reason why your action is never called.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(string _strTitle, string _strContent, string _listTags)
{
// Your code
}
Either change to HttpGet (which you should not) or use jQuery or other library that support Ajax in order to perform POST. You should not use GET method to update data. It will cause so many security problems for your that you would not know where to start with when tackling the problem.
Considering that you are already using jQuery, you might as well go all the way and use Ajax. Use $.post() method to perform HTTP POST operation.
Inside a callback function of the $.post() you can return false at the end in order to prevent redirection to Error or Index views.
$.post("your_url", function() {
// Do something
return false; // prevents redirection
});
That's about it.
You could try changing
var url = "/Question/Insert?" + "_strTitle='" + title + "'&_strContent='" + content + "'&_listTags='" + listTags.toString() + "'";
to
var url = "/Question/Insert?_strTitle=" + title + "&_strContent=" + content + "&_listTags=" + listTags.toString();
I've removed the single quotes as they're not required.
Without seeing your php code though it's not easy to work out where the problem is.
When you say "It didn't jump to Insert action of QuestionController." do you mean that the browser didn't load that page or that when the url was loaded it didn't route to the expected controller/action?
You could use an iframe if you want to avoid using AJAX, but I would recommend using AJAX
<iframe src="" id="loader"></iframe>
<script>
document.getElementById("loader").src = url;
</script>
Basically, I want to have an interactive button on my website, that, when clicked, sends some data to the server in order to be checked and display the response (without form sending / page reload).
I thought it would be something like:
function checkData()
{
var req = new XMLHttpRequest();
var conf = document.getElementById('my_text_area').value;
req.open("GET", 'check_data', true);
req.onreadystatechange = function ()
{
var pre = document.getElementById('check_data_out');
pre.innerHTML = req.responseText;
}
req.send(conf);
return false;
}
And on the server side:
#get('/check_data')
def check_data():
# Process the content and answer something...
content = str(request.is_ajax) + ' - ' + str(request.GET) + ' - ' + str(request.POST)
return content
But this obviously doesn't work. Either it is not the right way to send data via javascript or not the right way to access it in bottle.py.
Showing me how it works is highly appreciated.
You can use dojo for client side logic.
var button = dojo.byId('button_id'); // button_id refers to the id of the button you want to click
dojo.connect(button,'onclick',dojo.xhrGet({
url: '/check_data',
handleAs : 'text',
load : function(response){
dojo.byId('button_id').innerHTML = response;
}
}));