30702

Insert into database using onclick function

I'm developing a kind of question search engine based on Course wise, Subject wise by entering the keyword or question. Here I am querying the database based on search term against 3 tables namely table_one, table_two, and table_three. Code as follows

<?php if(isset($_GET['submit'])) { $query = $_GET['query']; $query = htmlspecialchars($query); $query = mysqli_escape_string($link,$query); $searchTerms = explode(' ', $query); $searchTermBits = array(); foreach ($searchTerms as $term) { $term = trim($term); if (!empty($term)) { $searchTermBits[] = "question LIKE '%$term%'"; } } $subject_id = $_GET['subject']; $course_id = $_GET['course']; $min_length = 1; if(strlen($query) >= $min_length) { $res = "SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_one WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%') UNION ALL SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_two WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%') UNION ALL SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_three WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')"; $raw_results = mysqli_query($link,$res) or die (mysqli_error()); if(mysqli_num_rows($raw_results) > 0) { echo "<h3 style='text-align:center;color:#3366CC'><span style='color:#000000'>Search Results For : </span> $query </h3>"; while($results = mysqli_fetch_array($raw_results)) { echo "<div class='content'>"; echo"<h4 id=".$results['id'].">" .preg_replace("/".preg_quote($query, "/")."/i", "<span class=\"highlight\">$query</span>", $results['question']) . "</h4>"; echo"<p id=".$results['id']."><span style='padding-left:20px'>option A : " .$results['option_a']."</span> <br><span style='padding-left:20px'> option B : ".$results['option_b']."</span><br/><span style='padding-left:20px'>option C : ".$results['option_c']. "</span><br><span style='padding-left:20px'>option D : ".$results['option_d']."</span><br><span style='padding-left:20px'> option E : ".$results['option_e']."</span><br><span style='color:#253E66;font-weight:bold;padding-left:20px'>Correct Ans : ".$results['correct_ans']. "</span><br><span style='padding-left:20px'>Question Year : ".$results['question_year']."</span><br><span style='padding-left:20px'>Contributor : ".$results['contributor']."</span><br /> <a onclick=addQuestion('".$results['id']."') href='#'><span class='button'>Add to Question Bank</span></a></p>"; echo "</div>"; } } else{ echo "<span style='height:21px;syle=background-color: #F1F0FF;font-size:25px;color:#CC0000'>Your search - $query - did not match any queries.</span> "; } } } ?>

I'm Calling the following addQuestion() function when i click the Add to Question Bank link.

<script> function addQuestion(val) { var conf=confirm("Are you sure you want to add this question to Question Bank") if(conf){ //Here I Want some code to update my database. } } </script>

The script above displaying confirmation box when i click the button, My Question is, After confirmation I want to insert my question into the new table in the database and display message like "Question added" in front of the question permanently as i know i can't write PHP inside Jquery function Any help may appreciated.

Answer1:

You can achieve this by including the ajax. put the ajax code which may looks like the following:

if(conf){ $.ajax({ type: "POST", url: "$$phpfilepath", data: {param:'$$value'}, success: function(data) { // do the message display code } }); }

Don't forget to include the jquery cdn link in the head tag of the html page.

Answer2:

you need to send an ajax request. you need to send it either by a post or get method to a php script that will return json so you can be updated on the page with results. the answer above has an example ajax script sent with a post method: data needs to be sielized if you are submitting it via form or an array.

this should help you http://www.w3schools.com/php/php_ajax_database.asp https://api.jquery.com/serialize/

Answer3:

Onclick - You need to do that with ajax. So basically, you need PHP plus javascript involved. You can use Jquery of similar JS library for easy ajax support.

Just and example with jquery library version 1.11.2 how to include:

<head> <script src="jquery-1.11.2.min.js"></script> </head>

For example, if this is your input field you want to save and button for submitting:

<input id="title" name="title" /> <input type="submit" value="Save">

Change it to button and give it javascript save() function (can be any name you give).

<input type="button" onclick="save($('#title').val());" value="Save">

In this example, I added 1 param to that save function, which is supposed to grab a value from html input filed with id "title". On this page, there that html is, you need to include mentioned jquery(or similar) library and also include piece of javascript function for generating ajax request, which is named "save" here.

If you included jquery library, you must call javascript function for saving your data before your tag:

<script type"text/javascript"> function save(){ $.ajax({ type: "POST", url: "yourpath/yourfile.php", data: {title: title}, success: function(data) { alert("Ajax save executed!"); } }); } </script>

When javascript function you named save() will execute, it will send POST request to yourpath/yourfile.php

There, you can easily get your POST data by in yourpath/yourfile.php:

if(isset($_POST['title'])){ // do something with POST data, save in db.. (make sure to include security when inserting to db) }

If you want to send it with GET, you easily replace <strong>POST</strong> with <strong>GET</strong>:

function save(){ $.ajax({ type: "GET",

and also in .php file you write:

if(isset($_GET['title'])){ // do something with POST data, save in db.. (make sure to include security when inserting to db) }

Recommend

  • How to solve Preg_match warning? [duplicate]
  • Calculate the total sum for each category from a text file
  • preg_match exact number
  • Remove line of file1 that exist on file2
  • Trying to upload user id to database, Session returning userid as null?
  • unserialize multiple array and echo by passing more than 2 parameter to arraycombine method
  • php file download headers
  • Infer constraints for both if and else of type equality
  • How to replace a contour (rectangle) in an image with a new image using Python?
  • PHP MySQL generating unique random number
  • Why do I have to use LD_PRELOAD for libcl.2 to use XML::LibXML::Common on HP/UX?
  • How to realize with WinForms in C# something like an image with map areas in a homepage (at hooverin
  • Why must we Forward Declare a class and include the corresponding header file in a header file
  • Android Ripple: How do other apps make their ripple so transparent without affecting the original co
  • text-align justify, cannot override
  • Angular - routerLinkActive and queryParams handling
  • Is it possible to get the word under the mouse cursor in a ``?
  • Google Maps api v3 get start and end coordinates of a street
  • Where can I find tomesh.c?
  • Randomizing -and remembering that randomisation- multiple choice questions in php
  • Julia: How to give multiple workers access to functions that are 'include(…)' into a modul
  • Image map in Flex
  • How can I display the parent menu item's description using Wordpress walkers?
  • Selenium to click on a javascript button corresponding to a text
  • How does document.ready work with angular element directives?
  • MySQL Order by column = x, column asc?
  • Is playing sound in Javascript performance heavy?
  • Google Custom Search with transparent background
  • FileReader+canvas image loading problem
  • Deselecting radio buttons while keeping the View Model in synch
  • What is Eclipse's Declaration View used for?
  • Why HTML5 Canvas with a larger size stretch a drawn line?
  • Knitr HTML Loop - Some HTML output, some R output
  • Can I make an Android app that runs a web view in Chrome 39?
  • Can a Chrome extension content script make an jQuery AJAX request for an html file that is itself a
  • Web-crawler for facebook in python
  • Java static initializers and reflection
  • unknown Exception android
  • Observable and ngFor in Angular 2
  • Unable to use reactive element in my shiny app