how to reload a div with form content using jquery ajax - javascript

I am working on creating an online visitor chat software using PHP and MySQL. What am i trying to do is load the page on clicking the submit button
id for submit button: send
id for visitor:vid
id for chat:cid
Below is the code snippet for Ajax request made by the code but it is not working.
I have put few alerts within the codes to test whether the function is working fine or not and the function is not working.
Please help me out.
Any other method is also accepted
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#send").click(function() {
var cid = $("#cid").val();
var vid = $("#vid").val();
var usermsg = $("#usermsg").val();
var submitmsg = $("#submitmsg").val();
var dataString = 'cid='+ cid + '&vid=' + vid + '&usermsg=' + usermsg;
alert(datastring);
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
success:function(result){
alert(result);
}});
});
</script>

Wrap your click function under
jQuery(document).ready(function($){
// your click event here
});

Change your code to:
<script type="text/javascript">
$(document).ready( function() {
$("#send").click(function() {
var cid = $("#cid").val();
var vid = $("#vid").val();
var usermsg = $("#usermsg").val();
var submitmsg = $("#submitmsg").val();
var dataString = 'cid='+ cid + '&vid=' + vid + '&usermsg=' + usermsg;
alert(datastring);
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
success:function(result){
alert(result);
}});
});
});
</script>

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.

Need to get some value of variable from linked lists

I have some page with form, which loading some data to POST when i submit it. Then it links user to the next page. On this page I catch data from POST, and I have two dropdownlists, where the second one depends on the first. The first get's value from POST data:
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'"); </script>';
Where $GLOBALS["i"] = id from DB, which has kept in data from POST by previous page.
But it doesn't work for the second dropdownlist which depends on it:
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
I think it can be from the part of code, which realises depending of the second dropdown list:
<script>
jQuery(function(){
var id = jQuery(".mark").val();
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
jQuery(".mark").change(function(){
var id = jQuery(".mark").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
});
Where "mark" - first dropdownlist, "comm" - the second one.
This is the first part of my problem.
The second: I have some value on the page which depends on the value of the second dropdownlist. I tried to:
jQuery(".comm").change(function(){
var id = jQuery(".comm").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function(data){
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type:"POST",
url: "../wp-content/price.php",
data: {price1: price1,price2: price2,price3: price3,price4: price4,price5: price5,price6: price6,price7: price7,price8: price8, price9: data},
success: function(data){
jQuery(".summPrice").html(data);
}
});
}
});
But it works only one time, and i don't know why.
I'll be glad for any offers.
I don't have a full visibility of the rendered html and of the ajax responses, but I would give a try with:
Remove this lines
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'");
</script>';
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
And do something like this where you print the html
...
<select id="markid" data-val="<?php echo isset($GLOBALS["i"]) ? $GLOBALS["i"] : -1;?>"></select>
<select id="comm" data-val="<?php echo isset($GLOBALS["i1"]) ? $GLOBALS["i1"] : -1;?>"></select>
And in your javascript have something like
<script>
(function ($) {
//when everything is ready
$(fillUpCommOptions);
$(watchSelectsChanges);
function fillUpCommOptions() {
var id = $('#markid').data('val') ? $('#markid').data('val') : $('#markid').val();
$('#markid').removeAttr('data-val');//remove data-val, at next change event we want the select new val
$.ajax({
type: "POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function (data) {
//assuming data is something like
// '<option value="niceValue">nice value</option>
$("#comm").html(data);
if ($("#comm").data('val')) {
//apply values from post also for the second dropdown
// assuming that data contains and option with value == $("#comm").data('val')
$("#comm").val($("#comm").data('val'));
$('#comm').removeAttr('data-val');
$("#comm").change()//trigger change after setting the value
}
}
});
}
function watchSelectsChanges() {
$('#markid')
.off('change')//just in case, could not be needed
.on('change', fillUpCommOptions);
$('#comm')
.off('change')//just in case, could not be needed
.on('change', handleDependentValues);
}
function handleDependentValues() {
var id = $("#comm").val();
if (id) {
$.ajax({
type: "POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function (data) {
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type: "POST",
url: "../wp-content/price.php",
data: {
price1: price1,
price2: price2,
price3: price3,
price4: price4,
price5: price5,
price6: price6,
price7: price7,
price8: price8,
price9: data
},
success: function (data) {
jQuery(".summPrice").html(data);
}
});
}
})
}
}
})(jQuery);

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);

Data variable in jquery ajax function

I'm trying to use the code below, but it's not working:
UPDATED WORKING:
$(document).ready(function() {
$('.infor').click(function () {
var datasend = $(this).html();
$.ajax({
type: 'POST',
url: 'http://domain.com/page.php',
data: 'im_id='+datasend',
success: function(data){
$('#test_holder').html(data);
}
});
});
});
As you can see I used $datasend as the var to send but it doesn't return the value of it, only its name.
I would change
$datasend = $(this).html;
to
var datasend = $(this).html();
Next I would change
data: 'im_id=$datasend',
to
data: 'im_id='+datasend,

XML error in JavaScript file

When I execute this JavaScript file in Firefox;
<script type="text/javascript" >
$(function () {
$(".comsubmit").click(function () {
var comsn = $("#comsn").val();
var comrn = $("#comrn").val();
var compic = $("#compic").val();
var comment = $("#comment").val();
var eventid = $("#eventid").val();
var dataString = 'comsn=' + comsn + '&comrn=' + comrn + '&compic=' + compic + '&comment=' + comment + '&eventid=' + eventid;
if (comment == '') {
alert('Must Type Comment to Post Comment');
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="assets/uploading.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "comments_post.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
</script>
I get this error
Error: missing } in XML expression
Line: 31, Column: 2
Source Code:
}); });
The arrow points inbetween the first semi colon and the space.
What can I do to fix this error?
Few remarks about your code:
You don't need the cache: false option as you are performing a POST request.
Instead of concatenating the parameters into dataString let jQuery handle formatting and escaping:
$.ajax({
type: "POST",
url: "comments_post.php",
data: {
comsn: comsn,
comrn: comrn,
compic: compic,
comment: comment,
eventid: eventid
},
success: function (html) {
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
Check the Content-Type header returned by comments_post.php. If it is not properly set (for example if it is set to text/xml), jQuery might try to parse the returned XML, while in reality you are returning HTML.
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<font family="Arial" color="red" ><span style="font-size: x-small;"><script style="text/javascript" src="http://sites.google.com/site/attachanu/home/scrollingnew.js?attredirects=0&d=1"> </script>
<script style="text/javascript">
var nMaxPosts = 20;
var sBgColor;
var nWidth;
var nScrollDelay = 75;
var sDirection="left";
var sOpenLinkLocation="N";
var sBulletChar="•";
</script>
<script style="text/javascript" src="http://hackerz7.blogspot.com/feeds/posts/default?alt=json-in-script&callback=RecentPostsScrollerv2">
</script></span></font>
I think the HTML you are passing from the Ajax call is not properly formated. Can you add an alert and make sure it looks OK?

Categories