PHP Serialize on ajax array Not Working - javascript

I have the following HTML fields being created inside a PHP look
<td><input type=\"checkbox\" name=\"investigator_id[]\" id=\"investigator_id\" value=\"$name_degree[$i]\">
<td><input type=text name=\"inv_rank[]\" id=inv_rank maxlength=\"2\" size=\"2\"></td>
<td><textarea name=\"inv_comm[]\" id=inv_comm rows=2 cols=20></textarea></td>
I am trying to save the data in these fields by calling a jquery function based on clicking on this button
Here is the script that is being called. I know that the js is being called because the "alert("now")" is poping up, but the dataString is not being populated correctly. I tested this on http://jsfiddle.net/ and it worked fine, but won't work on my site.
<script>
$(document).ready(function() {
$("#submit").click(function() {
alert("now");
var dataString = $("'[name=\"investigator_id\[\]\"]', '[name=\"inv_rank\[\]\"]','[name=\"inv_comm\[\]\"]'").serialize();
alert("ee"+dataString);
$.ajax({
type: "POST",
url: "save_data.php",
dataType: "json",
data: dataString,
success: function(data){
alert("sure"+data);
$("#myResponse").html(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error.");
}
});
});
});
</script>

Try this with the help of FormID like this:
<form method="post" id="yourFromID">
//Your form fields.
</form>
JS Code:
$("#yourFromID").submit(function (e){
e.preventDefault();
var dataString = $(this).serialize();
// then you can do ajax call, like this
$.ajax({
url: 'site.com',
data: dataString,
methodL 'post',
success: function(){...}
})
return false;
});

Related

Fetch Data in a form through Ajax in Laravel

I am making an auto-complete form, in which user enter only the id and the whole information related to that id comes in other field. I am using ajax and Laravel 5.4. The Data is coming in alert but how i can insert data in input fields of a form. Here is my script:
<script type="text/javascript">
$('#submitid').on('click', function() {
var vid = $( "#vid" ).val();
//var id=$(this).data('id');
$.ajax({
url: '/inquiryVendor',
type: "Get",
data:{id:$("#vid").val()}, // the value of input having id vid
success: function(response){ // What to do if we succeed
alert(response); console.log(response);
}
});
});
</script>
this is my controller:
public function VendorDetail(Request $request)
{
$id= $request->id;
$data = DB::select(DB::raw("SELECT * from bp where id = '$id'"));
echo json_encode($data);
}
here is my console.log response:
[{"id":37,"card_name":"Maka Furniture Co.,Ltd ","trade_type":"Manufacturer","address":"Xinzhang development zones,Shengfang town,Hebei province.","fc":"121AC209","status":0,"created_at":"2018-10-10 10:02:27","user":"admin"}]
here is the screenshot of response:
Any help would be highly appreciable.
If you want all data in single input you can use this
<script type="text/javascript">
$('#submitid').on('click', function() {
var vid = $( "#vid" ).val();
//var id=$(this).data('id');
$.ajax({
url: '/inquiryVendor',
type: "Get",
dataType: 'json',//this will expect a json response
data:{id:$("#vid").val()},
success: function(response){
$("#inputfieldid").val(response);
}
});
});
</script>
or if you want on different input field you can do like this
<script type="text/javascript">
$('#submitid').on('click', function() {
var vid = $( "#vid" ).val();
//var id=$(this).data('id');
$.ajax({
url: '/inquiryVendor',
type: "Get",
dataType: 'json',//this will expect a json response
data:{id:$("#vid").val()},
success: function(response){
$("#inputfieldid1").val(response.id);
$("#inputfieldid2").val(response.2ndcolumnName);
$("#inputfieldid").val(response.3rdcolumnName);
}
});
});
</script>
In your other fields you can do the following in success method:
success: function(response) {
$('.input1').val(response.input1);
$('.input2').val(response.input2);
$('.label1').html(response.label1);
}
I hope it would helpful.
add unique ID property to your input like this:
<input id="name" type="text">
Then fill this input with ajax result by this code:
<script type="text/javascript">
$('#submitid').on('click', function() {
var vid = $( "#vid" ).val();
//var id=$(this).data('id');
$.ajax({
url: '/inquiryVendor',
type: "Get",
data:{id:$("#vid").val()}, // the value of input having id vid
success: function(response){ // What to do if we succeed
$('#name').val(JSON.parse(response)[0].name); //<---- This line,
}
});
});
</script>
Do this for all your input base you logic.
Suppose you have input fields like this in your form
<input type="text" name="vendor_name" id="vendor_name">
<input type="text" name="vendor_mobile" id="vendor_mobile">
<input type="text" name="vendor_email" id="vendor_email">
You ajax code should be like this and I hope you get the parameters in your JSON response
<script type="text/javascript">
$('#submitid').on('click', function() {
var vid = $( "#vid" ).val();
//var id=$(this).data('id');
$.ajax({
url: '/inquiryVendor',
type: "Get",
data:{id:$("#vid").val()}, // the value of input having id vid
success: function(response){ // What to do if we succeed
$('#vendor_name').val(response.vendor_name)
$('#vendor_mobile').val(response.vendor_mobile)
$('#vendor_email').val(response.vendor_email)
}
});
});
</script>
If this can't help then could you please do console.log(response) and paste the debug data so it will be easy to help you more.
<script type="text/javascript">
$('#submitid').on('click', function() {
var vid = $( "#vid" ).val();
//var id=$(this).data('id');
$.ajax({
url: '/inquiryVendor',
type: "Get",
data:{id:$("#vid").val()}, // the value of input having id vid
success: function(response){ // What to do if we succeed
console.log(response)
}
});
});
</script>
if you don't want response[0] then you need to change in your controller File like this.
$vendor = DB::table('bp')->where('id', '.$id.')->first();
return response()->json($vendor);
As per your need, this will help for sure.

jquery window.location.assign() not working

I'm sending form data via jquery and cannot get the window.location.assign() to fire off. I am getting a successful submission. I've also tried window.location.href =
<form>
<div>
<a id="submitDesk" type="button" class="btn submitDesk">Submit Request</a>
</div>
</form>
$( document ).ready(function() {
$( "#submitDesk" ).click(function() {
var firstname = document.querySelector('#firstname').value;
var lastname = document.querySelector('#lastname').value;
var email = document.querySelector('#email').value;
$.ajax({
type: "POST",
url: "http://foo.com/desk.php",
dataType: 'json',
data: 'firstname='+ firstname + '&lastname='+ lastname+ '&email=' + email + '&location='+ location,
success: function(data) {
console.log(data);
window.location.assign('/thank-you/');
}
});
});
});
Kindly use below. data parameter string was not proper, String was getting break, SO i have added " ' " to make it a proper string.
$.ajax({
type: "POST",
url: "http://foo.com/desk.php",
dataType: 'json',
data: 'firstname='+ firstname + '&lastname='+ lastname+ '&email='+ email+ '&location='+ location,
success: function(data) {
console.log(data);
window.location.assign('http://foo.com/thank-you/');
}
});
The backend file was sending incorrect responses causing there to always be an error even though the form was a success.

LARAVEL: Use a javascript variable in php

I would like to get an id from a button. I need this id in my ajax request. This is my button:
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
I'm getting the id of the button this way:
<script type="text/javascript">var JcarID = this.id;</script>
Finally my Ajax Request.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '{{ action('CarController#delete', [$user->id, $car->id])}}',
success: function (data)
{
// alert(data);
}
});
});
Thx for reading!
SOLUTION
Changed some bits in my code. I changed the url of my request.
$('[name="deletecar"]').click(function (e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/deletecar/'+this.id,
success: function (data)
{
// alert(data);
}
});
});
Hard to guess what is your requirement yet either if you want to get the button id value
this.attr('id'); or this.prop('id');
Or if you want to set the id value of button
$('[name="deletecar"]').attr('id', yourvalue)
I think you want to use JcarId rather $car->id in ajax request. Here what you can do rather than directly using PHP code in ajax call.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '/CarController/delete',
data: {'carId':JcarId}
success: function (data)
{
// alert(data);
}
});
});

Updating div content after form submit without page reload

alright, I have a popup which displays some notes added about a customer. The content (notes) are shown via ajax (getting data via ajax). I also have a add new button to add a new note. The note is added with ajax as well. Now, the question arises, after the note is added into the database.
How do I refresh the div which is displaying the notes?
I have read multiple questions but couldn't get an answer.
My Code to get data.
<script type="text/javascript">
var cid = $('#cid').val();
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid="+cid,
dataType: "html", //expect html to be returned
success: function(response){
$("#notes").html(response);
//alert(response);
}
});
});
</script>
DIV
<div id="notes">
</div>
My code to submit the form (adding new note).
<script type="text/javascript">
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: { note: note, cid: cid }
}).done(function( msg ) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();
//$("#notes").load();
});
});
</script>
I tried load, but it doesn't work.
Please guide me in the correct direction.
Create a function to call the ajax and get the data from ajax.php then just call the function whenever you need to update the div:
<script type="text/javascript">
$(document).ready(function() {
// create a function to call the ajax and get the response
function getResponse() {
var cid = $('#cid').val();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "ajax.php?requestid=1&cid=" + cid,
dataType: "html", //expect html to be returned
success: function(response) {
$("#notes").html(response);
//alert(response);
}
});
}
getResponse(); // call the function on load
$("#submit").click(function() {
var note = $("#note").val();
var cid = $("#cid").val();
$.ajax({
type: "POST",
url: "ajax.php?requestid=2",
data: {
note: note,
cid: cid
}
}).done(function(msg) {
alert(msg);
$("#make_new_note").hide();
$("#add").show();
$("#cancel").hide();}
getResponse(); // call the function to reload the div
});
});
});
</script>
You need to provide a URL to jQuery load() function to tell where you get the content.
So to load the note you could try this:
$("#notes").load("ajax.php?requestid=1&cid="+cid);

problem in get value by ".serialize()"?

i want after click on #value(VALUE) get value input:checkbox with .serialize() ?
EXAMPLE: http://jsfiddle.net/tKBJ2/40/
$('#value').click(function(e){
e.preventDefault();
alert("this alert only after click on '#value'");
$('.table_show tr').each(function(){
if ($(this).prop('checked')) {
var dataString = $('.table_show').serialize(); // This don't work
alert(dataString);
$(this).parent().parent().fadeOut("slow");
$.ajax({
type: "POST",
url: "http://localhost/admin/customer_size/delete",
data: dataString,
cache: false,
success: function(){
},
error: function(data){
alert('Load was performed.');
}
})
}
})
});
serialize() is used to get query string from the inputs of a form, you should check if the selector select a form element or not.
cf jquery doc : http://api.jquery.com/serialize/
Encapsulate your div table_show in a form, and do serialize on this form:
<form class="myForm">
<div class="table_show">
rest of your code
</div>
</form>
Then in your js :
var dataString = $('.myForm').serialize();

Categories