I have a website, where once a button is clicked it will trigger some javascript actions. I want to get some data via a php script i have written. I am using this method:
$.get("get_uni_info.php?addressToSearch=" + address, address, function(myData)
{
$.each(myData, function(key, value)
{
console.info(value);
})
}, "json");
Inside the php code I am trying to get the value "address" to be able to search my database and send back some data but everything I just get nothing returned. I have test to the php code and it will return data if artificial measures are put in place so I can tell its not my PHP code.
Am i going wrong in my jQuery?
Possibly the problem is in usage of $.get method.
You should write either
$.get("get_uni_info.php?addressToSearch=" + address, function(myData) {
...
}, "json");
or
$.get("get_uni_info.php", { addressToSearch : address }, function(myData) {
...
}, "json");
PHP code should handle address as:
$address = $_GET['addressToSearch'];
EDIT: If this does not help, we need to have a look at your PHP code (the response part precisely) to know where is the exact problem.
Related
I have an html page with a search field that can have a name typed in which returns a table of Names and IDs (from Steam, specifically). The leftmost column, the names, are hyperlinks that I want to, when clicked, take the user to said player's profile (profile.php) and I want to send the "name" and "steamid" to that profile.php when the name link is clicked, so essentially sending two JS variables from one page to the PHP backend of another page.
I'm new to ajax and it seems that that is the only way to use it, so after researching for a while this is what I've come to:
$(document).ready(function() {
$('#playerList td').click(function(e) {
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function() {
console.log('success');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
Everything up to the ajax definition works as I want, and I want to send the "name" and "steamid" vars to profile.php, but I don't think I'm understanding how ajax works. My understanding is that ajax can "post" information (usually a json object from what I've seen) to a url, but can also return information from a page? That's where I'm a bit confused and am wondering if I'm just using it wrong.
As a quick note: playerList is my table's id.
When I click the hyperlink, it takes me to profile.php, which is what I want, but php's $_POST[] array seems to be empty/null as I get the "undefined array key" error when trying to access both 'playersSteamID' and 'playersName'. var_dump() returns NULL as well, so I'm wondering if there's a problem with the way the data{} field is being sent in the ajax. I'm still very new to this so any help would be much appreciated.
Update: How I'm accessing the variables in profile.php
<?php
echo var_dump($_POST['playersName']);
echo var_dump($_POST['playersSteamID']);
if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}
?>
The rest of profile.php is taking those variables and running several sql queries and building a table which work given proper variables, but since the $_POST[] is empty I can't continue past the above point as the first two lines return null and the conditionals are never true since isset() is false.
The ajax is used to, post or get parameters/info from/to URL without redirecting/refreshing/navigating to a particular page.
Please note down without redirecting/refreshing/navigating
In your case you want to send 2 parameters to profile.php and you also want to navigate to it, yes..? but for that you are using Ajax, which is not a right choice.
Solutions:-
-> Use normal form submission kinda thing, and post the parameters to profile.php, in this case you will get redirect to profile.php and can expect proper functionality.
You can use a normal form with a submit button {pretty normal}, or use a custom function to submit form with some further work if need to be done {form validation}.
you function would look like this...
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
//Do some other stuffs
document.forms['someform'].submit();//submitting the form here
}
});
});
The rest in profile.php remains same.
-> If you really wanna use ajax do following.
Ajax are meant for dynamic web designing, pretty useful to grab data from server without refreshing the page.
You should change the way your response is in profile.php file.
for eg:-
<?php
if(isset($_POST['playersSteamID'])){
$name = $_POST['playersName'];
$id = $_POST['playersSteamID'];
//Do your stuff here db query whatever
//Here echo out the needed html/json response.
echo "<h3>".$name."</h3>";
echo "<h4>".$playersSteamID."</h4>";
}
?>
The response {from: echo} will be available in data of function(data) in ajax success, you can use this data in whatever you want and however you want.
for eg:-
success: function(data){
console.log(data);//for debugging
$('#mydiv').html(data);//appending the response.
}
-> Use php sessions and store steamID in sesssion variable, very useful if you have some login functionality in your website.
$_SESSION['steamID'] = //the steamID here;
This variable can be used anywhere in site use by calling session_start() in the page, you want to use sessions.
for eg:-
click here to view your profile
profile.php
<?php
session_start();
$id = $_SESSION['steamID'];
//echo var_dump($_POST['playersName']);
//echo var_dump($_POST['playersSteamID']);
/*if (isset($_POST['playersName'])) {
console_log("PLAYER_NAME => ".$_POST['playersName']);
}
if (isset($_POST['playersSteamID'])) {
console_log("PLAYER_STEAMID => ".$_POST['playersSteamID']);
}*/
echo $id;
//Do your work here......
?>
For any queries comment down.
A hyperlink may be causing the page navigation, which you dont want.
Page navigation will make a get request but your endpoint is expecting a post request.
You can stop the navigation by setting the href to # or by removing the <a> altogether.
You could also try calling the preventDefault on the event object.
$(document).ready(function() {
$('#playerList td').click(function(e) {
e.preventDefault();
if ($(this).text() == $(this).closest('tr').children('td:first').text()) {
console.log($(this).text());
var name = $(this).text();
var steamid = $(this).closest('tr').children('td:nth-child(2)').text();
$.ajax({
url: 'profile.php',
method: 'POST',
data: {
playersSteamID : steamid,
playersName : name
},
success: function(data) {
console.log('success', data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
})
}
});
});
Iam trying to post an Javascript Object via php, but i cant get the value in PHP, iam using laravel framework.
my array,
[type: "sadf", level: "sadfasdf"]
javascript code,
var data_push = Array();
$('form').on('change', 'select, textarea, input', function(t,s){
var key = $(this).attr('id');
var value = $(this).val();
data_push[key] = value;
});
$("#submit").click(function(){
$.post("{!! URL::to('test') !!}", {
_token : tempcsrf,
req_data : data_push
},
function (resp, textStatus, jqXHR) {
alert(resp);
});
});
php code,
public function workbook_save(Request $request_data)
{
$require_data = $request_data->req_data;
print_r($require_data);
}
Tried also JSON.stringfy(data_push) ,json_decode but no luck, i cant get the Javascript object in php, donno what iam doing wrong here, pls advice.
This is what your JS does:
Creates an array
Sets up an event handler to populate the array when things change in the form
Posts the (empty) array to the server
Later on, things will change in the form and data will be put in the array.
The server knows nothing about this because you already sent its contents.
You need to change your logic so you only make the POST request when you are ready to send the data.
If I have a validation tag in my asp.net mvc application for a text field called search, can I plug into it using jquery/javascript to get it to trigger if certain logic is performed? How would I do that?
It looks something like this
#Html.TextBox("SearchQuery", other stuff here, other)
#Html.ValidationMessageFor("SearchQuery")
Say I want to trigger the validation message to show if this occurs
$('form').submit( function (e) {
e.preventDefault(e);
var results = GetLocation();
if (results) {
this.submit();
} else {
// trigger validation message and display "can't find results"
}
});
Please note that I don't think I need to validate here, I just want to show a message where the validation message would be if I did validate
As far as i understand your question, for custom messages coming from server you need to send the object to server and then get the response from it.
You can perform it with an ajax call for example:
$.ajax({
url : 'example.com',
type: 'POST',
data : results,
success:function(datafromserver)
{
$('.resultState').html(datafromserver);
}
});
Another thing if do validation first in the client and then send (and check again in server), in this case remember var result can always be true if the getLocation functions returns anything (such as string , object etc...) so in this case print it with console.log and take a look if is it an object (f example: data.x === none or 'no coordinates' just evaluate it correctly and you can avoid ajax.
Hope helped!
Regards
This post by #BenjaminRH (How to change/edit the text of a paragraph/div using jQuery?) provides exactly the sort of functionality I'm trying to build on.
By clicking on a button, a new paragraph is created on the page, which can be edited and saved to the page.
I want to save it to a database. When I look at the page source after editing, I don't see the changes there, which doesn't surprise me... but I don't know where to "capture" the changed text so that I can validate and post to mySQL.
JQuery is a javascript library - which runs client side. If you wanted to save that data into the database - you would have to send it to the server (php/asp/mvc etc) using ajax and then insert the data into the database.
See the jquery Ajax function for details on how to accomplish sending data asynchronously.
Create the data in javascript that you want to show and save in database.
Wrap the data in JSON and use ajax to POST the data to the server side code
Server-side retrieve the posted data and parse it into something usable
Server-side write a script to insert the data into the database.
Handle any errors that may occur.
Pseudo-code:
// step 1
var someData = 'this is my data';
$("#myDiv").html(someData);
// step 2
$.ajax({
type: "POST",
dataType: 'json', // <-- if the data is complex and needs to be object-oriented
url: "some.php", // <-- that is the file that will handle the post server-side.
data: JSON.stringify({ someData }) // <-- just pass someData if your data is not complex
})
.always(function(jqXHR, textStatus) {
if (textStatus != "success") {
// step 5: handle error.
alert("Error: " + jqXHR.statusText); //error is always called .statusText
} else {
alert("Success: " + jqXHR.response); //might not always be named .response
}});
OK, I've managed to solve it for myself, without using ajax. I took the example from (How to change/edit the text of a paragraph/div using jQuery?) and modified it by placing the elements in an (html) form.
The second modification was to use <textarea> elements, not <p> elements, as <p> elements cannot be posted.
As #caspian pointed out (in the comments) those two steps do populate the $_POST array and away we go.
I have a script for updating a database table. I need to return a JSON array and to update some tables with JQUERY.
my php script:
$update = mysql_query("UPDATE PLD_SEARCHES SET STATUS = 1, TOTAL_RESULTS = ".$scrapper->getTotalResults().",RESULTS = $resultCounter WHERE ID = ".$searchId);
$output = array("status"=>"COMPLETED","results"=>$resultCounter,"totalResults"=>$scrapper->getTotalResults());
echo json_encode($output);
jquery code:
$("button").live("click", function(event) {
event.preventDefault();
$.getJSON("startsearch.php", {
searchId: $(this).val()
}, function(data) {
alert(data[0].status);
});
now ...the problem is that if i use $.post("startsearch.php",{ searchId: $(this).val() }, function(data)) the script gets executed and i get a nice alert with value undefined. if i add the parameter "json" the script doesn't get executed anymore. I tried to use getJSON but again the same problem.
Anybody has any ideas? I am desperate...this has been bugging me for almost a week and I still haven't managed to solve it.
In your php file make sure to set the correct content type:
header("Content-type: application/json; charset=utf-8");
so that jquery can correctly eval the response into a json object.
You can get to your response data as follows:
alert(data.status);
alert(data.results);
alert(data.totalResults);
please don't use alert, install firebug into your firefox or enable the javascript console in chrome or safari. after that you can use console.log(data);
my guess is that data isn't an array. also have a look at the each() exmaple on the jquery docs http://docs.jquery.com/Ajax/jQuery.getJSON
Well, I'm trusting json2.js to parse the json data returned from AJAX request. You can download it from http://json.org. This library provide a better way to parse any string, and will throw an exception if the sting is not in json.
I always write my AJAX request like this:
$.post(URL,
{ PARAM },
function(data){
try {
var r = JSON.parse(data);
//this for your code above
alert (r.status); //should be 'COMPLETED'
}
catch (e) {
//data is not in json format, or there are another exception in try block
//do something about it
alert('Exception occured, please check the data!');
}
});
When processing json, the array in php will become a variable member in json. So if in your php it is $output['status'], then in json, it will be r.status.