JavaScript/Ajax - Send Data and Receive response with multiple variables - javascript

Here is my JavaScript code for sending the post action:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var ColorId = "1";
$( "#targetButton" ).click(function() {
$.ajax({
url: 'checkcolors.php',
type: 'post',
dataType: 'json',
success: function (data) {
var arr = data.msg.split(',');
arr.forEach(function(id){
$('#' + id.trim()).hide();
});
//$('#target').html(data.msg);
},
data: ColorId
});
});
});
</script>
<button type="button" id="targetButton">Send</button>
<div style="BlackAndWhite" id="24604682">24604682</div>
<div style="BlackAndWhite" id="24604682x">24604682x</div>
<div style="BlackAndWhite" id="24604679">24604679</div>
<div style="BlackAndWhite" id="24604621">24604621</div>
Here are the results from checkcolors.php:
24604603, 24604684, 24604640, 24604609, 24604682, 24604686, 24604681, 24604689, 24604602, 24604679, 24604680, 24604622, 24604685, 24604683, 24604621, 24604677, 24604688,
I can make them to be printed like this also:
24604603
24604684
24604640
24604609
24604682
24604686
24604681
24604689
24604602
24604679
24604680
24604622
24604685
24604683
24604621
24604677
24604688
I can make these numbers to be formated however i want.
What i have to do!
I have html div elements with the same ids that the result is returning.
When these numbers are returned i have to hide all div elements with the ids shown from checkcolors.php response.
How can i do that ?
Thanks in advance!

Here's a very crude way to do it:
<script type="text/javascript">
function send() {
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$('#target').html('sending..');
$.ajax({
url: 'checkcolors.php',
type: 'post',
dataType: 'json',
success: function (data) {
var arr = data.msg.split(',');
arr.forEach(function(id){
$('#' + id.trim()).hide();
});
//$('#target').html(data.msg);
},
data: person
});
}
</script>

Why style="BlackAndWhite" can be a class="BlackAndWhite" ???
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var ColorId = "1";
$( "#targetButton" ).click(function() {
$.ajax({
url: 'checkcolors.php',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
var arr = data.split(',');
var html = "";
arr.forEach(function(id){
html += "<div style='BlackAndWhite' id='" + id + "'>" + id + "</div>";
});
$('#target').html(html);
},
data: ColorId
});
});
});
</script>
<button type="button" id="targetButton">Send</button>
<div id="target"></div>

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.

How to get Pinterest Total Share Count Using Javascript?

What i require? I need to get a total share count using javascript.
Using this link: https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=http://google.com
I can get the result:
receiveCount({"url":"http://google.com","count":11278})
My code which is not working, i'm not sure which part of the code is wrong. Below:
#pin-div {
color: red
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<div id="pin-div">0</div>
<script type="text/javascript">
$(function() {
var url = "http://facebook.com";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
success: function(result) {
$.each(result, function(key, val) {
console.log(key + " - " + val["receiveCount"]["count"]);
var shareCount = val["receiveCount"]["count"];
$("#pin-div").html(shareCount);
});
}
});
});
</script>
Your data is jsonp: receiveCount({"url":"http://google.com","count":11278}). Where the receiveCount function must be created in the window context to hold the data.
You need to add: dataType: "jsonp" in your $.ajax code.
You can try with this version of your code:
#pin-div {
color: red
}
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<div id="pin-div">0</div>
<script type="text/javascript">
$(function() {
var url = "http://facebook.com";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
dataType: "jsonp",
success: function(result) {
receiveCount(result);
}
});
});
function receiveCount(data) {
$("#pin-div").html(data.count);
}
</script>

HTML Button Not Reappearing After Being Clicked

As you can see here when you click a 'METAR' button one after the other, the previous button reappears when the next one is clicked.
However, when you click the 'Total Users Online on VATSIM' button, followed by one of the 'METAR' buttons, the 'Total Users Online on VATSIM' button does not reappear.
My code is located in this Pastebin.
The JavaScript for the 'Total Users Online on VATSIM' button is as follows:
<script type="text/javascript">
$(document).ready(function() {
var userButtons = $('.getUserButtons');
userButtons.click(function(){
var clickedButton = $(this);
$.ajax({
type: "POST",
url: "/online.php",
dataType: 'html',
success: function(data) {
$('#outputDiv').hide('slow', function() {
$(this).remove();
});
userButtons.show('slow');
var outputElement = $('<div id="outputDiv" style="color: white;">' + data + '</div>');
outputElement.hide();
outputElement.insertAfter(clickedButton);
clickedButton.hide('slow', function() {
outputElement.show('slow');
});
},
error: function(jqXHR) {
alert(jqXHR.responseText);
}
});
});
});
</script>
The code for the button itself is as follows:
<li><button style="height: 40px;" class="btn btn-primary getUserButtons hvr-float-shadow">Total Users Online on VATSIM</button></li>
Any assistance would be appreciated. I think I need to edit the code so that clicking one of the 'METAR' buttons then tells the 'Total Users Online on VATSIM' to reappear; I don't know how though.
Thanks!
add getMetarButtons class to Total Users Online on VATSIM as well
Finally fixed the issue. Here it is:
script type="text/javascript">
$(document).ready(function() {
var metarButtons = $('.getMetarButtons');
var userButtons = $('.getUserButtons');
metarButtons.click(function(){
var clickedButton = $(this);
$.ajax({
type: "POST",
url: "metarData.php",
data: { location: clickedButton.attr('data-location') },
dataType: 'json',
success: function(data) {
$('.metarOutput').hide('slow', function() {
$(this).remove();
});
$('#outputDiv').hide('slow', function() {
$(this).remove();
});
metarButtons.show('slow');
userButtons.show('slow');
var outputElement = $('<div id="outputDiv"' + data['location'] + ' style="color: white;" class="metarOutput">' + data['metar'] + '</div>');
outputElement.hide();
outputElement.insertAfter(clickedButton);
clickedButton.hide('slow', function() {
outputElement.show('slow');
});
},
error: function(jqXHR) {
alert(jqXHR.responseText);
}
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var metarButtons = $('.getMetarButtons');
var userButtons = $('.getUserButtons');
userButtons.click(function(){
var clickedButton = $(this);
$.ajax({
type: "POST",
url: "online.php",
dataType: 'html',
success: function(data) {
$('.metarOutput').hide('slow', function() {
$(this).remove();
});
$('#outputDiv').hide('slow', function() {
$(this).remove();
});
metarButtons.show('slow');
userButtons.show('slow');
var outputElement = $('<div id="outputDiv" style="color: white;">' + data + '</div>');
outputElement.hide();
outputElement.insertAfter(clickedButton);
clickedButton.hide('slow', function() {
outputElement.show('slow');
});
},
error: function(jqXHR) {
alert(jqXHR.responseText);
}
});
});
});
</script>

Suppressing and adding parameters for ajax call

I am trying to make an ajax call for two separate click events. The difference is for the second click event the variable testOne should not be part of the call and instead there would be a new variable. How should I approach this?
var varOne = '';
var varTwo = '';
var varThree = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: {
testOne: varOne,
testTwo: varOne
}
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
varOne = 'xyz123';
varTwo = '123hbz';
testAjax();
});
$('.clickTwo').click(function(){
//varOne = 'xyz123'; // I dont need this for this click
varTwo = '123hbz';
varThree = 'kjsddfag'; // this gets added
testAjax();
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
Make some like this
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data= {
varOne: 'xyz123',
varTwo: '123hbz',
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data= {
varThree : 'kjsddfag',
varTwo: '123hbz',
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
You can also do the same in other way with minimum line of code, you can call the ajax on click event and pass the data based on the element triggered the click event.
like this:
$('.ajax').click(function(e){
if($(this).hasClass('clickOne')){
var data= { varOne: 'xyz123'; varTwo: '123hbz'; }
}else{
var data= { varThree : 'kjsddfag'; varTwo: '123hbz'; }
}
$.ajax({
type: "POST",
dataType: 'json',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
e.preventDefault();
});
<div class="ajax clickOne"></div>
<div class="ajax clickTwo"></div>
In this way you can put as many conditions for different data variable.
You should be doing it like this:
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data {
varOne = 'xyz123',
varTwo = '123hbz'
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data = {
varTwo = '123hbz',
varThree = 'kjsddfag'
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
This way you absolute control over which variables are added to which ajax call. You should not use global variables unless you really need them to be global, which doesn't seem to be the case.
You can pass whatever JavaScript object to the data parameter of the ajax method.
I just wanted to add something. I often hide value inside the value attribute of the button tags to produce something like this.
I haven't been able to test this of course but I thought it was worth mentioning.
jquery:
var fields = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: fields
}).done(function(data) {
$('.result').html(data);
});
}
$('#btn').click(function(){
var varCount = 0;
var vars = $(this).val().split('|');
$.each( vars, function( key, value ) {
varCount++;
fields = fields + 'var' + varCount + '=' + value + '&';
});
fields = fields.slice(0,-1);
$(this).val('123hbz|kjsddfag');
testAjax();
});
html:
<button id="btn" value="xyz123|123hbz"></button>
A more optimized and cleaner version -
var varTwo='junk1'
var varOne='junk2'
var varThree='junk3'
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.ajaxClick').click(function(){
var data={};
if(this.classList.contains('clickOne')){
data.varOne=varOne;
data.varTwo=varTwo;
}else{
data.varThree=varThree;
data.varTwo=varTwo;
}
testAjax(data);
});
<div class="ajaxClick clickOne"></div>
<div class="ajaxClick clickTwo"></div>

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