I'm building a form with a single field and a submit button. A user enters a value, clicks the button and the value is sent to a .ajax method which sends a POST request to the Google Shopping API.
At the moment, whenever I try and run the method once the submit button is clicked the JSON response isn't being received. As soon as I remove the code on button click, it reappears.
Any help would be great.
<!DOCTYPE html>
<html>
<head>
<style>
#images { padding:0; margin:0; overflow: hidden;}
#images img { width:200px; height:200px; border:none;}
#lists li { display: table;}
#lists img { width:200px; height: 200px; }
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<h1 id="title"></h1>
<p id="description"></p>
<div id="images"></div>
<div id="lists"></div>
<form id="myform">
<input type="text" name="myanswer" value="test">
<input type='submit' class="button" name="submitButton" value='submit'>
</form>
<script>
var apiKey = "key-removed-from-stackoverflow";
var country = "US";
var apiurl = "https://www.googleapis.com/shopping/search/v1/public/products?callback=?";
$(document).ready(function() {
$('.button').live('click', function() {
$.ajax({
type: "POST",
url: apiurl,
dataType: 'jsonp',
data :
{
key: apiKey,
country: country,
q: "star"
},
success: function(data) {
$.each(data.items, function(i, item){
if (item.product.images.length > 0) // sanity check
{
//global variables
var link = item.product.images[0]['link'];
var title = item.product.title;
var listData = "<li>" + title + "</li>" + '<img title="' + title + '" src="' + link + '" />';
$('#lists').append(listData);
var img = $("<img/>").attr("src", link);
$("<a/>").attr({href: link, title: "Courtesy of James"}).append(img).appendTo("#images");
console.log(data)
}
});
// console.log(data);
console.log(data)
}
});
});
});
</script>
</body>
</html>
add e.preventDefault() to your handler. Also remember to pass in the event parameter into the function too...
$('.button').live('click', function (e) {
e.preventDefault();
//rest of your code
});
Also, there is no reason to use .live() in this situation. I'd just bind it directly to the element -
$('.button').click(function () {
});
Related
when user click on a button it displays the dynamic data fetched from the database along with the appropriate check box ..so user has select or check the checkbox of some data and submit the result then those data are stored in database.
again that user clicked the same button then again those data are displayed but this time the data which are selected buy the user previously should be checked. I am trying to do that but enable to write code for it in jquery.
below is my code...
javascript
$(document).ready( function() {
$('#location_choose').click(function(e){
branch();
document.getElementById('brn_light').style.display='block';
document.getElementById('fade').style.display='block';
});
function branch()
{
//alert(user_id);
$.ajax({
url: "<?php echo base_url(); ?>/login/branch",
data: {},
type: "post",
cache: false,
success: function (data)
{
//alert(data);
var obj = $.parseJSON(data);
var result = "";
<?php foreach($resultsb as $rows){?>
for ( var i = 0; i < obj.length; i++ )
{
result+="<table id='branchtable'><tr height='25px' ><td>  </td><td ><input class='test' type='checkbox' name='branch_name' value="+obj[i].id+"<?php echo ($rows['branch_id']=="+obj[i].id+"? 'checked' : '');?>></td><td width='15px'></td><td width='630px'><b>"+obj[i].branch_name+
"</b></td></tr><tr><table id='branch_address' style='background-color:#EBF5FB'><tr><td>  </td></tr><tr><td width='60px'></td><td width='440px'>"+obj[i].address+"</td><td width='40px'></td></tr><td> </td></table></tr><tr></tr></table>";
}
<?php }?>
//alert(result);
document.getElementById("branch_table").innerHTML=result;
},
error: function (xhr, ajaxOptions, thrownError)
{
//alert(thrownError);
}
});
}
});
i tried using
<?php echo ($rows['branch_id']=="+obj[i].id+"? 'checked' : '');?>
in above code but still it doesnt checked the previous selected one.
Give The Same Class of Checkbox and Write Jquery Code
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$( document ).ready(function() {
$( '.select_all_text').click(function() {
var is_check = $(".select_type").prop('checked');
if(is_check == false)
{
$(".select_type").prop('checked', true);
$(''.select_all_text").text('De-select All');
}
else
{
$(".select_type").prop('checked', false);
$('.select_all_text").text('Select All');
}
});
});
</script>
</head>
<body>
<p style="position: sticky; z-index: 100; width: 50%;"><a id="select_all" onclick="check_uncheck" style="margin-right: 2%;" href="javascript:void(0)">Select all</a>
<?php
foreach($data_list as $data)
{
?>
<input type="checkbox" name="select_type[]" value="<?php echo $item_id; ?>" class="select_type" id="select_type"/>
<?php
}
?>
</body>
</html>
I want to pass the jquery value "selected" to fetchdata.php without reloading the page.
How can I do this?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"
type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.min.js" type="text/javascript">
</script>
<script>
$(document).ready(function() {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass() {
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if (selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" + selected, //The data your sending to some-page.php
success: function()
{
console.log("AJAX request was successfull");
},
error: function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
} else
{
alert("Please at least one of the checkbox");
}
}
</script>
</head>
<body>
<div id="checkboxlist">
<div><input type="checkbox" value="1" class="chk"> Value 1</div>
<div><input type="checkbox" value="2" class="chk"> Value 2</div>
<div><input type="checkbox" value="3" class="chk"> Value 3</div>
<div><input type="checkbox" value="4" class="chk"> Value 4</div>
<div><input type="checkbox" value="5" class="chk"> Value 5</div>
<div>
<input type="button" value="Get Value Using Class" id="buttonClass">
</div>
</html>
fetchdata.php
<?php
foreach($_GET['val'] as $r)
{
print_r($r);
}
?>
I am using the GET method to receive the data and the for-each loop to print the array, but I am not getting any values in the PHP file.
change the ajax function like below and make sure about the fectdata.php in the same folder or give the correct path.
$.ajax({
url: 'fetchdata.php',
type:'GET',
data: {val:selected},
success: function(data) {
console.log("AJAX request was successfull");
}
});
Check if the path to your script is correct:
url: 'fetchdata.php',
Is this script in your doc root?
change the following in your code,
in fetchdata.php
<?php
$valArray = explode('#',$_GET['val']);
foreach($valArray as $val){
echo $val."<br/>";
}
?>
In html File,
$(document).ready(function () {
$("#buttonClass").click(function() {
getValueUsingClass();
});
});
function getValueUsingClass(){
var chkArray = [];
$(".chk:checked").each(function() {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected;
selected = chkArray.join('#') + "#";
if(selected.length > 1)
{
$.ajax({
url: "fetchdata.php", //This is the page where you will handle your SQL insert
type: "GET",
data: "val=" +selected.toString(), //The data your sending to some-page.php
success: function(data1) {
$("#resultDiv").html(data1);
console.log("AJAX request was successfull");
},
error:function()
{
console.log("AJAX request was a failure");
}
});
//alert("You have selected " + selected);
}else
{
alert("Please at least one of the checkbox");
}
}
include the div after a button like
<div id="resultDiv"></div>
To begin, I'm working with 3 languages. HTML, Javascript and PHP. I'm unable to pass user inputted textarea text to a PHP variable which would be used as a message in an email that would be sent out. What I believe to be the problem is that my textarea is actually in a modal window and for some reason I think that is what is screwing things up.
Here is my HTML Code:
<div class="rejectModal" title="rejectModal" id="rejectModal" style="display: none; padding:15px ">
<form name="rejectForm" action="">
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43">{$rejectAreaNote}</textarea>
<input type="button" value="Reject" class="btn success" id="submitReject" name="Reject" />
<input class="btn" type="reset" value="Cancel" id="btnCancelSaveModal" />
</form>
</div>
JS Code:
$(function() {
$(".submitReject").click(function() {
// validate and process form here
$('.error').hide();
var rejectAreaNote = $("textarea#rejectArea").val();
var noteLength = rejectAreaNote.length;
if (rejectAreaNote == "" || noteLength < 5) {
$("label#rejectArea_error").show();
$("textarea#rejectArea").focus();
return false;
}
var dataString = rejectAreaNote;
alert (dataString);
//return false;
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: {
"Reject" : "Reject",
"rejectAreaNote" : "rejectAreaNote"
},
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Submitted!");
}
});
return false;
});
});
What creates the Modal (JS):
$('.rejectModal').css("background", "lightblue");
$('#btnRejectDocument').bind(isTouchScreen ? "touchstart" : "click", function(){
if (!gsSelection.unselectElem()) return false;
$('.rejectModal').dialog({
modal:true,
resizable:false,
width: 400,
}).removeClass("ui-widget-content");
$(".ui-dialog-titlebar").hide();
return;
});
$('#btnRejectDocumentModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
$('#btnCancelSaveModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
PHP Code:
if(isset($_POST['Reject'])&&$_POST['Reject']=='Reject')
{
$isReject = true;
RejectAction($DocumentID, $ClientName, $ClientEmail);
$smartyvalues["isReject"] = $isReject;
$smartyvalues["RejectMsg"] = "successfully rejected!";
}
Also pretty new tot his
Any help is greatly appreciated.
Textarea does not have a value attribute. If you want to add a value to your textarea, add it inside the tag: <textarea>value</textarea>
So try changing it to this:
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43"/>{$rejectAreaNote}</textarea>
if(isset($_POST['Reject']) ...
You are not sending this to the server. Instead, you're sending "dataString", which is just the text from textarea. What you should do instead is send an object with needed fields:
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: {
"Reject" : "Reject",
"rejectAreaNote" : "rejectAreaNote"
},
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Submitted!");
}
});
I'm still not sure what your code is supposed to do and how it glues together, but this here is definitely wrong.
I am confused a little bit and I have no clues what am I looking for.
Although I will post here important parts so you may figureout and help me.
A part of PHP file:
if (empty($vid) || empty($entry)) {
$broken = TRUE;
}
if(!$broken) {
$video = parseVideoEntry($entry);
echo "
<div class=\"video_wrap\">
<div class=\"video_thumbnail\">
<a href=\"{$video->watchURL}\">
<img src=\"$video->thumbnailURL\">
</a>
</div>
</div>
<!-- More of structure parts here -->
";
}
A part of HTML structure:
<form action="" method="GET" style="margin: 5% 0;" id="youtube_fetch">
<input type="text" name="id" value="https://www.youtube.com/watch?v=VIDEO_ID_HERE" id="videoID_input" />
<input type="submit" id="fetch_submit" />
</form>
A part of jQuery / Ajax call:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else
console.log(state);
}
});
e.preventDefault();
});
Ok so when I put valid youtube ID into the input field, it will return the else from ajax call (echo the html structure in console log).
The part that I don't know how to deal with is: "How to get that echoed HTML content/structure and append it into the <div id="youtube_content"></div> for example or directly to the body.
Use the .html() method:
$('#youtube_content').html(state);
References:
.html() - jQuery API Documentation
If I understand your question correctly:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else {
$('<div />', {
id: 'youtube_content'
}).appendTo('body');
$('#youtube_content').html(state);
}
}
});
e.preventDefault();
});
i am building one form with fancy box, form work fine but i could not get value from text box.
my java script is
$(function () {
$("#button").click(function () {
var yourName = $("input#yourName").val();
alert(yourName);
if (yourName == "") {
$('input#yourName').css({
backgroundColor: "#F90"
});
$("input#yourName").focus();
return false;
}
$.ajax({
type: "POST",
url: "bin/form1.php",
data: $("#login_form").serialize(),
context: document.body,
success: function (res) {
var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
success = success.replace(/^\s*|\s*$/g, "");
var RegularExpression = new RegExp(success);
if (RegularExpression.test(res)) {
alert('Message Sent');
$.fancybox.close();
} else {
alert('Error While processing');
}
},
});
return false;
});
});
now my html is
<div style="display:none; height:450px">
<form id="login_form" action="">
<p id="login_error">
Please, enter data
</p>
<input type="hidden" name="action" value="send_friend_post" />
<label for="yourName" style="margin-right:110px;">
<?php _e( 'Your name', 'newcorp') ; ?>
</label>
<input id="yourName" type="text" name="yourName" value="" class="text_new " />
<br/>
<input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
</form>
</div>
i am opening this fancy box popup from
<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>
every thing work fine but i can't get value of yourName even alert is showing blank.
Thanks
instead of this
var yourName = $("input#yourName").val();
try
var yourName = $("input[name='yourName']:text").val();
this will make ur function read the value of text box .
Firstly, with your form, it should be better to use
$(document).on('submit', 'form', function () { ... })
instead of
$(document).on('click', '#myButton', function () { ... })
Secondly, you should encapsulate your code into $(document).ready(function () { .. });
Here is a working example ;) http://jsfiddle.net/aANmv/1/
Check that the ID of Your input is not changed by fancybox at the time of opening the popup.
Instead of directly catching up the click event try to live the event if using jQuery 1.7 > or on when using jQuery 1.7 <.
live:
$("#button").live('click', function() { ... });
on:
$("#button").on('click', function() { ... });
Also try to load the javascript after the DOM is loaded:
$(document).ready(function(){
$("#button").live('click', function() { ... });
...
});
Instead of that
$(function() {
try
$(document).ready() {
this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.