Post to PHP backend from javascript code - javascript

I have tried other answers but none have worked. The javascript code is supposed to submit a list of product id's to a php page. When products are selected, the submit button triggers the submit function.
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
console.log(ids);
//send the ids to api
bundle = [];
$('.bundle-list').empty();
$('.total').html('No item in bundle');
$('.submit').addClass('hide');
}
I have tried inserting this line in the function
document.getElementByID("test").value = bundle;
and a hidden tag within the form but can't get the var to submit to PHP
<input type="hidden" id="test" name="test" visibility="hidden"></input>
Where should the position of the hidden element be relative to the JS code? and any other methods of retrieving the ID's?

Either by $.post or $.get variable you can send data to PHP file, but i think you want to save pids in hidden field, but you are not update its value on submit. like
$('#test').html('YOUR DATA')

Try this..
function submit() {
var ids = bundle.map(function(item){
$('#product-'+item.id+' button').attr('disabled', false);
return item.id;
});
$.ajax({
url: 'YOUR_URL HERE',
type: 'POST',
data: { qry: ids },
success: function(data) {
///WHEN SUCCESS
}
},
error: function(e) {
}
});
}

Related

How to detect that my select form have been change by ajax success

I have two form input ( text and select form ).
The select form change by ajax success when user search the employee data.
Now, i want the other jquery function that can automatically detect when the select form have been change by ajax success and retrieve the new value of select form to use by other function to make new data in my input text.
my Search Employee Function
function search_personal_result(formObj, urlres, responseDIV, disable_data, modal_class,result_data)
{
disable_data=disable_data||false;
modal_class=modal_class||false;
result_data=result_data||false;
var loading = '<p>Loading ...</p>';
$.ajax({
url: site_url+'/'+urlres,
beforeSend: function(){
$(responseDIV).html(loading);
},
data: $(formObj).serialize(),
type: "post",
dataType: "html",
success: function(response){
//proceed data result here
if(result_data==false){
var obj = jQuery.parseJSON(response);
$.each(obj, function (index, value) {
if(result_data==false){
for(var j in value){
//My SELECT Form Changed here
$('#VCIDSBU').val('MY NEW VALUE');
}
}
});
}
},
error: function(){
alert("Terjadi kesalahan!");
},
});
}
If the user search the employee data using search_personal_result, my select form have been successfully changes.
Now that i need is, how to make the other jQuery function that can detect that my SELECT Form have been changed by search_personal_result
I have try using
$(function () {
$('#form_create_sp').on('change','SELECT#my_select_id',function(){
alert('it changes');
});
})
It can only detect when the user manually change the select form. but not working when the select form changed by search_personal_result
Thanks for all expert here
You could always do some sort of console.log("Success"); Function based on if it sent or not.

Laravel - AJAX POST Array of Choices from Checkboxes

I have an AJAX Post that I'm trying to fix, but with a multitude of checkboxes on the input, I'm getting stuck.
At the moment, say I've this:
<input type="checkbox" name="billToEmail[]" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail[]" value="email2#email.com">email2#email.com
And I've a button called "Send Notifications", which starts the following script:
<script>
$('.modal-footer').on('click', '.sendNotificationNow', function() {
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: {
'billTo': $('.billToEmail:checked').val(),
'shipTo': $('.shipToEmail:checked').val(),
'shipFrom': $('.shipFromEmail:checked').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#sentNotifications').modal('show');
toastr.error('Validation error - Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
toastr.success('Successfully Sent Notifications!', 'Success Alert', {timeOut: 5000});
$('div.notificationssent').fadeOut();
$('div.notificationssent').load(url, function() {
$('div.notificationssent').fadeIn();
});
}
},
});
});
</script>
Now, I'm sure my issues are popping up near the top, where I'm trying to "translate" the multiple values into the data variables. Should I be putting something besides .val()?
I've a few more fields like this that I need to work on with the multiple checkboxes but if I can get some help for the billToEmail alone, I'm sure I can fix the remainder.
First, you don't need the [] sign. So, your checkbox html will look like this :
<input type="checkbox" name="billToEmail" value="email1#email.com">email1#email.com
<input type="checkbox" name="billToEmail" value="email2#email.com">email2#email.com
Second, you need to push selected value on checkbox into javascript array variable using foreach :
var billToEmail= [];
$("input:checkbox[name=billToEmail]:checked").each(function(){
billToEmail.push($(this).val());
});
Third, you need to convert javascript array into string using JSON.stringify().
billToEmails= JSON.stringify(billToEmail);
Then after that, pass the billToEmails variable into your data in AJAX. So, it will look like this :
var dataString = "billTo="+billToEmails+"&shipTo="+$('.shipToEmail:checked').val()+"&shipFrom="+$('.shipFromEmail:checked').val()+"&_token="$('input[name=_token]').val();
$.ajax({
type:'POST',
url: '/shipments/sendNotifications',
data: dataString,
In order to PHP can fetch the array, you need to decode the billToEmails string first using json_decode in your controller.
$variable = json_decode($request->billTo,true);
Try this-
billtoemail = $('input[name='billToEmail[]']:checked").map(function () {
return this.value;
}).get();
or
billtoemail= new Array();
$("input[name='billToEmail[]']").each(function(){
billtoemail.push(this.value);
});
Now send this variable billtoemail like other variable in your ajax. In your controller you can get all the values by a simple foreach($request->billTo as $billtoemail)

Issue populating ajax response into a div

What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

pass ID when button is clicked to Action link

I want to assign a certain value for an ID when button/url is clicked.
So that I can display a dynamic list based on this id by passing the id to action link.
Sample of my code (button)
<a class="" href="/LaborerSearchByName/Index">
<img src="/Content/images/b7.png" id="b7"
onclick="bb7();"
onmouseover="bigImg(this)"
onmouseout="normalImg(this)">
</a>
The call for action link
#Html.Action("Menu", "MenuItem", new { id = "MenuId"})
"MenuId" must by a dynamic value based on which button is clicked.
Here goes my solution, use Html.ActionLink() -
#Html.ActionLink("Menu Text", "Menu" ,"MenuItem", new { id = "MenuId" }, new { #id = "MenuId" })
Then say you have image control like this -
<img src="/Content/images/b7.png" id="b7"/>
Then you have simple JQuery script to replace query string in this way -
<script>
$(document).ready(function () {
$("#b7").click(function () {
$("#MenuId").attr("href","/MenuItem/Menu/" + this.id);
});
});
</script>
In the above script, when you click on the image element, its id (b7) will be used to formulate the anchor tag url. so now when image was clicked, a new url will be assigned to anchor tag on the client side using JQuery. So the final url should be something like this -
/MenuItem/Menu/b7
UPDATE: As per your comment, I am presenting a simple demonstration on how to use JQUERY AJAX to make a GET request with a parameter and get results back on to the UI.
Lets say you have a controller which returns Json -
public JsonResult GetJson(string MenuId)
{
List<string> urls = new List<string>();
urls.Add("https://google.com");
urls.Add("https://bing.com");
return Json(urls, JsonRequestBehavior.AllowGet);
}
Then you can call this controller action in a button click using JQuery Ajax in the following way. In your implementation you should get that dynamic value instead of input text control. For demo purpose I used Input text to get a value and pass it to controller action.
<input type="text" id="Menu" />
Click me
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.MenuId = $("#Menu").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {ou parse data
// This is how we parse returned json string
$.each(data, function (i, item) {
alert(data[i]);
});
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
When you run the code, you should see following view -
When you enter the value and click on anchor tag -
And as a result, you will get all the results parsed -
You can pass this using your function onclick="bb7(this);"
then in JavaScript part use setAttribute in you function: bb2(this){this.setAttribute("id","someID");}

simple form validation with jquery serialize() function

$(document).ready(function(){
$('#send').click(function() {
var names = $('#appontment_form').serialize();
//this is how my names variable look like
//doctor=Dr.Fathmath+Shahuda&date=2013-02-27&time=1900+-+1700&phone=
var doc = $(names).filter('doctor');
if(doc !='')
{
$.ajax({
type: "post",
url: "../../includes/jqueryRequireFiles/appointmentSave.php",
data:names,
success: function(data)
{
$('#confir').text('Your Appointment Received..');
}
});
return false;
}
});
});
I have a appontment form. when i click send link it will grab all the values in the textboxs and put it in the names variable through serialize() function. i want to filter the names variable and find out if any of the field is left not filled.. if only if then i will make the ajax part.. but its not working...any help
When you use $.serialize() the variable content looks like ?key=value1&key=value2. If you want to validate the form, just do it without serialize like
var found_errors = false;
if($('#formfield1').val().trim() == "") {
//Handle errors if field is empty
found_errors = true;
}
And if no errors are found, serialize the form and send it.
Consider using jQuery validation plugin.
http://docs.jquery.com/Plugins/Validation

Categories

Resources