I have some code and it is for sending comments to database.
And I have jquery and ajax code:
<script type="text/javascript">
$(document).ready(function() {
$('#comm1').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var comment = $('#comm1').val();
var fromstatid = '<?php echo $status->fromid; ?>';
var status = '<?php echo $status->id;?>';
var fromid = '<?php echo $frid; ?>';
$.ajax({
method: "POST",
url: "d/includes/counts.php",
data: {u: fromid, status: status, comment: comment, fus: fromstatid},
success: function(status) {
$('#comm1').val('');
}
});
};
});
});
</script>
#comm1 is textarea for comment ..
For php I have like basic output from database and the problem is that my jquery use only last output from database as value. In other words where ever I type a comment it send to database for the last output. It works if I have button for Reply and then it sends me to new page or something where I can limit output from database to 1 or to only that where I want to comment. But can I do it here on the page where are all comments... Also I was trying to set id as some word + php id from database for that output but it seem like when I add this to jquery code noting going to work....
The code I tried is : $("#something<?php echo $status->id; ?>").keypress.....
It stops the script it looks like the whole script is not working...
I asked similar question but no one answered me the right question... Also I was thinking of can I like make foreach in jquery here on this code.. And say for each output do something. I really don't know why it use only last output on page as value but it will help a lot if someone have some explanation?
EDITED:
Or do I need to echo for each output the jquery code?
UPDATE:
Tried by echoing the whole jquery code and it is not working....
NEW:
As you asked I have d/includes/counts.php file and the index.php
Inside counts.php i just input in database values send via ajax...
Inside index.php I said I have basic foreach database output to echo something like $status->text and for comment to echo textarea where I can type comment for text... Code is too long and I dont have problems with that code I have problems with connecting jquery code to all outputs not only last one....
Why does my var status = '<?php echo $status->id; ?>'; AND var fromstatid = '<?php echo $status->fromid; ?>'; use only last output values? Can I make some var inside echo for each output and use that var here in code to navigate which one is commented on?
I founded that also the script work only on one output like if I try to comment on the other one and press ENTER it wont work....
You must know that only the last output of the PHP file will be retrieved. So I'm wondering what did you output in the PHP file ? Can you post the PHP code please ? (Sorry, for answering here but not enough points to comment).
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to read the meta-description of another website as a string in JavaScript. I tried using CORS but get an error saying "No 'Access-Control-Allow-Origin' header is present on the requested resource."
I was suggested that I could use PHP to do this. I don't know PHP and need some help. How do I call a PHP function to read source of some webpage on a different domain and then feed the output to a JavaScript function as a string?
Here is a simple, straight-forward way to help you get what you want. Try it out first... Paste the entire code below on an Empty PHP File and run it. No real need for Ajax in this Simple Scenario. So you have 2 Options:
OPTION NR. 1
<?php
//SIMPLY CHANGE THE URL TO THE URL YOU DESIRE
$siteURL = "https://yahoo.com/";
$siteContent = file_get_contents($siteURL);
$metaRx = "#<meta .*description.*>$#m";
preg_match($metaRx, $siteContent, $metaMatches);
$metaString = str_replace("'", "\'", $metaMatches[0]);
//DUMP THE ARRAY OF MATCHES TO THE SCREEN... JUST TO EXPLORE THE RESULTS
var_dump($metaMatches);
?>
<script type="text/javascript">
//EXPOSE THE META TO YOUR JAVASCRIPT USING A GLOBAL VARIABLE (FOR EXAMPLE).
var SITE_META_DESC = '<?php echo $metaString; ?>';
// DUMP VALUE TO THE SCREEN USING ALERT....
alert(SITE_META_DESC);
</script>
Here is another alternative... it is concise and simple; however it may not give you the result you want:
OPTION NR. 2
<?php
//SIMPLY CHANGE THE URL TO THE URL YOU DESIRE
$metaTags = get_meta_tags('https://yahoo.com/');
$metaDescription = $metaTags["description"];
var_dump($metaDescription);
//USING A DATA-SOURCE ARRAY:
$arrURLs = array("http://sbb.ch", "http://alibabaexpress.com", "https://yahoo.com", "http://badoo.com" );
$arrMetaDescs = array();
// LOOP THROUGH THE $arrURLs AND GET THE META
// AND STORE THE RESULT IN AN ARRAY TOO.
foreach($arrURLs as $url){
//IF YOU WANT YOU COULD USE THE URL AS KEY FOR EASIER IDENTIFICATION
try{
$metaTags = get_meta_tags($url);
if($metaTags){
$key = preg_replace("&(https:\/\/|http:\/\/|www\.|\/.*$)?&", "", $url);
$arrMetaDescs[$key] = $metaTags["description"];
}
}catch(Exception $e){
}
}
var_dump($arrMetaDescs);
?>
<script type="text/javascript">
//EXPOSE THE META TO YOUR JAVASCRIPT USING A GLOBAL VARIABLE (FOR EXAMPLE).
var SITE_META_DESC = '<?php echo $metaDescription; ?>';
alert(SITE_META_DESC);
// IN THE CASE OF ARRAY-BASED META-EXTRACTION,
// STORE THE META VALUES IN JSON FORMAT FOR JAVASCRIPT
var ARR_META_DESC_EXTRACT = '<?php echo json_encode($arrMetaDescs); ?>';
console.log(ARR_META_DESC_EXTRACT);
</script>
Here's one way to do it:
Set up a page source_getter.php on your server and include the following code (from this answer):
$html = file_get_contents('your_url_here');
echo $html;
If you're using jQuery, run a request like this:
$.ajax({
url : 'source_getter.php',
success : function (result) {
doSomethingWithResult(result);
// result will equal $html from your PHP code
},
error : function () {
alert("error");
}
})
I haven't tested this code specifically but it should work just fine.
This is probebly the easy way to do it:
<?php
// Get Meta Tags from the given URL
$tags = get_meta_tags('http://www.example.com');
?>
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var urlMetaDesc = "<?php echo $tags['description']; ?>";
alert(urlMetaDesc);
</script>
</head>
<body>
</body>
</html>
Keep in mind though that if a website didn't set the meta-description tag, nothing will be returned and no alert will be shown.
I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>
i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?
I have a little contact form, where I would like to ask the user to calculate and enter the correct value in order to prevent spam. Now, when the send button is clicked, I fire a php script, where I change the calculation values. I would like to echo these values and show them as the new placeholder in case of both, success, as well as failure.
$("#send_button").click(function() {
var url = "contact.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
$("#form_info_label").css('color','#0ed68d');
$("#form_info_label").text(data);
$("#user_answer").attr("placeholder",txt);
},
error: function(data) {
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
alert(txt);
$("#form_info_label").css('color','#f2275e');
$("#form_info_label").text("Error. Please try again.");
$("#user_answer").removeAttr('value');
$("#user_answer").attr("placeholder",txt);
}
});
return false; // avoid to execute the actual submit of the form.
});
However my placeholder ends up not interpreting it as php code, but just simply copies the text. So my placeholder then ends up displaying:
<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>
I ended up returning a json-encoded array with my desired values from php back to javascript and parsed the response there.
You'll need PHP tags
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier'; ?>";
You actually have it right in the error handler, so you probably just forgot, and now you've edited the question to include them ?
If you have PHP tags, and it's still not being parsed, the file the javascript is in is not being parsed by PHP.
Remember on comuputers to use the * for multiply things, not the x.
And it´s also not clear, what your function "Calculate($param)" does, but usally you don´t need a function for adding one variable to another. But the brackets still needed...
In my case the PHP tag was not interpreted by js either. A solution I found was:
In my php file I defined the variable in a non-visible div:
?>
<div id="first_num" style="display: none">
<?php echo $first_num; ?>
</div>
<?php
In the jquery file I read the div value like this:
var first_num= $("#first_num").text().trim();
First of all what adeneo already said: .js files are not parsed by PHP.
Secondly PHP variables will not be expanded when they occur in single quoted strings. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
You should use either double quotes or
echo 'Spam protection: Calculate ('.$first_num.' + '.$second_num.') x '.$multiplier;
I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>
Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!
I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?
I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data