Javascript String Var + jQuery Textbox Val - javascript

Anyone know why the following code doesn't seem to work? I'm trying to append whatever is in the textbox to the URL string.
$.ajax({
type: 'POST',
url: 'http://myurl.com/something.php?myname='+$('#myname').val(),
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20;
chart.series[0].addPoint(point[0], true, shift);
chart.series[1].addPoint(point[1], true, shift);
setTimeout(requestData, 5000);
},
cache: false
});

You did not let us know what is not working. $('#myname').val() should work if you really have a myname object.
However, I could not help noticing that you are requesting via POST, but at the same time you are building a query string. Try changing the type to GET and see how it goes.

May be the value of the element contains characters that can alter the meaning of query strings, e.g. if the value begins with &asdf, the url becomes http://myurl.com/something.php?myname=&asdf. If so, try this:
$.ajax({
type: 'POST',
url: 'http://myurl.com/something.php?myname=' + encodeURIComponent($('#myname').val()), // pass via GET
// I assume there is no data to pass -- uncomment otherwise
// data: {
// name1: value1,
// name2: value2,
// },
success:
.
.
.

I would recommend using a variable instead of doing it inline like so:
<script type="text/javascript>
$(document).ready(function(){
var name = $("#myname").val();
//any validation would occur here
var posturl = "http://myurl.com/something.php?myname" + name;
$.ajax({
type: 'POST',
url: posturl,
data: data,
success: success
dataType: dataType
});
});
</script>
<body>
<input id="myname" value="John Doe" />
</body>

Related

Unable to send multiple data parameters with jQuery AJAX

I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});

Pass variable string from javascript to php using ajax

How to pass a variable value from html page using javascript to php?
i created this code in my index.php
$amount = $_GET['pricenumb'];
echo $amount;
and this is my javascript code to call on click of button and send the data to the PHP file.
<script type="text/javascript">
$(".cell").on("click", "input:checkbox", function () {
var thiss = $(this);
var total = $("#price");
var target = $("label[for='" + thiss.attr("id") + "']");
var item_value = +(target.html().replace(/[^0-9\.]/g, "") || 0);
var cur_total = +(total.html().replace("$", "") || 0);
if (thiss.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
};
total.text("$" + cur_total);
});
</script>
<script type="text/javascript">
$("#pay_btn").on("click", function () {
var price = $("#price").text();
var pricenumb = price.replace(/[^0-9\.]/g, "");
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
cache:false,
success: function(){
}
});
});
</script>
and this is the checkbox,
<div class="cell">
<div class="form-check"><label for="check-a" class="form-check-label"><input id="check-a" class="form-check-input" type="checkbox">$166<span class="form-check-sign"></span></label>
<div class="mask visible-on-sidebar-regular">Buy Product</div>
</div>
</div>
the work code is, when I check the checkbox, it will update the div content, and I want when I click on pay button, get the div value via javascript and send the value to my index.php
You are using POST in your ajax and GET in php, chage your ajax to GET. Also, In your ajax change
type: "POST",
url: "forumdisplay.php?fid=2",
data: "price=" + price + "pricenumb="+ pricenumb,
to
type: "GET",
url: "forumdisplay.php",
data: {
price: price,
pricenumb: pricenumb,
fid: 2
}
That's not how you pass data in ajax. The correct format is to use curly braces and define props name and then value
data:{propName1: value1,propsName2: value2,propsName3: "Some string value"}
Which can be used in the file like this in case of POST request.
$_POST['propName1'] which will give value1 variable data as a result
$_POST['propName3'] which will give output as Some string value string
The value can be in quotes if it's a string or not in quotes if it's a variable. So you need to redefine your ajax data props to
$.ajax({
type: "POST",
url: "forumdisplay.php?fid=2",
data: {price: price ,pricenumb: pricenumb},
cache:false,
success: function(response){
// Things to do on success
},
error: function(error){
// Error handling in case of error
}
});
These values you passed can be used in the file forumdisplay.php with $_POST['price'] and $_POST['pricenumb']. The name inside the $_POST is the propsName inside data props in ajax function.

Changes done in ajax success not loading in page without refreshing

I have an ajax block in javascript, which does a few operations, and then changes a text box in my page.
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
var content_id = "count_" + count_id;
var votes = $(content_id ).val();
$(upvotes_id).html(votes);
//window.location.reload();
}
});
The content value is reflected only after I refresh the page. I tried setting cache parameter as false and alse the same in ajaxSetup when document is ready. Still the changes arent getting reflected. Please help.
It looks like your return variable 'data' isn't being referenced in the success function. As pointed out elsewhere, also missing an id or class reference. Try this (or any other relevant variables):
var content_id = "#count_" + data.count_id;
add hash to get value like
var votes = $('#'+content_id ).val();
i think you forgot add "#" before the id
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
var content_id = "count_" + count_id;
var votes = $('#'+content_id ).val(); // add hash for id or . for class
$(upvotes_id).html(votes);
//window.location.reload();
}
});
I am assuming upvotes_id is either id or class. Use $("#upvotes_id").html(votes) or $(".upvotes_id").html(votes) instead.same in the case of "content_id" .
I can see few issues with your code like- no '#' for referring an element.
corrections:
$.ajax({
type: "POST",
url: "/post_to_page/",
data: JSON.stringify({'titleid': parseInt(count_id)}),
cache: false,
success: function(data){
**var content_id = "#count_" + count_id;**
var votes = $(content_id ).val();
$(upvotes_id).html(votes);
//window.location.reload();
}
});
Also you have not mentioned how you are getting upvotes_id. Use # there too. You are not using the response returned in success method. Is it intended?

Image does not update when appending newly inserted row using jquery ajax

I want to insert data using ajax and show that newly inserted data in a div, but the record (i.e. image and name ) does not get updated it.
I don't want to reload page, the newly entered record should be shown without page reload, but it shows only the initial name and image.
I can't understand whats the problem. Please help. Following is the code i am using static data which is stored in a variable as an example:
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
d = new Date();
var img_name='amit.png'+'?'+d.getTime();
var s_name='Ashish';
$('#main').prepend('<img alt="client" id="p_img"><h1>'+s_name+'</h1>');
$('#p_img').attr("src", "image/Amit.png");
},
error: function (error)
{
}
});
Shouldn't the src attribute use the response/variable/generated file name?
Like this:
$('#p_img').attr("src", '/image/' + img_name);
Instead of this:
$('#p_img').attr("src", "image/Amit.png");
It can be two reasons :
the image you are prepending to the DOM is not yet in the DOM when you are trying to add the src
or the src is not existing (should be an absolute or relative path)
Try to prepend the image with the src
$('#main').prepend('<img alt="client" src="ABSOLUTE_OR_RELATIVE_PATH/image/Amit.png"><h1>Amit</h1>');
Also there is no need to create a variable s_name which you only use once.
you can done it easily by returing List of data and populating the div with ajax success result.
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
// in data you are getting your result ...
// now for ease split json format data and store in list
// m not sure about your formate so m assuming at first index it
//should be image URL so..
var res = data.split(",");
var imgSrc = res[0];
$('#main').prepend('<img alt="client" id="p_img"/>');
$('#p_img').attr("src", imgSrc);
},
error: function (error)
{
}
});

Pass Array and String from Javascript to PHP with AJAX

I have the following ajax call.
My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123
I want to grab the addList in my PHP file as
$_POST['list'] is an array with values Sports, Cars, Outdoor
$_POST['new_list'] is a string 123123
But I couldnt convert the POST string into right forms.
I can create arrays/loops in both sides but it didnt feel right.
Whats the convenient way of doing it?
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-list&nonce="+ajax_var.nonce+"&post_list=&post_id="+post_id+"&" + addList,
success: function(count){
alert("done");
}
});
Any help will be appreciated. thanks!
try using followig code.
you just neeed to locate your form if and url to pass values to :
var form = new FormData($('#form_id')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
this will pass all form element automatically.
Working and tested code.
When you pass variable with the ajax method from jQuery, you can pass array like this :
jQuery
var myArray = newArray();
myArray.push("data1");
myString = "data2";
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: {array:myArray, param2:myString},
^name ^value
success: function(count){
alert("done");
}
});
PHP
echo $_POST['array'][0]; // data1
echo $_POST['param2']; // data2
Change your addList variable to this:
list[]=Sports&list[]=Cars&list[]=Outdoor&new_list=123123
PHP will parse the items named list[] into an array, and you'll find the values as $_POST['list'][0],$_POST['list'][1],$_POST['list'][2]

Categories