Can't pass String to controller through ajax - javascript

I'm new of web development with play framework and ajax,Now I want to pass the string in the form to controller with ajax but I don't know how to do.Could you please help me?Here is my code:
html:
<form onsubmit="return newSearch();" id="formId">
<input type="search" placeholder="Search for more" id="searchBar_chat">
</form>
<script type="text/javascript" >
function newSearch()
{
var s = document.getElementById("chatDialgue");
var searchValue = document.getElementById("searchBar_chat").value;
s.innerHTML = s.innerHTML + '<li>'+ searchValue +'</li>';
document.getElementById("searchBar_chat").value ="";
$.ajax({
url: "DataMatch/searchContentMatch",
type:"GET",
cache: false,
dataType:"text",
data:"searchValue",
success: function (responseData) {
s.innerHTML = s.innerHTML + '<li>'+responseData+'</li>';
}
});
return false;
}
</script>
controller:
public class DataMatch extends Controller{
public String searchContentMatch (String search) {
// Search match
return "HI"+search;
}
}

First of all, in the data parameter of $.ajax() you have to build a query string, so the correct way is concatenating the key ("search") with its value (searchValue).
Then, you don't need neither that return false statement in the script nor the return keyword on the onsubmit form attribute.
Lastly, since you're using jQuery, take advantage of its selection capabilities and replace document.getElementById with $.
<form onsubmit="newSearch();" id="formId">
<input type="search" placeholder="Search for more" id="searchBar_chat">
</form>
<script type="text/javascript" >
function newSearch(){
var searchValue = $("#searchBar_chat").val();
$("#chatDialgue").append('<li>'+ searchValue +'</li>');
$("#searchBar_chat").val("");
$.ajax({
url: "DataMatch/searchContentMatch",
type:"GET",
cache: false,
dataType: "text",
data: "search=" + searchValue,
success: function (responseData) {
$("#chatDialgue").append('<li>' + responseData + '</li>');
}
});
}
</script>

Pass it as a Query Parameter since it is just a single string.
var search="searchValue";
$.ajax({
url: "DataMatch/searchContentMatch?search="+search,
type:"GET",
cache: false,
dataType:"text",
success: function (responseData) {
s.innerHTML = s.innerHTML + '<li>'+responseData+'</li>';
}
});

You should use the Javascript router instead of hardcoding the endpoint in your Javascript code. This will allow you to change the endpoint name later on if needed. Also, you want to pass a query string parameter, so it goes directly in the URL. Here is how to use the reverse route:
#helper.javascriptRouter("jsRoutes")(
routes.javascript.DataMatch.searchContentMatch
)
//HTML here
var endpoint = jsRoutes.controllers.DataMatch.searchContentMatch(searchValue).url;
$.ajax({
url: endpoint,
type:"GET",
cache: false,
success: function (responseData) {
s.innerHTML = s.innerHTML + '<li>'+responseData+'</li>';
}
});

One more thing, to the previous answer, do not forget about parameter in the routes file:
GET /api/search/:search controllers.DataMatch.searchContentMatch(search: String)

Related

Modify result of .serialize() on the fly [duplicate]

Is it possible to send form elements (serialized with .serialize() method) and other parameters with a single AJAX request?
Example:
$.ajax({
type : 'POST',
url : 'url',
data : {
$('#form').serialize(),
par1 : 1,
par2 : '2',
par3: 232
}
}
If not what's the best way to submit a form together with other parameters?
Thanks
serialize() effectively turns the form values into a valid querystring, as such you can simply append to the string:
$.ajax({
type : 'POST',
url : 'url',
data : $('#form').serialize() + "&par1=1&par2=2&par3=232"
}
Alternatively you could use form.serialize() with $.param(object) if you store your params in some object variable. The usage would be:
var data = form.serialize() + '&' + $.param(object)
See http://api.jquery.com/jQuery.param for further reference.
I dont know but none of the above worked for me, Then i used this and it worked :
In form's serialized array it is stored as key value pair
We pushed the new value or values here in form variable and then we can pass this variable directly now.
var form = $('form.sigPad').serializeArray();
var uniquekey = {
name: "uniquekey",
value: $('#UniqueKey').val()
};
form.push(uniquekey);
If you want to send data with form serialize you may try this
var form= $("#formId");
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()+"&variable="+otherData,
success: function (data) {
var result=data;
$('#result').attr("value",result);
}
});
$("#add_form").submit(function(e) {
e.preventDefault();
var total_qty = $('#total_qty').text();
var total_amt = $('#total_amt').text();
$("#add_btn").val('adding....');
$.ajax({
url: 'action.php',
method: 'post',
data: $(this).serialize() + "&total_qty="+total_qty + "&total_amt="+total_amt,
success: function(data){
console.log(data);
}
});
});
pass value of parameter like this
data : $('#form_id').serialize() + "&parameter1=value1&parameter2=value2"
and so on.
Following Rory McCrossan answer, if you want to send an array of integer (almost for .NET), this is the code:
// ...
url: "MyUrl", // For example --> #Url.Action("Method", "Controller")
method: "post",
traditional: true,
data:
$('#myForm').serialize() +
"&param1="xxx" +
"&param2="33" +
"&" + $.param({ paramArray: ["1","2","3"]}, true)
,
// ...
encode in js :
var temp = $("#pay_property_amount").serialize();
temp = btoa(temp);
and pass in ajex
data: { temp_data : temp },
decode in php
$temp_data = base64_decode($this->input->post('temp_data'));
if($temp_data){
$temp_data = $this->unserializeForm($temp_data);
}
function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
$array = explode("=", $item);
if (preg_match('/(%5B%5D)/', $array[0])) {
$array[0] = str_replace('%5B%5D','',$array[0]);
if(array_key_exists($array[0],$returndata)){
$returndata[$array[0]][]=$array[1];
}else{
$returndata[$array[0]] =array();
$returndata[$array[0]][]=$array[1];
}
}else
{
$returndata[$array[0]] = $array[1];
}
}
return $returndata;
}
Those who want to add new data to form data can use this method.
Exemple:
$("form#myForm").submit(function(e){
e.preventDefault();
let formData = jQuery("#myForm").serializeArray();
let newData = [
{name:"city", value: "Ankara"},
{name:"jobs", value: "Full-Stack Web Developer"},
{name:"action", value: "ajax_proccess"}
];
let postData = formData.concat(newData);
console.log(formData);
console.log(newData);
console.log(postData);
jQuery(".alert").text("İş: " + postData[4]['value']);
jQuery.ajax({
url: jQuery("#myForm").attr('action'),
type: 'POST',
dataType: 'json',
data: postData,
success: function(data) {
//let response = JSON.parse(data);
console.log(data);
alert('Submitted.');
jQuery(".alert").text(newData[5]);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" action="" id="myForm">
<input type="hidden" name="name" value="Mahmut Yüksel">
<input type="hidden" name="surname" value="Mert">
<input type="hidden" name="countary" value="Turkey">
<input type="submit" value="Gönder">
</form>
<div class="alert">İş: </div>
You can also use serializeArray function to do the same.
You can create an auxiliar form using jQuery with the content of another form and then add thath form other params so you only have to serialize it in the ajax call.
function createInput(name,value){
return $('<input>').attr({
name: name,
value: value
});
}
$form = $("<form></form>");
$form.append($("#your_form input").clone());
$form.append(createInput('input_name', 'input_value'));
$form.append(createInput('input_name_2', 'input_value_2'));
....
$.ajax({
type : 'POST',
url : 'url',
data : $form.serialize()
}
I fix the problem with under statement ;
send data with url same GET methode
$.ajax({
url: 'includes/get_ajax_function.php?value=jack&id='+id,
type: 'post',
data: $('#b-info1').serializeArray(),
and get value with $_REQUEST['value'] OR $_GET['id']

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

Passing parameters between html pages using jquery

I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')

Passing a form array to Javascript via PHP using jQuery AJAX

I'm submitting a form via AJAX and utilising jQuery and I need to find out how I cna pass form arrays to it.
For example, my html would be something like:
<input id="standard_field" type="text" name="standard_name">
<input id="some_id_1" type="text" name="my_array[my_name_1]">
<input id="some_id_2" type="text" name="my_array[my_name_2]">
<input id="some_id_3" type="text" name="my_array[my_name_3]">
Now I know you can easily get the name of the standard field in jQuery using something like:
var foo = $('standard_field').val();
But I'm not sure how to get the array data? Also, it needs to be passed to the PHP script from ajax in exactly the same way the PHP script would get it as if the form was submitted without ajax.
So an example of how I would normally pass data:
var foo = $('standard_field').val();
var loadUrl = "some_script.php";
var dataObject = { foo: foo };
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
//..........
})
.fail(function() {
//......
});
// End
function getAjaxData(loadUrl, dataObject, action, type) {
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
So firstly how can I get the data to pass from the form and secondly how can I pass it from jQuery to the PHP script so PHP get's it as an array like it would if it was POST'ed straight to the PHP script?
You should use serialize
HTML:
<form id="form1" action="" method="post">
<input id="standard_field" type="text" name="standard_name">
<input id="some_id_1" type="text" name="my_array[my_name_1]">
<input id="some_id_2" type="text" name="my_array[my_name_2]">
<input id="some_id_3" type="text" name="my_array[my_name_3]">
</form>
JS:
var dataObject = $('#form1').serialize();
var loadUrl = "some_script.php";
getAjaxData(loadUrl, dataObject, 'POST', 'json')
.done(function(response) {
//..........
})
.fail(function() {
//......
});
// End
function getAjaxData(loadUrl, dataObject, action, type) {
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
You can use this plugin http://malsup.com/jquery/form/
Example code:
JS:
$('#your_button').change(function() {
var options = {
url: 'your_url',
type: 'POST',
dataType: 'json',
beforeSubmit: function() {
// Callback function to be invoked before the form is submitted
},
success: function(data) {
// Callback function to be invoked after the form has been submitted
},
error: function() {
// Callback function to be invoked upon error
}
};
// do something
});
PHP:
var_dump($_POST);
You can use the String.slice method to extract the label name.
var input = $('#myform input');
var data = [];
var name, label, value = '';
for(var i in input) {
name = input.eq(i).attr('name');
label = name.splice(9, -1);
value = input.eq(i).val();
data[label] = value;
}
data = JSON.stringify(data);
And for detect when it's an array you can user String.indexOf('[') like
For an unknown array structure :
array_name = name.splice(0, name.indexOf('['));
label = name.splice(name.indexOf('['), name.indexOf(']'));

Replace javascript onmouseover with jQuery only

I have a page that displays a dynamic amount of "orders" and I have a button to "view" and another button to "print". To display the specific OrderNumber I'm using a javascript function triggered by onmouseover and a jQuery ajax function to change the button text, make a database entry, and then view or print another page. The problem is the order is viewed or printed MULTIPLE times from onmouseover. How can use only jQuery and call the specfic OrderNumber? Here is the code I'm using now:
This code is repeated for each order:
<div class="console_orders_details">
<input type="button" value="View"
id="vieworder'.$row[orderid].'" onmouseover="vieworder('.$row[orderid].');">
</div>
Here is the function to view the order:
function vieworder(id){
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result)
{
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
I'm assuming I need to eliminate the "vieworder" function and use a pure jQuery function. However, I don't know how to send over the order "id", which is why I used javascript.
You can target all elements with an ID that starts with vieworder, and then store the row ID as a data attribute :
<div class="console_orders_details">
<input type="button" value="View" id="vieworder'.$row[orderid].'" data-id="'.$row[orderid].'">
</div>
JS
$(function(){
$('[id^="vieworder"]').on('click', function(){
var orderid = $(this).data('id'),
btn = $('input[type="button"]', this);
$.ajax({
url: "includes/ajax/console-view.php",
dataType: 'html',
data: {orderid : orderid}
}).done(function(result) {
window.open("print.php?view=1&orderid="+orderid+"");
btn.val("Viewed!").fadeIn(400);
});
});
});
Your onmouseover event is probably being fired many times, resulting in your problem. This might help to stop unwanted extra calls, by ignoring them unless the previous one has completed.
var activeRequests = {}; // global
function vieworder(id){
if (activeRequests[id]) { return; }
activeRequests[id] = true;
$(function(){
$('#vieworder' + id).click(function(){
var orderid = id;
var dataString = 'orderid='+ orderid; //string passed to url
$.ajax
({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
delete activeRequests[id];
window.open("print.php?view=1&orderid="+id+"");
$('#vieworder' + orderid + ':input[type="button"]').attr("value", "Viewed!").fadeIn(400);
}
});
})
});
}
First, don't have a dynamic id that you have to parse, and don't have an event handler in your html:
<div class="console_orders_details">
<input type="button" value="View" class="vieworder" data-id="$row[orderid]">
</div>
Next, create an event handler for just what you want to do. .one() will set an event handler to fire only once:
$(document).ready(function (){
$(".console_orders_details").one("mouseover", ".vieworder" function(){
var dataString = "orderid=" + $(this).data("id");
$.ajax({
url: "includes/ajax/console-view.php", //url of php script
dataType: 'html', //json is return type from php script
data: dataString, //dataString is the string passed to the url
success: function(result) {
window.open("print.php?view=1&" + dataString);
$(this).val("Viewed!");
}
});
});
});
If you want this to work onclick, then just change the mouseover to click. Also, fadeIn doesn't work on values. Here is a fiddle that has the basics: http://jsfiddle.net/iGanja/EnK2M/1/

Categories