JQuery AJAX request not working. - javascript

I am using AJAX for the first time and I am not sure if I have the correct syntax down. Basically I have a method in the behind code that takes in 2 string parameters and executes an updates the users password. But it keeps coming back as failed.
Here is my current asp button:
<td><asp:Button ID="Button1" runat="server" Text="Add Password" alt="Add Password" /></td>
This is the code that executes once the user hits the Add Password button on the form:
$("#edit_password_form").submit(function (e) {
e.preventDefault();
var finalValue = value2.value;
<%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%>
var custNoString = <%=inputCust%>
$.ajax({
url: 'reciept.aspx/Button1_Click',
method: 'post',
contentType: 'application/json',
data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}',
success: function(){
alert("The function worked correctly");
},
error:function(){ alert("the function did not succeed");}
});
});;
Any ideas on why it could be failing? Mayb I am missing an ajax key or my syntax could be off.
Let me know! Thanks.

Data parameters need properly created JSON. You are missing out on some single quotes here and there.
Instead of manually creating the JSON string, try creating an object first, then stringify it for data. Refer to the code below:
$("#edit_password_form").submit(function (e) {
e.preventDefault();
var finalValue = value2.value;
<%string inputCust = Session[SessionKey.CUSTOMER_ID].ToString();%>
var custNoString = <%=inputCust%>
var dataObj = {};
dataObj.custID = custNoString;
dataObj.tempPass2 = finalValue;
$.ajax({
url: 'reciept.aspx/Button1_Click',
method: 'post',
contentType: 'application/json',
data: JSON.stringify(dataObj),
success: function(){
alert("The function worked correctly");
},
error:function(){ alert("the function did not succeed");}
});
});;

it is not correct syntax to post data: data: '{custID:' + custNoString + 'tempPass2:' + finalValue + '}'
try to pass your data by json format this way data: { custID: custNoString, tempPass2: finalValue }
otherwise it should not work .
more check this link http://www.json.org/JSONRequest.html

(Posted as answer on behalf of the OP).
This is what ended up working for me:
// Create the data object for the 2 parameters for the c# Method
var dataObj = { custID1: custNoString, tempPass2: finalValue };
// AJAX request for run the function
$.ajax({
type: 'post',
url: 'reciept.aspx/Button1_Click',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(dataObj),
success: function(){
alert("The function worked correctly");
},
error:function(){ alert("the function did not succeed");}
});
Creating the data object first was the key. Thank you for all your help and suggestions!

Related

In Ajax response my if condition is not working

Check the jquery code bellow. Here after process post request the response returning no_file_found but if condition not meeting and not hitting alert(). Whats wrong i am doing here?
$("#btnFoo").on("click", function () {
var file_data = $('#formUploadImg').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('ProId', $(this).attr("img-upload-product-id"));
$.ajax({
url: '/mycontroller/upload',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
console.log(typeof response);//it returns string
if (response == "no_file_found") {
alert("this not hits");//this alert not hits
}
},
error: function (response) {
alert("Error");
}
});
});
Please note i am using c# mvc5 and the response is comming from mvc5 controller. Mvc5 example bellow:
[HttpPost]
public JsonResult upload()
{
return Json("no_file_found");
}
You need to use .trim() function to make sure all unseen spaces are removed from the response to be able to match the exact comparison== of no_file_found.
Edit: The reason it is not working is because you are returning "no_file_found" with double quotes "" added. But on the front end you are checking simply no_file_found - You need to use replace function to make sure all the double quotes are deleted from the response.
var response = '"no_file_found"';
if (response.replace(/["']/g, "").trim() == "no_file_found") {
alert("this hits"); //this alert hits
}
The problem here is that you are returning a Json value - but your ajax is set to have a dataType: 'text'.
If you change dataType: 'json' all works as expeceted.

Passing javascript variables(array) to php

I have a function where the user inputs are stored in a variable in javascript.
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
var bookseats = seat;
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
});
});
When the user clicks on the #btnsubmit button, I want to send this variable(actually an array) to a PHP file named confirm.php.
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
In my PHP file, I've written the code to get the sent variable as follows.
$bookseats = "";
if(isset($_POST['bookseats']))
{
$bookseats = $_POST["bookseats"];
print_r($bookseats);
}
When executed, nothing happens in the PHP file(doesn't print the bookseats).Is there something wrong with this code?
You're not using a "success" callback to get the output of the PHP code. See success callback
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats},
success: function(data) {
console.log(data); // or alert(data);
}
});
Also, I think you should stop the propagation of the default behavior of the button, to prevent the browser to redirect the page to the form's action URL:
$('#btnsubmit').click(function(ev) {
ev.preventDefault();
As #Malovich pointed out, as of jQuery 1.8, you could also use .then():
$.ajax({
type: 'POST',
url: 'confirm.php',
data: {'bookseats': bookseats}
}).then(function(data) {
console.log(data); // or alert(data);
}, function(){
console.log("Error");
});

pass data($post) to php file using javascript without callback

I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});

Access Javascript variable in php in same page

Hi I am facing problem with json data. Here is my js code.
<script>
$(function(){
$.ajax({
url:"http://example.com/salary?from=USD&to=GBP",
dataType: 'jsonp',
success:function(json){
alert(json['to']);
},
error:function(){
alert("Error");
},
});
});
</script>
I want to use json data in PHP in same page.
I know that you cannot assign Javascript value to PHP variable.
Is there way to do this?
Or is possible to do similar task in php (Jquery Ajax cross domain) like above javascript code ?
Any help?
your js code
var my_json_obj = new Object();
my_json_obj .name = "Lanny";
my_json_obj .age = "25";
my_json_obj .location = "China";
var json_str = JSON.stringify(my_json_obj);
<script>
$(function(){
$.ajax({
type: "POST",
dataType: "json",
url: "my.php",
data: {
postData: json_str
},
success: function (data) { alert(data) },
eror: function (data) { alert(data) }
});
});
</script>
your my.php file
$postData=$_POST['postData'];
$my_obj=json_decode($postData,true);
$name=$my_obj['name'];
$age=$my_obj['age'];
$localtion=$my_obj['location'];
You could do that with AJAX.
You need a script, which will give javascript vars to the PHP Script, like:
var PHPFile = 'PHPFile.php?arg1=' + arg1 + '&arg2=' + arg2;
In the "PHPFile.php" you can access them by
$arg1 = $_GET["arg1"];
$arg2 = $_GET["arg2"];
Or you could do that with jquery $.ajax-> data, too.
You can access them by
$arg1 = $_POST["arg1"];
$arg2 = $_POST["arg2"];
Something like that:
result = $.ajax({
type: 'POST',
async: false,
url: 'PHPFile.php',
data: ({
arg1: arg1,
arg2: arg2
})
}).responseText;
alert(result);
EDIT:
If you want to do that with a json-object, try this:
json_decode();
http://www.php.net/manual/en/function.json-decode.php
http://www.php.net/manual/en/function.json-encode.php

Why do I get undefined when displaying value in a global variable?

I just don't get it, obviously. I've tried setters and getters, self invoking functions, you name it. It's like the click handler is returning a value but there's no way for me to keep it?
This is my code in the first file request.js
var testId = (function (inId) {
var citeId = inId;
return citeId;
})();
function mainAjax() {
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
});
}
var promise = mainAjax();
this is the code in my second file requestMain.js,
promise.done(function (json) {
var linkBase = "http://www.sciencebase.gov/catalog/item/";
var link = "";
var itemId = "";
var urlId = "";
$.each(json.items, function(i,item) {
link = linkBase + this.id;
$('#sbItems').append('<li><b>' + this.title + ' - </b>' + this.summary + '</li>');
});
$('#sbItems a').on('click', function (e) {
e.preventDefault();
var str = $(this).attr('id');
if (str.length == 7) {
itemId = str.slice(5,6);
}
else if (str.length == 8) {
itemId = str.slice(5,7);
}
testId = json.items[itemId].id;
alert(testId);
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
This webpage displays a list of links. A link could have some more information that I want displayed on a second webpage or it could have nothing. So when a link is clicked I need to store/save/keep the id from the link so that I can use it in the url to make another ajax request, because until I get the id the ajax request for the next page will have no idea what information to ask for.
For now I'm simply doing this
alert(testId);
But what I'm trying to do is this,
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' + testId + '?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
// Then doing something with json.something
testId would be used in the url and it would change depending on the link that was clicked on the previous page. The ajax call is totally dependent on the click event and is displayed on a separate webpage with new information.
And this would be in my third file requestCitation.js which currently gives me a big undefined when doing
alert(testId);
I think this is a scope issue, but how can I store the value returned from a click??? So that I can then use it globally? It seems like the value disappears outside of the scope as if there was never a click at all even thought I'm storing it in a variable?
the html for the first page has script tags for request.js and requestMain.js and the second page has script tags for request.js and requestCitation.js, so they can both see the variable testId.
Thanks for the help!
Here's the jsfiddle
These are the links and when a link is clicked
Your testId is holding the value retuned by the function you're calling, and since the function returns its argument and you've called it without arguments, it will be undefined:
var testId = (function (inId) {
var citeId = inId;
return citeId; //returns the argument
})(); // called with no argument
I'm not entirely sure what you're trying to do but if you're trying to keep the data returned from the AJAX request as a global variable, I would have thought it was done using something similar to the below.
E.g.
var promise = '';
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
data: '';
success: function(data){
promise = data;
}
});
But as I said I'm not understanding fully so I could be very wrong with my answer.

Categories

Resources